feat(resource): add ResourceKind interface, SkillKind/AgentKind implementations, and reserved name validation

Create internal/resource/ package with:
- kind.go: ResourceKind interface (Discover, ResolveName, FlatName,
  CreateLink, feature gates) + DiscoveredResource struct
- skill.go: SkillKind — directory-based discovery via SKILL.md,
  frontmatter name resolution, nested separator flatten (a/b → a__b)
- agent.go: AgentKind — single-file .md discovery with conventional
  excludes (README/LICENSE/CHANGELOG/SKILL.md), filename-based naming
  with frontmatter override, directory-strip flatten (dir/f.md → f.md)

Add "agents" to reservedSkillNames in validate.SkillName() to prevent
skill names conflicting with the agents source directory.

16 unit tests covering discovery, nested paths, name resolution,
flat name computation, feature gates, and edge cases.
This commit is contained in:
Willie
2026-04-07 18:05:39 +08:00
parent 7a010a9ae0
commit 5160ed5ffe
6 changed files with 633 additions and 0 deletions
+118
View File
@@ -0,0 +1,118 @@
package resource
import (
"os"
"path/filepath"
"strings"
"skillshare/internal/utils"
)
// AgentKind handles single-file .md agent resources.
type AgentKind struct{}
var _ ResourceKind = AgentKind{}
func (AgentKind) Kind() string { return "agent" }
// Discover scans sourceDir for .md files, excluding conventional files
// (README.md, LICENSE.md, etc.) and hidden files.
func (AgentKind) Discover(sourceDir string) ([]DiscoveredResource, error) {
walkRoot := utils.ResolveSymlink(sourceDir)
var resources []DiscoveredResource
err := filepath.Walk(walkRoot, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if info.IsDir() {
if info.Name() == ".git" || utils.IsHidden(info.Name()) && info.Name() != "." {
return filepath.SkipDir
}
return nil
}
// Only .md files
if !strings.HasSuffix(strings.ToLower(info.Name()), ".md") {
return nil
}
// Skip conventional excludes
if ConventionalExcludes[info.Name()] {
return nil
}
// Skip hidden files
if utils.IsHidden(info.Name()) {
return nil
}
relPath, relErr := filepath.Rel(walkRoot, path)
if relErr != nil {
return nil
}
relPath = strings.ReplaceAll(relPath, "\\", "/")
name := agentNameFromFile(path, info.Name())
isNested := strings.Contains(relPath, "/")
resources = append(resources, DiscoveredResource{
Name: name,
Kind: "agent",
RelPath: relPath,
AbsPath: path,
IsNested: isNested,
FlatName: AgentFlatName(relPath),
SourcePath: filepath.Join(sourceDir, relPath),
})
return nil
})
if err != nil {
return nil, err
}
return resources, nil
}
// agentNameFromFile resolves an agent name. Checks frontmatter name field
// first, falls back to filename without .md extension.
func agentNameFromFile(filePath, fileName string) string {
name := utils.ParseFrontmatterField(filePath, "name")
if name != "" {
return name
}
return strings.TrimSuffix(fileName, ".md")
}
// ResolveName extracts the agent name from an .md file.
// Checks frontmatter name field first, falls back to filename.
func (AgentKind) ResolveName(path string) string {
return agentNameFromFile(path, filepath.Base(path))
}
// FlatName strips directory prefixes, keeping only the filename.
// Example: "curriculum/math-tutor.md" → "math-tutor.md"
func (AgentKind) FlatName(relPath string) string {
return AgentFlatName(relPath)
}
// AgentFlatName is the standalone flat name computation for agents.
// Strips directory prefixes, keeping only the filename.
func AgentFlatName(relPath string) string {
relPath = strings.ReplaceAll(relPath, "\\", "/")
return filepath.Base(relPath)
}
// CreateLink creates a file symlink from dst pointing to src.
func (AgentKind) CreateLink(src, dst string) error {
return os.Symlink(src, dst)
}
func (AgentKind) SupportsAudit() bool { return true }
func (AgentKind) SupportsTrack() bool { return true }
func (AgentKind) SupportsCollect() bool { return true }
+59
View File
@@ -0,0 +1,59 @@
package resource
// ResourceKind encapsulates per-kind behavior for skills and agents.
// Each kind defines how resources are discovered, named, linked, and validated.
type ResourceKind interface {
// Kind returns the resource kind identifier ("skill" or "agent").
Kind() string
// Discover scans sourceDir and returns all resources found.
Discover(sourceDir string) ([]DiscoveredResource, error)
// ResolveName extracts the canonical name from a resource at the given path.
// For skills: reads SKILL.md frontmatter name field.
// For agents: uses filename, with optional frontmatter name override.
ResolveName(path string) string
// FlatName computes the flattened name used in target directories.
// For skills: path/to/skill → path__to__skill (nested separator).
// For agents: dir/file.md → file.md (directory prefix stripped).
FlatName(relPath string) string
// CreateLink creates a symlink from dst pointing to src.
// For skills: directory symlink. For agents: file symlink.
// Both use os.Symlink; the distinction is semantic (unit shape).
CreateLink(src, dst string) error
// SupportsAudit reports whether this kind supports security audit scanning.
SupportsAudit() bool
// SupportsTrack reports whether this kind supports tracked repo updates.
SupportsTrack() bool
// SupportsCollect reports whether this kind supports collecting from targets.
SupportsCollect() bool
}
// DiscoveredResource represents a resource found during source directory scan.
// Used for both skills and agents.
type DiscoveredResource struct {
Name string // Canonical name (from frontmatter or filename)
Kind string // "skill" or "agent"
RelPath string // Relative path from source root
AbsPath string // Full absolute path
IsNested bool // Whether this resource is inside a subdirectory
FlatName string // Flattened name for target directories
IsInRepo bool // Whether this resource is inside a tracked repo
Disabled bool // Whether this resource is ignored by ignore file
SourcePath string // Full path preserving caller's logical path (may differ from AbsPath if symlinked)
}
// ConventionalExcludes are filenames excluded from agent discovery.
var ConventionalExcludes = map[string]bool{
"README.md": true,
"CHANGELOG.md": true,
"LICENSE.md": true,
"HISTORY.md": true,
"SECURITY.md": true,
"SKILL.md": true,
}
+320
View File
@@ -0,0 +1,320 @@
package resource
import (
"os"
"path/filepath"
"testing"
)
// --- SkillKind tests ---
func TestSkillKind_Kind(t *testing.T) {
k := SkillKind{}
if k.Kind() != "skill" {
t.Errorf("SkillKind.Kind() = %q, want %q", k.Kind(), "skill")
}
}
func TestSkillKind_Discover(t *testing.T) {
dir := t.TempDir()
// Create two skills
os.MkdirAll(filepath.Join(dir, "my-skill"), 0o755)
os.WriteFile(filepath.Join(dir, "my-skill", "SKILL.md"), []byte("---\nname: my-skill\n---\n# Content"), 0o644)
os.MkdirAll(filepath.Join(dir, "another"), 0o755)
os.WriteFile(filepath.Join(dir, "another", "SKILL.md"), []byte("---\nname: another\n---\n# Content"), 0o644)
// Non-skill directory (no SKILL.md)
os.MkdirAll(filepath.Join(dir, "not-a-skill"), 0o755)
os.WriteFile(filepath.Join(dir, "not-a-skill", "README.md"), []byte("# Readme"), 0o644)
k := SkillKind{}
resources, err := k.Discover(dir)
if err != nil {
t.Fatalf("Discover error: %v", err)
}
if len(resources) != 2 {
t.Fatalf("expected 2 resources, got %d", len(resources))
}
names := map[string]bool{}
for _, r := range resources {
names[r.Name] = true
if r.Kind != "skill" {
t.Errorf("resource %q has Kind=%q, want %q", r.Name, r.Kind, "skill")
}
}
if !names["my-skill"] {
t.Error("expected to discover 'my-skill'")
}
if !names["another"] {
t.Error("expected to discover 'another'")
}
}
func TestSkillKind_Discover_Nested(t *testing.T) {
dir := t.TempDir()
os.MkdirAll(filepath.Join(dir, "_team", "frontend", "ui"), 0o755)
os.WriteFile(filepath.Join(dir, "_team", "frontend", "ui", "SKILL.md"), []byte("---\nname: ui\n---\n"), 0o644)
k := SkillKind{}
resources, err := k.Discover(dir)
if err != nil {
t.Fatalf("Discover error: %v", err)
}
if len(resources) != 1 {
t.Fatalf("expected 1 resource, got %d", len(resources))
}
r := resources[0]
if r.Name != "ui" {
t.Errorf("Name = %q, want %q", r.Name, "ui")
}
if r.FlatName != "_team__frontend__ui" {
t.Errorf("FlatName = %q, want %q", r.FlatName, "_team__frontend__ui")
}
if !r.IsNested {
t.Error("expected IsNested=true for nested skill")
}
if !r.IsInRepo {
t.Error("expected IsInRepo=true for _-prefixed dir")
}
}
func TestSkillKind_ResolveName_FromFrontmatter(t *testing.T) {
dir := t.TempDir()
skillDir := filepath.Join(dir, "my-skill")
os.MkdirAll(skillDir, 0o755)
os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte("---\nname: custom-name\n---\n"), 0o644)
k := SkillKind{}
name := k.ResolveName(skillDir)
if name != "custom-name" {
t.Errorf("ResolveName = %q, want %q", name, "custom-name")
}
}
func TestSkillKind_ResolveName_FallbackToDirName(t *testing.T) {
dir := t.TempDir()
skillDir := filepath.Join(dir, "fallback-skill")
os.MkdirAll(skillDir, 0o755)
os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte("---\n---\n"), 0o644)
k := SkillKind{}
name := k.ResolveName(skillDir)
if name != "fallback-skill" {
t.Errorf("ResolveName = %q, want %q", name, "fallback-skill")
}
}
func TestSkillKind_FlatName(t *testing.T) {
k := SkillKind{}
tests := []struct {
relPath string
want string
}{
{"my-skill", "my-skill"},
{"_team/frontend/ui", "_team__frontend__ui"},
}
for _, tt := range tests {
got := k.FlatName(tt.relPath)
if got != tt.want {
t.Errorf("FlatName(%q) = %q, want %q", tt.relPath, got, tt.want)
}
}
}
func TestSkillKind_FeatureGates(t *testing.T) {
k := SkillKind{}
if !k.SupportsAudit() {
t.Error("SkillKind should support audit")
}
if !k.SupportsTrack() {
t.Error("SkillKind should support track")
}
if !k.SupportsCollect() {
t.Error("SkillKind should support collect")
}
}
// --- AgentKind tests ---
func TestAgentKind_Kind(t *testing.T) {
k := AgentKind{}
if k.Kind() != "agent" {
t.Errorf("AgentKind.Kind() = %q, want %q", k.Kind(), "agent")
}
}
func TestAgentKind_Discover(t *testing.T) {
dir := t.TempDir()
// Create agent files
os.WriteFile(filepath.Join(dir, "tutor.md"), []byte("# Tutor agent"), 0o644)
os.WriteFile(filepath.Join(dir, "reviewer.md"), []byte("# Reviewer agent"), 0o644)
// Conventional excludes should be skipped
os.WriteFile(filepath.Join(dir, "README.md"), []byte("# Readme"), 0o644)
os.WriteFile(filepath.Join(dir, "LICENSE.md"), []byte("# License"), 0o644)
os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("---\nname: test\n---\n"), 0o644)
// Non-.md files should be skipped
os.WriteFile(filepath.Join(dir, "config.yaml"), []byte("key: value"), 0o644)
// Hidden files should be skipped
os.WriteFile(filepath.Join(dir, ".hidden.md"), []byte("# Hidden"), 0o644)
k := AgentKind{}
resources, err := k.Discover(dir)
if err != nil {
t.Fatalf("Discover error: %v", err)
}
if len(resources) != 2 {
t.Fatalf("expected 2 resources, got %d: %v", len(resources), resources)
}
names := map[string]bool{}
for _, r := range resources {
names[r.Name] = true
if r.Kind != "agent" {
t.Errorf("resource %q has Kind=%q, want %q", r.Name, r.Kind, "agent")
}
}
if !names["tutor"] {
t.Error("expected to discover 'tutor'")
}
if !names["reviewer"] {
t.Error("expected to discover 'reviewer'")
}
}
func TestAgentKind_Discover_Nested(t *testing.T) {
dir := t.TempDir()
os.MkdirAll(filepath.Join(dir, "curriculum"), 0o755)
os.WriteFile(filepath.Join(dir, "curriculum", "math-tutor.md"), []byte("# Math tutor"), 0o644)
k := AgentKind{}
resources, err := k.Discover(dir)
if err != nil {
t.Fatalf("Discover error: %v", err)
}
if len(resources) != 1 {
t.Fatalf("expected 1 resource, got %d", len(resources))
}
r := resources[0]
if r.Name != "math-tutor" {
t.Errorf("Name = %q, want %q", r.Name, "math-tutor")
}
if r.RelPath != "curriculum/math-tutor.md" {
t.Errorf("RelPath = %q, want %q", r.RelPath, "curriculum/math-tutor.md")
}
if r.FlatName != "math-tutor.md" {
t.Errorf("FlatName = %q, want %q", r.FlatName, "math-tutor.md")
}
if !r.IsNested {
t.Error("expected IsNested=true for nested agent")
}
}
func TestAgentKind_ResolveName_FromFilename(t *testing.T) {
dir := t.TempDir()
agentFile := filepath.Join(dir, "tutor.md")
os.WriteFile(agentFile, []byte("# Tutor agent"), 0o644)
k := AgentKind{}
name := k.ResolveName(agentFile)
if name != "tutor" {
t.Errorf("ResolveName = %q, want %q", name, "tutor")
}
}
func TestAgentKind_ResolveName_FromFrontmatter(t *testing.T) {
dir := t.TempDir()
agentFile := filepath.Join(dir, "tutor.md")
os.WriteFile(agentFile, []byte("---\nname: curriculum-tutor\n---\n# Tutor"), 0o644)
k := AgentKind{}
name := k.ResolveName(agentFile)
if name != "curriculum-tutor" {
t.Errorf("ResolveName = %q, want %q", name, "curriculum-tutor")
}
}
func TestAgentKind_FlatName(t *testing.T) {
k := AgentKind{}
tests := []struct {
relPath string
want string
}{
{"tutor.md", "tutor.md"},
{"curriculum/math-tutor.md", "math-tutor.md"},
{"a/b/deep.md", "deep.md"},
}
for _, tt := range tests {
got := k.FlatName(tt.relPath)
if got != tt.want {
t.Errorf("FlatName(%q) = %q, want %q", tt.relPath, got, tt.want)
}
}
}
func TestAgentKind_FeatureGates(t *testing.T) {
k := AgentKind{}
if !k.SupportsAudit() {
t.Error("AgentKind should support audit")
}
if !k.SupportsTrack() {
t.Error("AgentKind should support track")
}
if !k.SupportsCollect() {
t.Error("AgentKind should support collect")
}
}
func TestAgentKind_Discover_EmptyDir(t *testing.T) {
dir := t.TempDir()
k := AgentKind{}
resources, err := k.Discover(dir)
if err != nil {
t.Fatalf("Discover error: %v", err)
}
if len(resources) != 0 {
t.Errorf("expected 0 resources, got %d", len(resources))
}
}
func TestAgentKind_Discover_SkipsGitDir(t *testing.T) {
dir := t.TempDir()
os.MkdirAll(filepath.Join(dir, ".git"), 0o755)
os.WriteFile(filepath.Join(dir, ".git", "config.md"), []byte("# git config"), 0o644)
os.WriteFile(filepath.Join(dir, "real-agent.md"), []byte("# Agent"), 0o644)
k := AgentKind{}
resources, err := k.Discover(dir)
if err != nil {
t.Fatalf("Discover error: %v", err)
}
if len(resources) != 1 {
t.Fatalf("expected 1 resource, got %d", len(resources))
}
if resources[0].Name != "real-agent" {
t.Errorf("Name = %q, want %q", resources[0].Name, "real-agent")
}
}
+100
View File
@@ -0,0 +1,100 @@
package resource
import (
"os"
"path/filepath"
"strings"
"skillshare/internal/utils"
)
// SkillKind handles directory-based skill resources identified by SKILL.md.
type SkillKind struct{}
var _ ResourceKind = SkillKind{}
func (SkillKind) Kind() string { return "skill" }
// Discover scans sourceDir for directories containing SKILL.md.
// This is a simplified discovery for the resource package; the full
// discovery with ignore support, frontmatter parsing, and context
// collection remains in internal/sync/discover_walk.go.
func (SkillKind) Discover(sourceDir string) ([]DiscoveredResource, error) {
walkRoot := utils.ResolveSymlink(sourceDir)
var resources []DiscoveredResource
err := filepath.Walk(walkRoot, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if info.IsDir() && info.Name() == ".git" {
return filepath.SkipDir
}
if !info.IsDir() && info.Name() == "SKILL.md" {
skillDir := filepath.Dir(path)
relPath, relErr := filepath.Rel(walkRoot, skillDir)
if relErr != nil || relPath == "." {
return nil
}
relPath = strings.ReplaceAll(relPath, "\\", "/")
name := utils.ParseFrontmatterField(filepath.Join(skillDir, "SKILL.md"), "name")
if name == "" {
name = filepath.Base(skillDir)
}
isInRepo := false
parts := strings.Split(relPath, "/")
if len(parts) > 0 && utils.IsTrackedRepoDir(parts[0]) {
isInRepo = true
}
resources = append(resources, DiscoveredResource{
Name: name,
Kind: "skill",
RelPath: relPath,
AbsPath: skillDir,
IsNested: strings.Contains(relPath, "/"),
FlatName: utils.PathToFlatName(relPath),
IsInRepo: isInRepo,
SourcePath: filepath.Join(sourceDir, relPath),
})
}
return nil
})
if err != nil {
return nil, err
}
return resources, nil
}
// ResolveName reads the name field from SKILL.md frontmatter.
// Falls back to directory base name if frontmatter has no name.
func (SkillKind) ResolveName(path string) string {
skillFile := filepath.Join(path, "SKILL.md")
name := utils.ParseFrontmatterField(skillFile, "name")
if name != "" {
return name
}
return filepath.Base(path)
}
// FlatName converts a relative path to a flat name using __ separator.
func (SkillKind) FlatName(relPath string) string {
return utils.PathToFlatName(relPath)
}
// CreateLink creates a directory symlink from dst pointing to src.
func (SkillKind) CreateLink(src, dst string) error {
return os.Symlink(src, dst)
}
func (SkillKind) SupportsAudit() bool { return true }
func (SkillKind) SupportsTrack() bool { return true }
func (SkillKind) SupportsCollect() bool { return true }
+11
View File
@@ -54,11 +54,16 @@ func TargetName(name string) error {
return nil
}
// reservedSkillNames are names that cannot be used as skill names
// because they conflict with resource kind directories or commands.
var reservedSkillNames = []string{"agents"}
// SkillName validates a skill name.
// Rules:
// - Must start with a letter or number
// - Can contain letters, numbers, underscores, and hyphens
// - Length 1-64 characters
// - Cannot be a reserved skill name (e.g. "agents")
func SkillName(name string) error {
if name == "" {
return fmt.Errorf("skill name cannot be empty")
@@ -72,6 +77,12 @@ func SkillName(name string) error {
return fmt.Errorf("skill name must start with a letter or number and contain only letters, numbers, underscores, and hyphens")
}
for _, r := range reservedSkillNames {
if strings.EqualFold(name, r) {
return fmt.Errorf("'%s' is a reserved name and cannot be used as a skill name", name)
}
}
return nil
}
+25
View File
@@ -44,6 +44,31 @@ func TestTargetName(t *testing.T) {
}
}
func TestSkillName(t *testing.T) {
tests := []struct {
name string
input string
wantErr bool
}{
{"valid", "my-skill", false},
{"valid with number", "skill2", false},
{"empty", "", true},
{"too long", strings.Repeat("a", 65), true},
{"reserved agents", "agents", true},
{"reserved agents uppercase", "Agents", true},
{"starts with special", "-skill", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := SkillName(tt.input)
if (err != nil) != tt.wantErr {
t.Errorf("SkillName(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
}
})
}
}
func TestPath(t *testing.T) {
tests := []struct {
name string