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)
}
}