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 or agent that differs between the lock and upstream. type Change struct { Name string Kind ChangeKind // Agent is set for an agent definition, whose Old and New are files, not directories. Agent bool // Skill directories (or agent files) in the store; empty when added or removed, // and Old is also empty for a source dropped from the manifest. Old, New string } // Label is Name, marked when the change is an agent. func (c Change) Label() string { if c.Agent { return "agent " + c.Name } return c.Name } // 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 or agent %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 } if _, ok := src.Agents[name]; ok { return key, true } } for key, src := range m.Sources { named := func(k manifest.Skill) bool { return k.Installed() == name } if slices.ContainsFunc(src.Skills.Items, named) || slices.ContainsFunc(src.Agents.Items, named) { 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}) } for _, name := range slices.Sorted(maps.Keys(locked.Agents)) { st.Changes = append(st.Changes, Change{Name: name, Kind: Removed, Agent: true}) } 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) var agents []skills.Skill if err == nil { agents, err = skills.DiscoverAgents(res.StorePath) } if err == nil { st.next = &lock.Source{Locked: res.Locked} st.next.Skills, err = resolve(src.Skills, found, "skill") } if err == nil { st.next.Agents, err = resolve(src.Agents, agents, "agent") } if err != nil { st.Err = err return st } for _, kind := range []struct { old, new map[string]string agent bool }{ {locked.Skills, st.next.Skills, false}, {locked.Agents, st.next.Agents, true}, } { changes, err := compare(ctx, kind.old, kind.new, oldRoot, res.StorePath, kind.agent) if err != nil { st.Err = err return st } st.Changes = append(st.Changes, changes...) } return st } // compare lists the entries of one kind that differ between the locked paths (in // oldRoot) and the resolved ones (in newRoot), sorted by name. func compare(ctx context.Context, locked, next map[string]string, oldRoot, newRoot string, agent bool) ([]Change, error) { names := slices.Sorted(maps.Keys(locked)) for name := range next { if _, ok := locked[name]; !ok { names = append(names, name) } } slices.Sort(names) var out []Change for _, name := range names { oldPath, wasLocked := locked[name] newPath, stays := next[name] ch := Change{Name: name, Agent: agent} if wasLocked { ch.Old = filepath.Join(oldRoot, oldPath) } if stays { ch.New = filepath.Join(newRoot, newPath) } switch { case !stays: ch.Kind = Removed case !wasLocked: ch.Kind = Added default: same, err := sameDir(ctx, ch.Old, ch.New) if err != nil { return nil, err } if same { continue } ch.Kind = Modified } out = append(out, ch) } return out, nil } // 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.Label()) } } return "skills: " + strings.Join(heads, ", ") + "\n\n" + strings.Join(body, "\n") } // Diff renders a change as a unified diff with a/ and b/ paths. func Diff(ctx context.Context, ch Change) (string, error) { // An added or removed agent is a file, so it needs an empty file to compare with. var empty string if ch.Agent { f, err := os.CreateTemp("", "skm-empty-") if err != nil { return "", err } f.Close() empty = f.Name() } else { var err error if empty, err = os.MkdirTemp("", "skm-empty-"); 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 }