// Package core implements skm's operations on the manifest and lock. The CLI and // the TUI both call into it. package core import ( "cmp" "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 // Agents to add, by name or path; ignored when AllAgents is set. Agents []manifest.Skill AllAgents bool } // NoSelectionError is returned by Add when neither skills nor All were given. type NoSelectionError struct { Source string Available []skills.Skill AvailableAgents []skills.Skill } func (e *NoSelectionError) Error() string { msg := fmt.Sprintf("no skills selected from %s; available: %s", e.Source, available(e.Available)) if len(e.AvailableAgents) > 0 { msg += "; agents: " + available(e.AvailableAgents) } return msg } 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, src, ref, err := target(m, l, req) if err != nil { return "", err } res, found, agents, err := s.fetchSource(ctx, ref) if err != nil { return "", fmt.Errorf("%s: %w", key, err) } if !req.All && len(req.Skills) == 0 && !req.AllAgents && len(req.Agents) == 0 { return "", &NoSelectionError{Source: key, Available: found, AvailableAgents: agents} } if err := selectInto(&src.Skills, req.Skills, req.All, found, key, "skill"); err != nil { return "", err } if err := selectInto(&src.Agents, req.Agents, req.AllAgents, agents, key, "agent"); err != nil { return "", err } resolved, err := resolve(src.Skills, found, "skill") if err != nil { return "", fmt.Errorf("%s: %w", key, err) } resolvedAgents, err := resolve(src.Agents, agents, "agent") if err != nil { return "", fmt.Errorf("%s: %w", key, err) } m.Sources[key] = src l.Sources[key] = &lock.Source{Locked: res.Locked, Skills: resolved, Agents: resolvedAgents} return key, s.save(m, l) } // selectInto adds the requested entries of one kind to sel, or switches it to "*". func selectInto(sel *manifest.Selection, req []manifest.Skill, all bool, found []skills.Skill, key, kind string) error { switch { case all: *sel = manifest.Selection{All: true} case len(req) == 0: case sel.All: return fmt.Errorf("source %q already installs every %s", key, kind) default: for _, k := range req { 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 %s at %s", key, kind, k.Path) } k.Name = found[i].Name } if slices.ContainsFunc(sel.Items, func(e manifest.Skill) bool { return e.Installed() == k.Installed() }) { return fmt.Errorf("%s is already installed from %s", k.Installed(), key) } sel.Items = append(sel.Items, k) } } return nil } // target resolves the source an add goes to and the flake ref to fetch: the pinned // rev for a tracked source, the head of its ref for a new one. src is a copy that // is safe to modify. func target(m *manifest.Manifest, l *lock.Lock, req AddRequest) (key string, src *manifest.Source, ref string, err error) { key = req.Name if key == "" { key = SourceKey(req.URL) } existing := m.Sources[key] if existing == nil { src = &manifest.Source{URL: req.URL, Ref: req.Ref} return key, src, flakeRef(src), nil } if existing.URL != req.URL { return "", nil, "", fmt.Errorf("source %q already exists with url %s; pick another name with --name", key, existing.URL) } if req.Ref != "" && req.Ref != existing.Ref { return "", nil, "", fmt.Errorf("source %q tracks ref %q; add a second source with --name to track %q", key, existing.Ref, req.Ref) } locked := l.Sources[key] if locked == nil { return "", nil, "", fmt.Errorf("source %q is in %s but not locked; run skm update %s first", key, ManifestFile, key) } src = &manifest.Source{URL: existing.URL, Ref: existing.Ref, Skills: manifest.Selection{All: existing.Skills.All, Items: slices.Clone(existing.Skills.Items)}, Agents: manifest.Selection{All: existing.Agents.All, Items: slices.Clone(existing.Agents.Items)}, } return key, src, fetch.AtRev(flakeRef(src), locked.Rev()), nil } // Select turns skills chosen from found into manifest entries. Names that appear // more than once in found get their path, so the entry stays unambiguous. func Select(found, chosen []skills.Skill) []manifest.Skill { count := map[string]int{} for _, f := range found { count[f.Name]++ } var out []manifest.Skill for _, c := range chosen { k := manifest.Skill{Name: c.Name} if count[c.Name] > 1 { k.Path = c.Path } out = append(out, k) } return out } // Available lists the skills Add would choose from, and which of their paths are // already installed from that source. func (s Store) Available(ctx context.Context, req AddRequest) ([]skills.Skill, map[string]bool, error) { m, l, err := s.load() if err != nil { return nil, nil, err } key, _, ref, err := target(m, l, req) if err != nil { return nil, nil, err } _, found, _, err := s.fetchSource(ctx, ref) if err != nil { return nil, nil, fmt.Errorf("%s: %w", key, err) } installed := map[string]bool{} if locked := l.Sources[key]; locked != nil { for _, path := range locked.Skills { installed[path] = true } } return found, installed, nil } // fetchSource prefetches ref and finds its skills and agent definitions. func (s Store) fetchSource(ctx context.Context, ref string) (fetch.Result, []skills.Skill, []skills.Skill, error) { res, err := s.Fetcher.Prefetch(ctx, ref) if err != nil { return fetch.Result{}, nil, nil, err } found, err := skills.Discover(res.StorePath) if err != nil { return fetch.Result{}, nil, nil, err } agents, err := skills.DiscoverAgents(res.StorePath) if err != nil { return fetch.Result{}, nil, nil, err } if len(found) == 0 && len(agents) == 0 { return fetch.Result{}, nil, nil, fmt.Errorf("%s contains no SKILL.md or agent definition", ref) } return res, found, agents, nil } // fetchSkills is fetchSource for callers that only install skills. func (s Store) fetchSkills(ctx context.Context, ref string) (fetch.Result, []skills.Skill, error) { res, found, _, err := s.fetchSource(ctx, ref) if err == nil && len(found) == 0 { err = fmt.Errorf("%s contains no SKILL.md", ref) } return res, found, err } // resolve maps installed names to paths within the source. func resolve(sel manifest.Selection, found []skills.Skill, kind string) (map[string]string, error) { out := map[string]string{} add := func(name, path string) error { if prev, dup := out[name]; dup { return fmt.Errorf("two %ss installed as %q: %s and %s", kind, 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 %ss explicitly, picking one with "path"`, err, kind) } } 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 %s %q at %s", kind, k.Name, k.Path) case len(matches) == 0: return nil, fmt.Errorf("no %s %q; available: %s", kind, 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 %ss named %q (%s); pick one with "path"`, kind, 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 { for _, kind := range []string{"skill", "agent"} { owner := map[string]string{} for _, key := range slices.Sorted(maps.Keys(l.Sources)) { installed := l.Sources[key].Skills if kind == "agent" { installed = l.Sources[key].Agents } for _, name := range slices.Sorted(maps.Keys(installed)) { if prev, ok := owner[name]; ok { return fmt.Errorf(`%s %q comes from both %s and %s; rename one with "as"`, kind, 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) { return s.removeOne(name, false) } // RemoveAgent drops one installed agent definition, like Remove. func (s Store) RemoveAgent(name string) (string, error) { return s.removeOne(name, true) } func (s Store) removeOne(name string, agent bool) (string, error) { kind := "skill" if agent { kind = "agent" } m, l, err := s.load() if err != nil { return "", err } for _, key := range slices.Sorted(maps.Keys(m.Sources)) { src := m.Sources[key] sel, locks := &src.Skills, func(ls *lock.Source) map[string]string { return ls.Skills } if agent { sel, locks = &src.Agents, func(ls *lock.Source) map[string]string { return ls.Agents } } i := slices.IndexFunc(sel.Items, func(k manifest.Skill) bool { return k.Installed() == name }) locked := l.Sources[key] != nil && has(locks(l.Sources[key]), name) if i < 0 && !locked { continue } if sel.All { return "", fmt.Errorf(`%s comes from %s, which installs every %s ("*"); remove the whole source with --source %s`, name, key, kind, key) } if i >= 0 { sel.Items = slices.Delete(sel.Items, i, i+1) } if locked { delete(locks(l.Sources[key]), name) } if src.Empty() { delete(m.Sources, key) delete(l.Sources, key) } return key, s.save(m, l) } return "", fmt.Errorf("no installed %s %q", kind, name) } func has(m map[string]string, name string) bool { _, ok := m[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 // Agent is set for an agent definition, which Path names as a file. Agent bool } // List returns the locked skills and agents, 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()}) } for name, path := range src.Agents { out = append(out, Installed{Name: name, Source: key, Path: path, Rev: src.Rev(), Agent: true}) } } slices.SortFunc(out, func(a, b Installed) int { return cmp.Or(strings.Compare(a.Name, b.Name), compareBool(a.Agent, b.Agent)) }) return out, nil } func compareBool(a, b bool) int { switch { case a == b: return 0 case b: return -1 } return 1 }