feat: skm, pin agent skills from git repos via Nix

CLI (add, remove, list, outdated, update, import) over a skills.json manifest and a skills.lock.json pinned with nix flake prefetch, plus a home-manager module that links each locked skill via builtins.fetchTree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
johannesandClaude Opus 5.5 committed 2026-10-23 14:04:50 +02:00
commit 65a96ada8e
26 files changed
+2843

No files matched your search

+333
View File
@@ -0,0 +1,333 @@
// Package core implements skm's operations on the manifest and lock. The CLI and
// the TUI both call into it.
package core
import (
"context"
"fmt"
"maps"
"path/filepath"
"slices"
"strings"
"skill-manager/internal/fetch"
"skill-manager/internal/lock"
"skill-manager/internal/manifest"
"skill-manager/internal/skills"
)
const (
ManifestFile = "skills.json"
LockFile = "skills.lock.json"
)
// Store is a directory holding skills.json and skills.lock.json.
type Store struct {
Dir string
Fetcher fetch.Fetcher
}
func (s Store) load() (*manifest.Manifest, *lock.Lock, error) {
m, err := manifest.Load(filepath.Join(s.Dir, ManifestFile))
if err != nil {
return nil, nil, err
}
l, err := lock.Load(filepath.Join(s.Dir, LockFile))
if err != nil {
return nil, nil, err
}
return m, l, nil
}
// save validates, then writes the lock before the manifest: a crash in between
// leaves a lock that still matches what's installed.
func (s Store) save(m *manifest.Manifest, l *lock.Lock) error {
if err := checkCollisions(l); err != nil {
return err
}
if err := l.Save(filepath.Join(s.Dir, LockFile)); err != nil {
return err
}
return m.Save(filepath.Join(s.Dir, ManifestFile))
}
func flakeRef(src *manifest.Source) string {
if src.Ref == "" {
return src.URL
}
return fetch.WithParam(src.URL, "ref", src.Ref)
}
// SourceKey derives a source name from its URL: owner/repo.
func SourceKey(url string) string {
base, _, _ := strings.Cut(url, "?")
var parts []string
if _, rest, ok := strings.Cut(base, "://"); ok {
// git+ssh://git@host/group/repo.git: drop the host, keep the last two segments.
_, path, _ := strings.Cut(rest, "/")
parts = strings.Split(strings.TrimSuffix(strings.Trim(path, "/"), ".git"), "/")
if len(parts) > 2 {
parts = parts[len(parts)-2:]
}
} else {
// github:owner/repo[/ref]: the first two segments.
_, path, _ := strings.Cut(base, ":")
parts = strings.Split(strings.Trim(path, "/"), "/")
if len(parts) > 2 {
parts = parts[:2]
}
}
return strings.Join(parts, "/")
}
type AddRequest struct {
// Name is the source key; empty derives it from URL.
Name string
URL string
Ref string
// Skills to add. Ignored when All is set.
Skills []manifest.Skill
All bool
}
// NoSelectionError is returned by Add when neither skills nor All were given.
type NoSelectionError struct {
Source string
Available []skills.Skill
}
func (e *NoSelectionError) Error() string {
return fmt.Sprintf("no skills selected from %s; available: %s", e.Source, available(e.Available))
}
func available(found []skills.Skill) string {
var names []string
for _, f := range found {
names = append(names, f.Name)
}
slices.Sort(names)
return strings.Join(slices.Compact(names), ", ")
}
// Add records skills from a source. A new source is pinned at the head of its ref;
// adding to an existing source keeps its pin. Returns the source key.
func (s Store) Add(ctx context.Context, req AddRequest) (string, error) {
m, l, err := s.load()
if err != nil {
return "", err
}
key := req.Name
if key == "" {
key = SourceKey(req.URL)
}
src := m.Sources[key]
var ref string
if src != nil {
if src.URL != req.URL {
return "", fmt.Errorf("source %q already exists with url %s; pick another name with --name", key, src.URL)
}
if req.Ref != "" && req.Ref != src.Ref {
return "", fmt.Errorf("source %q tracks ref %q; add a second source with --name to track %q", key, src.Ref, req.Ref)
}
locked := l.Sources[key]
if locked == nil {
return "", fmt.Errorf("source %q is in %s but not locked; run skm update %s first", key, ManifestFile, key)
}
ref = fetch.AtRev(flakeRef(src), locked.Rev())
src = &manifest.Source{URL: src.URL, Ref: src.Ref, Skills: manifest.Selection{
All: src.Skills.All,
Items: slices.Clone(src.Skills.Items),
}}
} else {
src = &manifest.Source{URL: req.URL, Ref: req.Ref}
ref = flakeRef(src)
}
res, found, err := s.fetchSkills(ctx, ref)
if err != nil {
return "", fmt.Errorf("%s: %w", key, err)
}
switch {
case req.All:
src.Skills = manifest.Selection{All: true}
case len(req.Skills) == 0:
return "", &NoSelectionError{Source: key, Available: found}
case src.Skills.All:
return "", fmt.Errorf("source %q already installs every skill", key)
default:
for _, k := range req.Skills {
if k.Name == "" {
i := slices.IndexFunc(found, func(f skills.Skill) bool { return f.Path == k.Path })
if i < 0 {
return "", fmt.Errorf("%s: no skill at %s", key, k.Path)
}
k.Name = found[i].Name
}
if slices.ContainsFunc(src.Skills.Items, func(e manifest.Skill) bool { return e.Installed() == k.Installed() }) {
return "", fmt.Errorf("%s is already installed from %s", k.Installed(), key)
}
src.Skills.Items = append(src.Skills.Items, k)
}
}
resolved, err := resolve(src.Skills, found)
if err != nil {
return "", fmt.Errorf("%s: %w", key, err)
}
m.Sources[key] = src
l.Sources[key] = &lock.Source{Locked: res.Locked, Skills: resolved}
return key, s.save(m, l)
}
func (s Store) fetchSkills(ctx context.Context, ref string) (fetch.Result, []skills.Skill, error) {
res, err := s.Fetcher.Prefetch(ctx, ref)
if err != nil {
return fetch.Result{}, nil, err
}
found, err := skills.Discover(res.StorePath)
if err != nil {
return fetch.Result{}, nil, err
}
if len(found) == 0 {
return fetch.Result{}, nil, fmt.Errorf("%s contains no SKILL.md", ref)
}
return res, found, nil
}
// resolve maps installed names to paths within the source.
func resolve(sel manifest.Selection, found []skills.Skill) (map[string]string, error) {
out := map[string]string{}
add := func(name, path string) error {
if prev, dup := out[name]; dup {
return fmt.Errorf("two skills installed as %q: %s and %s", name, prev, path)
}
out[name] = path
return nil
}
if sel.All {
for _, f := range found {
if err := add(f.Name, f.Path); err != nil {
return nil, fmt.Errorf(`%w; list skills explicitly, picking one with "path"`, err)
}
}
return out, nil
}
for _, k := range sel.Items {
var matches []skills.Skill
for _, f := range found {
if f.Name == k.Name && (k.Path == "" || f.Path == k.Path) {
matches = append(matches, f)
}
}
switch {
case len(matches) == 0 && k.Path != "":
return nil, fmt.Errorf("no skill %q at %s", k.Name, k.Path)
case len(matches) == 0:
return nil, fmt.Errorf("no skill %q; available: %s", k.Name, available(found))
case len(matches) > 1:
var paths []string
for _, f := range matches {
paths = append(paths, f.Path)
}
return nil, fmt.Errorf(`several skills named %q (%s); pick one with "path"`, k.Name, strings.Join(paths, ", "))
}
if err := add(k.Installed(), matches[0].Path); err != nil {
return nil, err
}
}
return out, nil
}
func checkCollisions(l *lock.Lock) error {
owner := map[string]string{}
for _, key := range slices.Sorted(maps.Keys(l.Sources)) {
for _, name := range slices.Sorted(maps.Keys(l.Sources[key].Skills)) {
if prev, ok := owner[name]; ok {
return fmt.Errorf(`skill %q comes from both %s and %s; rename one with "as"`, name, prev, key)
}
owner[name] = key
}
}
return nil
}
// Remove drops one installed skill, and its source once that is empty.
// Returns the source it came from.
func (s Store) Remove(name string) (string, error) {
m, l, err := s.load()
if err != nil {
return "", err
}
for _, key := range slices.Sorted(maps.Keys(m.Sources)) {
src := m.Sources[key]
i := slices.IndexFunc(src.Skills.Items, func(k manifest.Skill) bool { return k.Installed() == name })
locked := isLocked(l, key, name)
if i < 0 && !locked {
continue
}
if src.Skills.All {
return "", fmt.Errorf(`%s comes from %s, which installs every skill ("*"); remove the whole source with --source %s`, name, key, key)
}
if i >= 0 {
src.Skills.Items = slices.Delete(src.Skills.Items, i, i+1)
}
if locked {
delete(l.Sources[key].Skills, name)
}
if len(src.Skills.Items) == 0 {
delete(m.Sources, key)
delete(l.Sources, key)
}
return key, s.save(m, l)
}
return "", fmt.Errorf("no installed skill %q", name)
}
func isLocked(l *lock.Lock, key, name string) bool {
src := l.Sources[key]
if src == nil {
return false
}
_, ok := src.Skills[name]
return ok
}
// RemoveSource drops a source and all its skills.
func (s Store) RemoveSource(key string) error {
m, l, err := s.load()
if err != nil {
return err
}
if _, ok := m.Sources[key]; !ok {
return fmt.Errorf("no source %q", key)
}
delete(m.Sources, key)
delete(l.Sources, key)
return s.save(m, l)
}
type Installed struct {
Name string
Source string
Path string
Rev string
}
// List returns the locked skills, sorted by name.
func (s Store) List() ([]Installed, error) {
_, l, err := s.load()
if err != nil {
return nil, err
}
var out []Installed
for key, src := range l.Sources {
for name, path := range src.Skills {
out = append(out, Installed{Name: name, Source: key, Path: path, Rev: src.Rev()})
}
}
slices.SortFunc(out, func(a, b Installed) int { return strings.Compare(a.Name, b.Name) })
return out, nil
}
+212
View File
@@ -0,0 +1,212 @@
package core
import (
"context"
"errors"
"net/url"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"testing"
"skill-manager/internal/fetch"
"skill-manager/internal/lock"
"skill-manager/internal/manifest"
)
// fakeRepo maps revs to fixture directories; head is what an unpinned fetch gets.
type fakeRepo struct {
head string
revs map[string]string
}
func (r *fakeRepo) push(rev, dir string) {
r.revs[rev] = dir
r.head = rev
}
// fakeFetcher serves fakeRepos keyed by flake ref without its query.
type fakeFetcher struct {
mu sync.Mutex
repos map[string]*fakeRepo
calls []string
}
func (f *fakeFetcher) Prefetch(_ context.Context, ref string) (fetch.Result, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.calls = append(f.calls, ref)
base, query, _ := strings.Cut(ref, "?")
repo, ok := f.repos[base]
if !ok {
return fetch.Result{}, errors.New("unknown source " + base)
}
rev := repo.head
q, _ := url.ParseQuery(query)
if pinned := q.Get("rev"); pinned != "" {
rev = pinned
}
dir, ok := repo.revs[rev]
if !ok {
return fetch.Result{}, errors.New("unknown rev " + rev)
}
return fetch.Result{StorePath: dir, Locked: map[string]any{"rev": rev, "narHash": "sha256-" + rev}}, nil
}
// fixture builds a repo with skills/<name>/SKILL.md for each "name" or "name:content".
func fixture(t *testing.T, skills ...string) string {
t.Helper()
root := t.TempDir()
for _, s := range skills {
name, content, _ := strings.Cut(s, ":")
dir := filepath.Join(root, "skills", name)
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
return root
}
func newStore(t *testing.T) (Store, *fakeFetcher) {
f := &fakeFetcher{repos: map[string]*fakeRepo{
"github:mp/skills": {head: "r1", revs: map[string]string{"r1": fixture(t, "tdd", "prototype", "grilling")}},
"github:other/skills": {head: "r1", revs: map[string]string{"r1": fixture(t, "grilling", "deslop:d")}},
}}
return Store{Dir: t.TempDir(), Fetcher: f}, f
}
func names(t *testing.T, s Store) []string {
t.Helper()
list, err := s.List()
if err != nil {
t.Fatal(err)
}
var out []string
for _, i := range list {
out = append(out, i.Source+":"+i.Name)
}
return out
}
func pick(names ...string) []manifest.Skill {
var out []manifest.Skill
for _, n := range names {
name, as, _ := strings.Cut(n, "=")
out = append(out, manifest.Skill{Name: name, As: as})
}
return out
}
func TestSourceKey(t *testing.T) {
cases := map[string]string{
"github:mattpocock/skills": "mattpocock/skills",
"github:mattpocock/skills/main": "mattpocock/skills",
"github:mattpocock/skills?ref=main": "mattpocock/skills",
"git+ssh://git@git.example.com/jo/skills.git": "jo/skills",
"git+https://host/group/sub/repo?ref=x": "sub/repo",
}
for in, want := range cases {
if got := SourceKey(in); got != want {
t.Errorf("SourceKey(%q) = %q, want %q", in, got, want)
}
}
}
func TestAdd(t *testing.T) {
ctx := context.Background()
s, f := newStore(t)
if _, err := s.Add(ctx, AddRequest{URL: "github:mp/skills", Ref: "main", Skills: pick("tdd")}); err != nil {
t.Fatal(err)
}
if f.calls[0] != "github:mp/skills?ref=main" {
t.Errorf("first fetch = %q", f.calls[0])
}
// Adding to an existing source keeps its pin even if upstream moved.
f.repos["github:mp/skills"].push("r2", fixture(t, "tdd:new", "prototype", "grilling"))
if _, err := s.Add(ctx, AddRequest{URL: "github:mp/skills", Skills: pick("prototype")}); err != nil {
t.Fatal(err)
}
if f.calls[1] != "github:mp/skills?rev=r1" {
t.Errorf("second fetch = %q, want pinned to r1", f.calls[1])
}
if got, want := names(t, s), []string{"mp/skills:prototype", "mp/skills:tdd"}; !reflect.DeepEqual(got, want) {
t.Errorf("installed %v, want %v", got, want)
}
l, err := lock.Load(filepath.Join(s.Dir, LockFile))
if err != nil {
t.Fatal(err)
}
if rev := l.Sources["mp/skills"].Rev(); rev != "r1" {
t.Errorf("locked rev %q, want r1", rev)
}
}
func TestAddErrors(t *testing.T) {
ctx := context.Background()
s, _ := newStore(t)
if _, err := s.Add(ctx, AddRequest{URL: "github:mp/skills", Skills: pick("grilling")}); err != nil {
t.Fatal(err)
}
_, err := s.Add(ctx, AddRequest{URL: "github:other/skills"})
if sel, ok := errors.AsType[*NoSelectionError](err); !ok || available(sel.Available) != "deslop, grilling" {
t.Errorf("no selection: got %v", err)
}
if _, err := s.Add(ctx, AddRequest{URL: "github:other/skills", Skills: pick("nope")}); err == nil {
t.Error("want error for a missing skill")
}
if _, err := s.Add(ctx, AddRequest{URL: "github:other/skills", Skills: pick("grilling")}); err == nil {
t.Error("want collision error")
}
if _, err := s.Add(ctx, AddRequest{URL: "github:mp/skills", Skills: pick("grilling")}); err == nil {
t.Error("want error for adding the same skill twice")
}
// Failed adds must leave nothing behind; an alias resolves the collision.
if _, err := s.Add(ctx, AddRequest{URL: "github:other/skills", Skills: pick("grilling=grilling-o")}); err != nil {
t.Fatal(err)
}
if got, want := names(t, s), []string{"mp/skills:grilling", "other/skills:grilling-o"}; !reflect.DeepEqual(got, want) {
t.Errorf("installed %v, want %v", got, want)
}
}
func TestRemove(t *testing.T) {
ctx := context.Background()
s, _ := newStore(t)
if _, err := s.Add(ctx, AddRequest{URL: "github:mp/skills", Skills: pick("tdd", "prototype")}); err != nil {
t.Fatal(err)
}
if _, err := s.Add(ctx, AddRequest{URL: "github:other/skills", All: true}); err != nil {
t.Fatal(err)
}
if _, err := s.Remove("deslop"); err == nil {
t.Error("want error removing one skill from a * source")
}
if _, err := s.Remove("tdd"); err != nil {
t.Fatal(err)
}
if _, err := s.Remove("prototype"); err != nil {
t.Fatal(err)
}
if err := s.RemoveSource("other/skills"); err != nil {
t.Fatal(err)
}
m, err := manifest.Load(filepath.Join(s.Dir, ManifestFile))
if err != nil {
t.Fatal(err)
}
if len(m.Sources) != 0 || len(names(t, s)) != 0 {
t.Errorf("want everything removed, manifest has %v", m.Sources)
}
}
+227
View File
@@ -0,0 +1,227 @@
package core
import (
"context"
"errors"
"fmt"
"maps"
"os"
"path"
"path/filepath"
"slices"
"sync"
"skill-manager/internal/fetch"
"skill-manager/internal/jsonfile"
"skill-manager/internal/lock"
"skill-manager/internal/manifest"
"skill-manager/internal/skills"
)
// vercelLock is the part of vercel-labs/skills' .skill-lock.json that Import reads.
type vercelLock struct {
Skills map[string]struct {
Source string `json:"source"`
SourceType string `json:"sourceType"`
SkillPath string `json:"skillPath"`
} `json:"skills"`
}
type ImportStatus int
const (
Identical ImportStatus = iota
Differs
NoLocalCopy
)
// Imported compares an imported skill with the copy committed in the local directory.
type Imported struct {
Name, Source string
Upstream string // skill directory in the store
Local string // committed copy; empty if there is none
Status ImportStatus
}
type ImportReport struct {
Sources int
Imported []Imported
Skipped []string // "name: reason"
Untracked []string // skills in the local dir that skm doesn't install
}
type vercelEntry struct{ name, dir string }
type fetched struct {
key string
src *manifest.Source
res fetch.Result
found []skills.Skill
err error
}
// Import adds every skill in vercel's lock to the manifest. New sources are pinned
// at the head of their default branch; sources already in the manifest keep their
// pin. Each skill is compared with its committed copy in localDir.
func (s Store) Import(ctx context.Context, vercelPath, localDir string) (ImportReport, error) {
var rep ImportReport
var vl vercelLock
ok, err := jsonfile.Read(vercelPath, &vl)
if err != nil {
return rep, err
}
if !ok {
return rep, fmt.Errorf("%s not found", vercelPath)
}
m, l, err := s.load()
if err != nil {
return rep, err
}
bySource := map[string][]vercelEntry{}
for _, name := range slices.Sorted(maps.Keys(vl.Skills)) {
e := vl.Skills[name]
if e.SourceType != "github" {
rep.Skipped = append(rep.Skipped, fmt.Sprintf("%s: unsupported source type %q", name, e.SourceType))
continue
}
bySource[e.Source] = append(bySource[e.Source], vercelEntry{name: name, dir: path.Dir(e.SkillPath)})
}
// Fetch every source in parallel; merge in order afterwards.
ghSources := slices.Sorted(maps.Keys(bySource))
results := make([]fetched, len(ghSources))
var wg sync.WaitGroup
for i, gh := range ghSources {
url := "github:" + gh
f := fetched{key: SourceKey(url), src: &manifest.Source{URL: url}}
ref := url
if existing := m.Sources[f.key]; existing != nil {
if existing.URL != url {
f.err = fmt.Errorf("source %q already exists with url %s", f.key, existing.URL)
results[i] = f
continue
}
f.src = existing
ref = flakeRef(existing)
if locked := l.Sources[f.key]; locked != nil {
ref = fetch.AtRev(ref, locked.Rev())
}
}
wg.Go(func() {
f.res, f.found, f.err = s.fetchSkills(ctx, ref)
results[i] = f
})
}
wg.Wait()
for i, f := range results {
entries := bySource[ghSources[i]]
if f.err != nil {
for _, e := range entries {
rep.Skipped = append(rep.Skipped, fmt.Sprintf("%s: %v", e.name, f.err))
}
continue
}
// A "*" source already selects everything; its skills are only compared.
if !f.src.Skills.All {
for _, e := range entries {
if slices.ContainsFunc(f.src.Skills.Items, func(k manifest.Skill) bool { return k.Installed() == e.name }) {
continue
}
item, err := importItem(e, f.found)
if err != nil {
rep.Skipped = append(rep.Skipped, fmt.Sprintf("%s: %v", e.name, err))
continue
}
f.src.Skills.Items = append(f.src.Skills.Items, item)
}
}
if !f.src.Skills.All && len(f.src.Skills.Items) == 0 {
continue
}
resolved, err := resolve(f.src.Skills, f.found)
if err != nil {
return rep, fmt.Errorf("%s: %w", f.key, err)
}
m.Sources[f.key] = f.src
l.Sources[f.key] = &lock.Source{Locked: f.res.Locked, Skills: resolved}
rep.Sources++
for _, name := range slices.Sorted(maps.Keys(resolved)) {
imp := Imported{Name: name, Source: f.key, Upstream: filepath.Join(f.res.StorePath, resolved[name]), Status: NoLocalCopy}
if local := filepath.Join(localDir, name); isDir(local) {
imp.Local = local
same, err := sameDir(ctx, local, imp.Upstream)
if err != nil {
return rep, err
}
imp.Status = Differs
if same {
imp.Status = Identical
}
}
rep.Imported = append(rep.Imported, imp)
}
}
if err := s.save(m, l); err != nil {
return rep, err
}
rep.Untracked, err = untracked(localDir, l)
return rep, err
}
// importItem picks the upstream skill at the vercel entry's path, aliasing it when
// vercel installed it under another name.
func importItem(e vercelEntry, found []skills.Skill) (manifest.Skill, error) {
i := slices.IndexFunc(found, func(f skills.Skill) bool { return f.Path == e.dir })
if i < 0 {
return manifest.Skill{}, fmt.Errorf("not at %s upstream anymore (removed or moved)", e.dir)
}
item := manifest.Skill{Name: found[i].Name}
if e.name != item.Name {
item.As = e.name
}
sameName := 0
for _, f := range found {
if f.Name == item.Name {
sameName++
}
}
if sameName > 1 {
item.Path = e.dir
}
return item, nil
}
func untracked(localDir string, l *lock.Lock) ([]string, error) {
entries, err := os.ReadDir(localDir)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
installed := map[string]bool{}
for _, src := range l.Sources {
for name := range src.Skills {
installed[name] = true
}
}
var out []string
for _, e := range entries {
if !e.IsDir() || installed[e.Name()] {
continue
}
if _, err := os.Stat(filepath.Join(localDir, e.Name(), "SKILL.md")); err == nil {
out = append(out, e.Name())
}
}
return out, nil
}
func isDir(p string) bool {
fi, err := os.Stat(p)
return err == nil && fi.IsDir()
}
+112
View File
@@ -0,0 +1,112 @@
package core
import (
"context"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"skill-manager/internal/manifest"
)
func writeFile(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
func TestImport(t *testing.T) {
ctx := context.Background()
s, _ := newStore(t)
// Already managed before the import: kept, not duplicated.
if _, err := s.Add(ctx, AddRequest{URL: "github:mp/skills", Skills: pick("prototype")}); err != nil {
t.Fatal(err)
}
vercel := filepath.Join(t.TempDir(), ".skill-lock.json")
writeFile(t, vercel, `{"version": 3, "skills": {
"tdd": {"source": "mp/skills", "sourceType": "github", "skillPath": "skills/tdd/SKILL.md"},
"prototype": {"source": "mp/skills", "sourceType": "github", "skillPath": "skills/prototype/SKILL.md"},
"gone": {"source": "mp/skills", "sourceType": "github", "skillPath": "skills/gone/SKILL.md"},
"deslop": {"source": "other/skills", "sourceType": "github", "skillPath": "skills/deslop/SKILL.md"},
"grill-o": {"source": "other/skills", "sourceType": "github", "skillPath": "skills/grilling/SKILL.md"},
"x": {"source": "x", "sourceType": "local", "skillPath": "x/SKILL.md"}
}}`)
local := t.TempDir()
writeFile(t, filepath.Join(local, "tdd", "SKILL.md"), "")
writeFile(t, filepath.Join(local, "deslop", "SKILL.md"), "my edits")
writeFile(t, filepath.Join(local, "c4-model", "SKILL.md"), "")
if err := os.MkdirAll(filepath.Join(local, "synced"), 0o755); err != nil {
t.Fatal(err)
}
rep, err := s.Import(ctx, vercel, local)
if err != nil {
t.Fatal(err)
}
var got []string
for _, imp := range rep.Imported {
got = append(got, imp.Name+"="+[]string{"same", "differs", "nolocal"}[imp.Status])
}
want := []string{"prototype=nolocal", "tdd=same", "deslop=differs", "grill-o=nolocal"}
if !reflect.DeepEqual(got, want) {
t.Errorf("imported %v, want %v", got, want)
}
if len(rep.Skipped) != 2 || !strings.HasPrefix(rep.Skipped[0], "x:") || !strings.HasPrefix(rep.Skipped[1], "gone:") {
t.Errorf("skipped %v", rep.Skipped)
}
if !reflect.DeepEqual(rep.Untracked, []string{"c4-model"}) {
t.Errorf("untracked %v", rep.Untracked)
}
m, err := manifest.Load(filepath.Join(s.Dir, ManifestFile))
if err != nil {
t.Fatal(err)
}
if got, want := m.Sources["other/skills"].Skills.Items, pick("deslop", "grilling=grill-o"); !reflect.DeepEqual(got, want) {
t.Errorf("other/skills items %v, want %v", got, want)
}
if got, want := m.Sources["mp/skills"].Skills.Items, pick("prototype", "tdd"); !reflect.DeepEqual(got, want) {
t.Errorf("mp/skills items %v, want %v", got, want)
}
// Running it again changes nothing.
if _, err := s.Import(ctx, vercel, local); err != nil {
t.Fatal(err)
}
if got := names(t, s); len(got) != 4 {
t.Errorf("after re-import: %v", got)
}
}
func TestDuplicateNames(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
writeFile(t, filepath.Join(root, "a", "skills", "pr", "SKILL.md"), "")
writeFile(t, filepath.Join(root, "b", "skills", "pr", "SKILL.md"), "")
f := &fakeFetcher{repos: map[string]*fakeRepo{"github:c/plugins": {head: "r1", revs: map[string]string{"r1": root}}}}
s := Store{Dir: t.TempDir(), Fetcher: f}
if _, err := s.Add(ctx, AddRequest{URL: "github:c/plugins", Skills: pick("pr")}); err == nil || !strings.Contains(err.Error(), "several skills") {
t.Errorf("ambiguous name: %v", err)
}
if _, err := s.Add(ctx, AddRequest{URL: "github:c/plugins", All: true}); err == nil {
t.Error(`want error for "*" over duplicate names`)
}
if _, err := s.Add(ctx, AddRequest{URL: "github:c/plugins", Skills: []manifest.Skill{{Path: "b/skills/pr"}}}); err != nil {
t.Fatal(err)
}
list, err := s.List()
if err != nil {
t.Fatal(err)
}
if len(list) != 1 || list[0].Name != "pr" || list[0].Path != "b/skills/pr" {
t.Errorf("installed %+v", list)
}
}
+286
View File
@@ -0,0 +1,286 @@
package core
import (
"cmp"
"context"
"errors"
"fmt"
"maps"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"sync"
"skill-manager/internal/fetch"
"skill-manager/internal/lock"
"skill-manager/internal/manifest"
"skill-manager/internal/skills"
)
type ChangeKind int
const (
Modified ChangeKind = iota
Added
Removed
)
func (k ChangeKind) Symbol() string {
return [...]string{"↑", "+", "-"}[k]
}
// Change is one installed skill that differs between the lock and upstream.
type Change struct {
Name string
Kind ChangeKind
// Skill directories in the store; empty when added or removed, and Old is
// also empty for a source dropped from the manifest.
Old, New string
}
// SourceStatus compares a source's lock entry with the head of its ref.
type SourceStatus struct {
Source string
OldRev, NewRev string // OldRev is empty for a source not yet locked
Changes []Change
Err error
next *lock.Source // nil: the source was dropped from the manifest
}
func (s SourceStatus) Outdated() bool {
return s.Err == nil && len(s.Changes) > 0
}
// Check fetches the head of each source's ref and reports which installed skills
// would change. With no names it checks every source; names may be sources or
// installed skills. It also picks up hand edits to skills.json: sources or skills
// added there show as Added, removed ones as Removed.
func (s Store) Check(ctx context.Context, names ...string) ([]SourceStatus, error) {
m, l, err := s.load()
if err != nil {
return nil, err
}
keys, err := selectSources(m, l, names)
if err != nil {
return nil, err
}
out := make([]SourceStatus, len(keys))
var wg sync.WaitGroup
for i, key := range keys {
wg.Go(func() { out[i] = s.check(ctx, key, m.Sources[key], l.Sources[key]) })
}
wg.Wait()
return out, nil
}
func selectSources(m *manifest.Manifest, l *lock.Lock, names []string) ([]string, error) {
all := slices.Sorted(maps.Keys(m.Sources))
for key := range l.Sources {
if _, ok := m.Sources[key]; !ok {
all = append(all, key)
}
}
slices.Sort(all)
if len(names) == 0 {
return all, nil
}
picked := map[string]bool{}
for _, name := range names {
key, ok := owner(m, l, name)
if !ok {
return nil, fmt.Errorf("no source or installed skill %q", name)
}
picked[key] = true
}
return slices.DeleteFunc(all, func(k string) bool { return !picked[k] }), nil
}
// owner finds the source a name refers to: the source itself, or the one installing that skill.
func owner(m *manifest.Manifest, l *lock.Lock, name string) (string, bool) {
if _, ok := m.Sources[name]; ok {
return name, true
}
if _, ok := l.Sources[name]; ok {
return name, true
}
for key, src := range l.Sources {
if _, ok := src.Skills[name]; ok {
return key, true
}
}
for key, src := range m.Sources {
if slices.ContainsFunc(src.Skills.Items, func(k manifest.Skill) bool { return k.Installed() == name }) {
return key, true
}
}
return "", false
}
func (s Store) check(ctx context.Context, key string, src *manifest.Source, locked *lock.Source) SourceStatus {
st := SourceStatus{Source: key}
if locked == nil {
locked = &lock.Source{}
}
st.OldRev = locked.Rev()
if src == nil {
// Dropped from skills.json. Without its url there's nothing to fetch for a diff.
for _, name := range slices.Sorted(maps.Keys(locked.Skills)) {
st.Changes = append(st.Changes, Change{Name: name, Kind: Removed})
}
return st
}
var oldRoot string
if st.OldRev != "" {
res, err := s.Fetcher.Prefetch(ctx, fetch.AtRev(flakeRef(src), st.OldRev))
if err != nil {
st.Err = err
return st
}
oldRoot = res.StorePath
}
res, err := s.Fetcher.Prefetch(ctx, flakeRef(src))
if err != nil {
st.Err = err
return st
}
st.NewRev = res.Rev()
found, err := skills.Discover(res.StorePath)
if err == nil {
st.next = &lock.Source{Locked: res.Locked}
st.next.Skills, err = resolve(src.Skills, found)
}
if err != nil {
st.Err = err
return st
}
names := slices.Sorted(maps.Keys(locked.Skills))
for name := range st.next.Skills {
if _, ok := locked.Skills[name]; !ok {
names = append(names, name)
}
}
slices.Sort(names)
for _, name := range names {
oldPath, wasLocked := locked.Skills[name]
newPath, stays := st.next.Skills[name]
ch := Change{Name: name}
if wasLocked {
ch.Old = filepath.Join(oldRoot, oldPath)
}
if stays {
ch.New = filepath.Join(res.StorePath, newPath)
}
switch {
case !stays:
ch.Kind = Removed
case !wasLocked:
ch.Kind = Added
default:
same, err := sameDir(ctx, ch.Old, ch.New)
if err != nil {
st.Err = err
return st
}
if same {
continue
}
ch.Kind = Modified
}
st.Changes = append(st.Changes, ch)
}
return st
}
// Apply writes the lock entries of the outdated statuses.
func (s Store) Apply(statuses []SourceStatus) error {
m, l, err := s.load()
if err != nil {
return err
}
for _, st := range statuses {
if !st.Outdated() {
continue
}
if st.next == nil {
delete(l.Sources, st.Source)
} else {
l.Sources[st.Source] = st.next
}
}
return s.save(m, l)
}
// CommitMessage summarizes applied statuses for the nix repo's git log.
func CommitMessage(applied []SourceStatus) string {
var heads, body []string
for _, st := range applied {
switch {
case st.next == nil:
heads = append(heads, "remove "+st.Source)
case st.OldRev == "":
heads = append(heads, fmt.Sprintf("add %s@%.7s", st.Source, st.NewRev))
case st.OldRev == st.NewRev:
// Same pin; only the selection in skills.json changed.
heads = append(heads, "update "+st.Source)
default:
heads = append(heads, fmt.Sprintf("update %s %.7s→%.7s", st.Source, st.OldRev, st.NewRev))
}
for _, ch := range st.Changes {
body = append(body, ch.Kind.Symbol()+" "+ch.Name)
}
}
return "skills: " + strings.Join(heads, ", ") + "\n\n" + strings.Join(body, "\n")
}
// Diff renders a change as a unified diff with a/<name> and b/<name> paths.
func Diff(ctx context.Context, ch Change) (string, error) {
empty, err := os.MkdirTemp("", "skm-empty-")
if err != nil {
return "", err
}
defer os.Remove(empty)
oldDir, newDir := cmp.Or(ch.Old, empty), cmp.Or(ch.New, empty)
out, err := exec.CommandContext(ctx, "diff", "-ruN", oldDir, newDir).Output()
if !differs(err) && err != nil {
return "", fmt.Errorf("diff %s: %w", ch.Name, err)
}
text := strings.ReplaceAll(string(out), oldDir, "a/"+ch.Name)
text = strings.ReplaceAll(text, newDir, "b/"+ch.Name)
// Store timestamps are always the epoch; drop them from the file headers.
lines := strings.SplitAfter(text, "\n")
for i, line := range lines {
if strings.HasPrefix(line, "--- ") || strings.HasPrefix(line, "+++ ") {
if head, _, ok := strings.Cut(line, "\t"); ok {
lines[i] = head + "\n"
}
}
}
return strings.Join(lines, ""), nil
}
func sameDir(ctx context.Context, a, b string) (bool, error) {
if a == b {
return true, nil
}
err := exec.CommandContext(ctx, "diff", "-rq", a, b).Run()
if differs(err) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("diff: %w", err)
}
return true, nil
}
// differs reports diff's "files differ" exit status.
func differs(err error) bool {
exit, ok := errors.AsType[*exec.ExitError](err)
return ok && exit.ExitCode() == 1
}
+238
View File
@@ -0,0 +1,238 @@
package core
import (
"context"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"skill-manager/internal/fetch"
"skill-manager/internal/lock"
"skill-manager/internal/manifest"
)
func changes(st SourceStatus) []string {
var out []string
for _, ch := range st.Changes {
out = append(out, ch.Kind.Symbol()+ch.Name)
}
return out
}
func lockedRev(t *testing.T, s Store, key string) string {
t.Helper()
l, err := lock.Load(filepath.Join(s.Dir, LockFile))
if err != nil {
t.Fatal(err)
}
if l.Sources[key] == nil {
return ""
}
return l.Sources[key].Rev()
}
func check(t *testing.T, s Store, names ...string) []SourceStatus {
t.Helper()
sts, err := s.Check(context.Background(), names...)
if err != nil {
t.Fatal(err)
}
for _, st := range sts {
if st.Err != nil {
t.Fatalf("%s: %v", st.Source, st.Err)
}
}
return sts
}
func TestCheckModified(t *testing.T) {
ctx := context.Background()
s, f := newStore(t)
if _, err := s.Add(ctx, AddRequest{URL: "github:mp/skills", Skills: pick("tdd", "prototype")}); err != nil {
t.Fatal(err)
}
// Upstream moves without touching our skills: not outdated.
f.repos["github:mp/skills"].push("r2", fixture(t, "tdd", "prototype", "grilling:changed"))
if sts := check(t, s); sts[0].Outdated() {
t.Fatalf("unrelated upstream change reported: %v", changes(sts[0]))
}
f.repos["github:mp/skills"].push("r3", fixture(t, "tdd:v2", "prototype", "new"))
sts := check(t, s)
if len(sts) != 1 || sts[0].OldRev != "r1" || sts[0].NewRev != "r3" {
t.Fatalf("statuses %+v", sts)
}
if got := changes(sts[0]); !reflect.DeepEqual(got, []string{"↑tdd"}) {
t.Errorf("changes %v, want only tdd modified", got)
}
d, err := Diff(ctx, sts[0].Changes[0])
if err != nil {
t.Fatal(err)
}
if !strings.Contains(d, "b/tdd/SKILL.md") || !strings.Contains(d, "+v2") {
t.Errorf("diff:\n%s", d)
}
if err := s.Apply(sts); err != nil {
t.Fatal(err)
}
if rev := lockedRev(t, s, "mp/skills"); rev != "r3" {
t.Errorf("locked %q, want r3", rev)
}
if sts := check(t, s); sts[0].Outdated() {
t.Errorf("still outdated after apply: %v", changes(sts[0]))
}
}
func TestCheckAllSource(t *testing.T) {
ctx := context.Background()
s, f := newStore(t)
if _, err := s.Add(ctx, AddRequest{URL: "github:other/skills", All: true}); err != nil {
t.Fatal(err)
}
f.repos["github:other/skills"].push("r2", fixture(t, "grilling", "fresh"))
sts := check(t, s)
if got, want := changes(sts[0]), []string{"-deslop", "+fresh"}; !reflect.DeepEqual(got, want) {
t.Errorf("changes %v, want %v", got, want)
}
d, err := Diff(ctx, sts[0].Changes[0])
if err != nil {
t.Fatal(err)
}
if !strings.Contains(d, "a/deslop/SKILL.md") {
t.Errorf("removal diff:\n%s", d)
}
if err := s.Apply(sts); err != nil {
t.Fatal(err)
}
if got, want := names(t, s), []string{"other/skills:fresh", "other/skills:grilling"}; !reflect.DeepEqual(got, want) {
t.Errorf("installed %v, want %v", got, want)
}
}
func TestCheckHandEdits(t *testing.T) {
ctx := context.Background()
s, _ := newStore(t)
if _, err := s.Add(ctx, AddRequest{URL: "github:mp/skills", Skills: pick("tdd")}); err != nil {
t.Fatal(err)
}
// Drop mp and add other by editing skills.json directly.
path := filepath.Join(s.Dir, ManifestFile)
m, err := manifest.Load(path)
if err != nil {
t.Fatal(err)
}
delete(m.Sources, "mp/skills")
m.Sources["other/skills"] = &manifest.Source{URL: "github:other/skills", Skills: manifest.Selection{Items: pick("deslop")}}
if err := m.Save(path); err != nil {
t.Fatal(err)
}
sts := check(t, s)
if len(sts) != 2 {
t.Fatalf("statuses %+v", sts)
}
if got := changes(sts[0]); sts[0].Source != "mp/skills" || !reflect.DeepEqual(got, []string{"-tdd"}) {
t.Errorf("mp: %s %v", sts[0].Source, got)
}
if got := changes(sts[1]); sts[1].OldRev != "" || !reflect.DeepEqual(got, []string{"+deslop"}) {
t.Errorf("other: %v", got)
}
msg := CommitMessage(sts)
if !strings.HasPrefix(msg, "skills: remove mp/skills, add other/skills@r1\n") {
t.Errorf("commit message:\n%s", msg)
}
if err := s.Apply(sts); err != nil {
t.Fatal(err)
}
if got, want := names(t, s), []string{"other/skills:deslop"}; !reflect.DeepEqual(got, want) {
t.Errorf("installed %v, want %v", got, want)
}
}
func TestCheckNames(t *testing.T) {
ctx := context.Background()
s, _ := newStore(t)
if _, err := s.Add(ctx, AddRequest{URL: "github:mp/skills", Skills: pick("tdd")}); err != nil {
t.Fatal(err)
}
if _, err := s.Add(ctx, AddRequest{URL: "github:other/skills", Skills: pick("deslop")}); err != nil {
t.Fatal(err)
}
for name, want := range map[string]string{"deslop": "other/skills", "mp/skills": "mp/skills"} {
if sts := check(t, s, name); len(sts) != 1 || sts[0].Source != want {
t.Errorf("Check(%q) = %+v, want only %s", name, sts, want)
}
}
if _, err := s.Check(ctx, "nope"); err == nil {
t.Error("want error for an unknown name")
}
}
// TestEndToEnd drives add, check and apply through the real nix against a local git repo.
func TestEndToEnd(t *testing.T) {
if _, err := exec.LookPath("nix"); err != nil {
t.Skip("nix not on PATH")
}
ctx := context.Background()
repo := t.TempDir()
write := func(rel, content string) {
path := filepath.Join(repo, rel)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
git := func(args ...string) string {
out, err := exec.Command("git", append([]string{"-C", repo, "-c", "user.name=t", "-c", "user.email=t@t"}, args...)...).CombinedOutput()
if err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
return strings.TrimSpace(string(out))
}
write("skills/a/SKILL.md", "a v1\n")
write("skills/b/SKILL.md", "b v1\n")
git("init", "-q", "-b", "main")
git("add", ".")
git("commit", "-q", "-m", "v1")
s := Store{Dir: t.TempDir(), Fetcher: fetch.Nix{}}
if _, err := s.Add(ctx, AddRequest{Name: "local", URL: "git+file://" + repo, Ref: "main", Skills: pick("a")}); err != nil {
t.Fatal(err)
}
v1 := git("rev-parse", "HEAD")
if rev := lockedRev(t, s, "local"); rev != v1 {
t.Fatalf("locked %q, want %q", rev, v1)
}
write("skills/a/SKILL.md", "a v2\n")
git("commit", "-q", "-am", "v2")
sts := check(t, s)
if got := changes(sts[0]); !reflect.DeepEqual(got, []string{"↑a"}) {
t.Fatalf("changes %v", got)
}
d, err := Diff(ctx, sts[0].Changes[0])
if err != nil {
t.Fatal(err)
}
if !strings.Contains(d, "-a v1") || !strings.Contains(d, "+a v2") {
t.Errorf("diff:\n%s", d)
}
if err := s.Apply(sts); err != nil {
t.Fatal(err)
}
if rev, v2 := lockedRev(t, s, "local"), git("rev-parse", "HEAD"); rev != v2 {
t.Errorf("locked %q, want %q", rev, v2)
}
}
+98
View File
@@ -0,0 +1,98 @@
// Package fetch resolves flake refs to pinned store paths.
package fetch
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/url"
"os/exec"
"strings"
)
// Result is a source fetched into the Nix store.
type Result struct {
StorePath string
// Locked holds the attrs to pass to builtins.fetchTree, including narHash.
Locked map[string]any
}
// Rev returns the locked commit.
func (r Result) Rev() string {
rev, _ := r.Locked["rev"].(string)
return rev
}
type Fetcher interface {
Prefetch(ctx context.Context, flakeRef string) (Result, error)
}
// WithParam adds or replaces a query parameter on a flake ref, e.g. ref or rev.
func WithParam(flakeRef, key, value string) string {
return editQuery(flakeRef, func(q url.Values) { q.Set(key, value) })
}
// AtRev pins a flake ref to a commit. Shorthand refs (github:, gitlab:, sourcehut:)
// reject ref and rev together, so their ref is dropped; git refs keep it because
// the rev must be reachable from it.
func AtRev(flakeRef, rev string) string {
base, _, _ := strings.Cut(flakeRef, "?")
shorthand := !strings.Contains(base, "://")
return editQuery(flakeRef, func(q url.Values) {
if shorthand {
q.Del("ref")
}
q.Set("rev", rev)
})
}
func editQuery(flakeRef string, edit func(url.Values)) string {
base, query, _ := strings.Cut(flakeRef, "?")
q, err := url.ParseQuery(query)
if err != nil {
q = url.Values{}
}
edit(q)
if len(q) == 0 {
return base
}
return base + "?" + q.Encode()
}
// Nix fetches with `nix flake prefetch`.
type Nix struct {
// Bin is the nix executable; empty means "nix" from PATH.
Bin string
}
func (n Nix) Prefetch(ctx context.Context, flakeRef string) (Result, error) {
bin := n.Bin
if bin == "" {
bin = "nix"
}
cmd := exec.CommandContext(ctx, bin,
"--extra-experimental-features", "nix-command flakes",
"flake", "prefetch", "--json", flakeRef)
var stderr bytes.Buffer
cmd.Stderr = &stderr
out, err := cmd.Output()
if err != nil {
return Result{}, fmt.Errorf("nix flake prefetch %s: %w: %s", flakeRef, err, strings.TrimSpace(stderr.String()))
}
var raw struct {
Hash string `json:"hash"`
Locked map[string]any `json:"locked"`
StorePath string `json:"storePath"`
}
if err := json.Unmarshal(out, &raw); err != nil {
return Result{}, fmt.Errorf("parse prefetch output for %s: %w", flakeRef, err)
}
if raw.Hash == "" || raw.StorePath == "" || raw.Locked == nil {
return Result{}, fmt.Errorf("incomplete prefetch output for %s: %s", flakeRef, out)
}
// prefetch reports the hash beside locked, but fetchTree needs it inside.
raw.Locked["narHash"] = raw.Hash
return Result{StorePath: raw.StorePath, Locked: raw.Locked}, nil
}
+84
View File
@@ -0,0 +1,84 @@
package fetch
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestWithParam(t *testing.T) {
cases := []struct{ in, key, val, want string }{
{"github:o/r", "ref", "main", "github:o/r?ref=main"},
{"git+ssh://git@h/o/r?ref=main", "rev", "abc", "git+ssh://git@h/o/r?ref=main&rev=abc"},
{"github:o/r?ref=old", "ref", "v2", "github:o/r?ref=v2"},
}
for _, c := range cases {
if got := WithParam(c.in, c.key, c.val); got != c.want {
t.Errorf("WithParam(%q, %q, %q) = %q, want %q", c.in, c.key, c.val, got, c.want)
}
}
}
func TestAtRev(t *testing.T) {
cases := map[string]string{
"github:o/r?ref=main": "github:o/r?rev=abc",
"git+ssh://h/o/r?ref=main": "git+ssh://h/o/r?ref=main&rev=abc",
"git+file:///tmp/r": "git+file:///tmp/r?rev=abc",
}
for in, want := range cases {
if got := AtRev(in, "abc"); got != want {
t.Errorf("AtRev(%q) = %q, want %q", in, got, want)
}
}
}
// TestNixPrefetch runs the real nix against a local git repo. No network.
func TestNixPrefetch(t *testing.T) {
// Not on PATH inside the build sandbox, where nix can't run anyway.
if _, err := exec.LookPath("nix"); err != nil {
t.Skip("nix not on PATH")
}
repo := t.TempDir()
write(t, filepath.Join(repo, "tdd", "SKILL.md"), "# tdd\n")
git(t, repo, "init", "-q", "-b", "main")
git(t, repo, "add", ".")
git(t, repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "init")
head := strings.TrimSpace(git(t, repo, "rev-parse", "HEAD"))
res, err := Nix{}.Prefetch(context.Background(), WithParam("git+file://"+repo, "ref", "main"))
if err != nil {
t.Fatal(err)
}
if res.Rev() != head {
t.Errorf("rev = %q, want %q", res.Rev(), head)
}
if h, _ := res.Locked["narHash"].(string); !strings.HasPrefix(h, "sha256-") {
t.Errorf("narHash = %q, want sha256-…", h)
}
if _, err := os.Stat(filepath.Join(res.StorePath, "tdd", "SKILL.md")); err != nil {
t.Errorf("skill missing from store path: %v", err)
}
}
func write(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
func git(t *testing.T, dir string, args ...string) string {
t.Helper()
out, err := exec.Command("git", append([]string{"-C", dir}, args...)...).CombinedOutput()
if err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
return string(out)
}
+56
View File
@@ -0,0 +1,56 @@
// Package jsonfile reads and atomically writes the hand-editable JSON files.
package jsonfile
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
)
// Read decodes path into v. A missing file leaves v untouched and reports false.
func Read(path string, v any) (bool, error) {
b, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return false, nil
}
if err != nil {
return false, err
}
if err := json.Unmarshal(b, v); err != nil {
return false, fmt.Errorf("%s: %w", path, err)
}
return true, nil
}
// Write encodes v with two-space indent and replaces path atomically.
func Write(path string, v any) error {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
// Keep "&" in flake ref queries readable.
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(v); err != nil {
return err
}
tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
if _, err := tmp.Write(buf.Bytes()); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
if err := os.Chmod(tmp.Name(), 0o644); err != nil {
return err
}
return os.Rename(tmp.Name(), path)
}
+45
View File
@@ -0,0 +1,45 @@
// Package lock is skills.lock.json: what each source is pinned to. Only skm writes it.
package lock
import (
"fmt"
"skill-manager/internal/jsonfile"
)
const version = 1
type Lock struct {
Version int `json:"version"`
Sources map[string]*Source `json:"sources"`
}
type Source struct {
// Locked is passed verbatim to builtins.fetchTree.
Locked map[string]any `json:"locked"`
// Skills maps installed name to the skill's directory in the source.
Skills map[string]string `json:"skills"`
}
func (s Source) Rev() string {
rev, _ := s.Locked["rev"].(string)
return rev
}
func Load(path string) (*Lock, error) {
l := &Lock{Version: version}
if _, err := jsonfile.Read(path, l); err != nil {
return nil, err
}
if l.Version != version {
return nil, fmt.Errorf("%s: unsupported lock version %d", path, l.Version)
}
if l.Sources == nil {
l.Sources = map[string]*Source{}
}
return l, nil
}
func (l *Lock) Save(path string) error {
return jsonfile.Write(path, l)
}
+98
View File
@@ -0,0 +1,98 @@
// Package manifest is skills.json: the sources and skills you want.
package manifest
import (
"encoding/json"
"fmt"
"skill-manager/internal/jsonfile"
)
type Manifest struct {
Sources map[string]*Source `json:"sources"`
}
type Source struct {
// URL is a flake ref, e.g. github:owner/repo or git+ssh://git@host/user/repo.
URL string `json:"url"`
// Ref is the branch or tag to track; empty means the default branch.
Ref string `json:"ref,omitempty"`
Skills Selection `json:"skills"`
}
// Selection is either "*" (every skill in the repo) or a list of skills.
type Selection struct {
All bool
Items []Skill
}
// Skill names a skill in its repo and optionally renames it on install.
type Skill struct {
Name string `json:"name"`
// Path picks one skill when the repo has several with this name.
Path string `json:"path,omitempty"`
As string `json:"as,omitempty"`
}
// Installed is the name the skill gets on disk.
func (k Skill) Installed() string {
if k.As != "" {
return k.As
}
return k.Name
}
func Load(path string) (*Manifest, error) {
m := &Manifest{}
if _, err := jsonfile.Read(path, m); err != nil {
return nil, err
}
if m.Sources == nil {
m.Sources = map[string]*Source{}
}
return m, nil
}
func (m *Manifest) Save(path string) error {
return jsonfile.Write(path, m)
}
func (s Selection) MarshalJSON() ([]byte, error) {
if s.All {
return json.Marshal("*")
}
if s.Items == nil {
return []byte("[]"), nil
}
return json.Marshal(s.Items)
}
func (s *Selection) UnmarshalJSON(b []byte) error {
var str string
if json.Unmarshal(b, &str) == nil {
if str != "*" {
return fmt.Errorf(`skills must be "*" or a list, got %q`, str)
}
*s = Selection{All: true}
return nil
}
*s = Selection{}
return json.Unmarshal(b, &s.Items)
}
// A skill is written as "name", or as an object when it has a path or alias.
func (k Skill) MarshalJSON() ([]byte, error) {
if k.As == "" && k.Path == "" {
return json.Marshal(k.Name)
}
type plain Skill
return json.Marshal(plain(k))
}
func (k *Skill) UnmarshalJSON(b []byte) error {
if json.Unmarshal(b, &k.Name) == nil {
return nil
}
type plain Skill
return json.Unmarshal(b, (*plain)(k))
}
+47
View File
@@ -0,0 +1,47 @@
package manifest
import (
"encoding/json"
"reflect"
"testing"
)
func TestSelectionJSON(t *testing.T) {
cases := []struct {
json string
sel Selection
}{
{`"*"`, Selection{All: true}},
{`[]`, Selection{}},
{`["tdd",{"name":"grilling","as":"grilling-mp"}]`, Selection{Items: []Skill{
{Name: "tdd"},
{Name: "grilling", As: "grilling-mp"},
}}},
}
for _, c := range cases {
var got Selection
if err := json.Unmarshal([]byte(c.json), &got); err != nil {
t.Fatalf("unmarshal %s: %v", c.json, err)
}
if c.sel.Items == nil && got.Items != nil && len(got.Items) == 0 {
got.Items = nil
}
if !reflect.DeepEqual(got, c.sel) {
t.Errorf("unmarshal %s = %+v, want %+v", c.json, got, c.sel)
}
out, err := json.Marshal(c.sel)
if err != nil {
t.Fatal(err)
}
if string(out) != c.json {
t.Errorf("marshal %+v = %s, want %s", c.sel, out, c.json)
}
}
}
func TestSelectionRejectsOtherStrings(t *testing.T) {
var s Selection
if err := json.Unmarshal([]byte(`"tdd"`), &s); err == nil {
t.Error("want error for a bare skill name")
}
}
+84
View File
@@ -0,0 +1,84 @@
// Package skills finds skills inside a fetched source.
package skills
import (
"bufio"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
)
// Skill is a directory containing SKILL.md.
type Skill struct {
// Name comes from the SKILL.md frontmatter, falling back to the directory name.
// Names aren't unique: plugin monorepos ship the same skill in several places.
Name string
// Path is slash-separated and relative to the source root ("." for a repo
// that is itself one skill).
Path string
}
// Discover returns every skill under root in lexical walk order. Skills don't nest.
func Discover(root string) ([]Skill, error) {
var found []Skill
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() {
return nil
}
if d.Name() == ".git" {
return filepath.SkipDir
}
skillFile := filepath.Join(path, "SKILL.md")
if _, err := os.Stat(skillFile); err != nil {
return nil
}
rel, err := filepath.Rel(root, path)
if err != nil {
return err
}
rel = filepath.ToSlash(rel)
name, err := frontmatterName(skillFile)
if err != nil {
return err
}
if name == "" {
if rel == "." {
return fmt.Errorf("SKILL.md at the repo root has no name in its frontmatter")
}
name = d.Name()
}
found = append(found, Skill{Name: name, Path: rel})
return filepath.SkipDir
})
return found, err
}
// frontmatterName reads `name:` from the YAML frontmatter, or "" if absent.
func frontmatterName(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
sc := bufio.NewScanner(f)
if !sc.Scan() || strings.TrimSpace(sc.Text()) != "---" {
return "", sc.Err()
}
for sc.Scan() {
line := sc.Text()
if strings.TrimSpace(line) == "---" {
break
}
if v, ok := strings.CutPrefix(line, "name:"); ok {
return strings.Trim(strings.TrimSpace(v), `"'`), nil
}
}
return "", sc.Err()
}
+63
View File
@@ -0,0 +1,63 @@
package skills
import (
"os"
"path/filepath"
"reflect"
"testing"
)
func write(t *testing.T, root, rel, content string) {
t.Helper()
path := filepath.Join(root, rel)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
func TestDiscover(t *testing.T) {
root := t.TempDir()
write(t, root, "skills/tdd/SKILL.md", "# no frontmatter\n")
write(t, root, "skills/grill/SKILL.md", "---\nname: \"grilling\"\ndescription: x\n---\n")
// Skills don't nest: this one belongs to tdd.
write(t, root, "skills/tdd/examples/inner/SKILL.md", "")
write(t, root, ".git/hooks/SKILL.md", "")
write(t, root, "README.md", "")
got, err := Discover(root)
if err != nil {
t.Fatal(err)
}
want := []Skill{{Name: "grilling", Path: "skills/grill"}, {Name: "tdd", Path: "skills/tdd"}}
if !reflect.DeepEqual(got, want) {
t.Errorf("got %v, want %v", got, want)
}
}
func TestDiscoverRootSkill(t *testing.T) {
root := t.TempDir()
write(t, root, "SKILL.md", "---\nname: ponytail\n---\n")
got, err := Discover(root)
if err != nil {
t.Fatal(err)
}
if want := []Skill{{Name: "ponytail", Path: "."}}; !reflect.DeepEqual(got, want) {
t.Errorf("got %v, want %v", got, want)
}
}
func TestDiscoverDuplicateNames(t *testing.T) {
root := t.TempDir()
write(t, root, "a/tdd/SKILL.md", "")
write(t, root, "b/tdd/SKILL.md", "")
got, err := Discover(root)
if err != nil {
t.Fatal(err)
}
if want := []Skill{{Name: "tdd", Path: "a/tdd"}, {Name: "tdd", Path: "b/tdd"}}; !reflect.DeepEqual(got, want) {
t.Errorf("got %v, want %v", got, want)
}
}