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