From 65a96ada8efad20c0bcf973bc9684842b273754c Mon Sep 17 00:00:00 2001 From: Johannes Kresner Date: Fri, 23 Oct 2026 14:04:50 +0200 Subject: [PATCH] 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 --- .gitignore | 13 ++ PLAN.md | 144 +++++++++++++ cmd/skm/import.go | 86 ++++++++ cmd/skm/main.go | 209 ++++++++++++++++++ cmd/skm/update.go | 144 +++++++++++++ devenv.lock | 65 ++++++ devenv.nix | 15 ++ devenv.yaml | 18 ++ flake.lock | 27 +++ flake.nix | 60 ++++++ go.mod | 3 + internal/core/core.go | 333 +++++++++++++++++++++++++++++ internal/core/core_test.go | 212 ++++++++++++++++++ internal/core/import.go | 227 ++++++++++++++++++++ internal/core/import_test.go | 112 ++++++++++ internal/core/update.go | 286 +++++++++++++++++++++++++ internal/core/update_test.go | 238 +++++++++++++++++++++ internal/fetch/fetch.go | 98 +++++++++ internal/fetch/fetch_test.go | 84 ++++++++ internal/jsonfile/jsonfile.go | 56 +++++ internal/lock/lock.go | 45 ++++ internal/manifest/manifest.go | 98 +++++++++ internal/manifest/manifest_test.go | 47 ++++ internal/skills/discover.go | 84 ++++++++ internal/skills/discover_test.go | 63 ++++++ nix/module.nix | 76 +++++++ 26 files changed, 2843 insertions(+) create mode 100644 .gitignore create mode 100644 PLAN.md create mode 100644 cmd/skm/import.go create mode 100644 cmd/skm/main.go create mode 100644 cmd/skm/update.go create mode 100644 devenv.lock create mode 100644 devenv.nix create mode 100644 devenv.yaml create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 go.mod create mode 100644 internal/core/core.go create mode 100644 internal/core/core_test.go create mode 100644 internal/core/import.go create mode 100644 internal/core/import_test.go create mode 100644 internal/core/update.go create mode 100644 internal/core/update_test.go create mode 100644 internal/fetch/fetch.go create mode 100644 internal/fetch/fetch_test.go create mode 100644 internal/jsonfile/jsonfile.go create mode 100644 internal/lock/lock.go create mode 100644 internal/manifest/manifest.go create mode 100644 internal/manifest/manifest_test.go create mode 100644 internal/skills/discover.go create mode 100644 internal/skills/discover_test.go create mode 100644 nix/module.nix diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5747279 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +result +result-* + +# Devenv +.devenv* +devenv.local.nix +devenv.local.yaml + +# direnv +.direnv + +# pre-commit +.pre-commit-config.yaml diff --git a/PLAN.md b/PLAN.md new file mode 100644 index 0000000..4499b1e --- /dev/null +++ b/PLAN.md @@ -0,0 +1,144 @@ +# skm: skill manager + +`skm` installs agent skills from git repos, pins each repo to a commit with a Nix hash, and updates on demand after you review the diff. Nix fetches the pinned sources and links them into place. `skm` only edits the manifest and lockfile. + +It replaces the current setup, where skills are committed as plain copies under `~/Repos/nix/home/agents/skills` and their origin is tracked (without commits) in vercel's `~/.local/state/skills/.skill-lock.json`. + +## Decisions + +| Topic | Decision | +|---|---| +| Source of truth | `skills.json` manifest (hand-edited or edited by `skm`). `skills.lock.json` is written only by `skm`. | +| Location | Both files in `~/Repos/nix/home/agents`. No skill contents in the dotfiles. Own skills live in their own private repo. | +| Sources | Flake refs: `github:owner/repo`, `git+ssh://…`, `git+https://…`. Skills are directories containing `SKILL.md`, at the repo root or in subdirectories. No tarballs, registries, or local paths. | +| Pinning | Per repo. Optional `ref` (branch/tag), default branch otherwise. To hold one skill back, add a second source entry with its own `ref`. | +| Hash | `narHash` (`sha256-…` SRI, same value `fetchFromGitHub` uses), from `nix flake prefetch --json`. | +| Outdated | A skill is outdated only if its own subtree differs between the locked and the new store path. Repo commits that don't touch it don't count. | +| Update | `update [name]` shows the diff of the affected skills and applies after you confirm. `--yes` skips the prompt. | +| Local edits | Impossible (read-only store). Change a skill by forking it or moving it to your own repo. | +| Selection | Named skills, or `"*"` for every skill in the repo. With `*`, `outdated` reports skills added or removed upstream. | +| Name collisions | Error, unless one entry renames its skill with `"as"`. Within one repo names aren't unique (plugin monorepos ship the same skill twice), so an entry can pick one with `"path"`; `"*"` refuses repos with duplicate names. | +| Fetching | Only through `nix flake prefetch`. No git dependency in `skm`. | +| Linking | home-manager links each skill individually to `~/.claude/skills/` and `~/.agents/skills/`. The parent directories stay writable, so Claude's `synced/` dir keeps working. Targets are configurable globally. | +| Rebuild | `skm` prints "run the switch". With `--switch` it runs the configured `switchCommand`. | +| Git | `skm` never commits. It prints a suggested commit message. | +| UI | Go + bubbletea. Subcommands for scripting, plus a dashboard when run with no arguments. | +| Binary | `skm`. Repo stays `skill-manager`. | + +## File formats + +`skills.json`: + +```json +{ + "sources": { + "mattpocock": { + "url": "github:mattpocock/skills", + "skills": ["tdd", "prototype", { "name": "grilling", "as": "grilling-mp" }] + }, + "own": { + "url": "git+ssh://git@//skills", + "ref": "main", + "skills": "*" + } + } +} +``` + +`skills.lock.json` (written by `skm`; `locked` is `nix flake prefetch --json`'s `locked` with its `hash` added as `narHash`): + +```json +{ + "version": 1, + "sources": { + "mattpocock": { + "locked": { "type": "github", "owner": "mattpocock", "repo": "skills", "rev": "abc123…", "narHash": "sha256-…" }, + "skills": { "tdd": "skills/tdd", "prototype": "skills/prototype", "grilling-mp": "skills/grilling" } + } + } +} +``` + +`skills` in the lock maps the installed name to the subpath, already resolved (including the `*` expansion). Nix can then link skills without scanning repos at eval time. + +## Nix side (this repo's flake) + +- `packages.skm`: `buildGoModule`. +- `homeModules.default`, options under `programs.skill-manager`: + - `enable` + - `manifestDir` (string path to the working tree, e.g. `/home/johannes/Repos/nix/home/agents`) + - `lockFile` (path inside the consuming flake, read at eval time; required, because pure eval can't read `manifestDir`) + - `targets` (default `[ ".claude/skills" ".agents/skills" ]`) + - `switchCommand` (string) +- The module reads the lock, calls `builtins.fetchTree source.locked` for each source, and emits `home.file."/".source = "${src}/${subpath}"`. It also writes `~/.config/skill-manager/config.json` with `manifestDir` and `switchCommand`, and installs `skm`. +- `devShells.default`: go, gopls, nix. +- `checks`: Go tests, including the end-to-end test. + +## Required changes in `~/Repos/nix` + +1. Add `skill-manager` as a flake input and import its home-manager module in `homeManager.johannes`. +2. **Rebuild must evaluate as the user** so `fetchTree` on the private `git+ssh` repo uses the user's SSH agent: + - Linux: `nixos-rebuild switch --sudo --flake …` instead of `sudo nixos-rebuild …` (`devenv.nix:85`). + - voyager: `nix build .#darwinConfigurations.voyager.system` as the user, then `sudo ./result/activate` (`devenv.nix:80`). +3. In `modules/home/dotfiles.nix`, drop `".claude/skills".source = live "agents/skills"` and the skills part of `.agents`. The module now owns those paths. +4. After migration: delete `home/agents/skills/*` from git (keep `skills.json`, `skills.lock.json`) and delete `~/.local/state/skills/.skill-lock.json`. + +## CLI + +| Command | Does | +|---|---| +| `skm` | Dashboard | +| `skm add [--ref R] [--name N]` | Prefetch, list `SKILL.md` dirs, pick in TUI (or `--skill a,b=alias`, `--all`), write manifest + lock. Adding to an existing source keeps its pin. | +| `skm remove ` / `--source S` | Remove the skill from the manifest and drop the source when it's empty, or remove a whole source | +| `skm list` | Installed skills with source and short rev | +| `skm outdated` | Prefetch each source's ref in parallel and report changed / added / removed skills | +| `skm update [name…]` | Diff review, then write the lock. `--yes`, `--switch` | +| `skm import [path]` | Read vercel's `.skill-lock.json`, write the manifest, pin HEAD, show the diff against the current `home/agents/skills` copies | + +Global flag: `--dir` overrides `manifestDir`. + +## Dashboard + +- A list of sources, each expanding to its skills, with a status per skill: ✓ up to date, ↑ outdated, ± added/removed upstream, spinner while checking. +- Upstream checks start in the background on open, in parallel across sources. +- Keys: `a` add (URL prompt, then the picker), `d` remove, `u` update the selected source (or `U` for all outdated), `enter` diff review, `q` quit. +- Diff review: a file list on the left, a scrollable diff viewport on the right, `y` accept, `n` skip. +- Every action calls the same core package as the subcommands. The TUI holds no logic of its own. + +## Code layout + +``` +cmd/skm/ main, stdlib flag subcommands +internal/jsonfile/ atomic JSON read/write +internal/manifest/ load/save skills.json, validation, collisions +internal/lock/ load/save skills.lock.json +internal/fetch/ Fetcher interface; nix implementation (nix flake prefetch --json) +internal/skills/ discover SKILL.md dirs, subtree compare, diff generation +internal/core/ add/remove/outdated/update/import operations +internal/tui/ bubbletea models: dashboard, picker, diff review +nix/module.nix home-manager module +flake.nix +``` + +`Fetcher` interface: `Prefetch(url, ref) -> {StorePath, Locked}`. The real implementation shells out to nix. The fake serves fixture directories. + +Diffs are computed in Go between `oldStorePath/subpath` and `newStorePath/subpath`. The old store path comes from prefetching the locked rev, which is cached in the store. + +## Tests + +- Unit: manifest/lock round-trips, collision and alias rules, `*` expansion, subtree change detection, diff output (fake fetcher). +- End-to-end: a temp `git+file://` repo with two skills; `add`, commit upstream, `outdated`, `update --yes`; assert the lock. Needs nix, no network. Nix can't run inside the build sandbox, so these tests skip during `nix flake check` and run via `go test` in the devShell. +- TUI: `teatest` golden files for the dashboard, picker and diff review. + +## Build order + +1. Flake skeleton + devShell, Go module, `Fetcher` with the nix implementation. +2. Manifest/lock packages, `add` (non-interactive), `list`, `remove`. +3. home-manager module; switch `~/Repos/nix` over with one source to prove linking and the eval-as-user rebuild. +4. `outdated`, `update` with a plain-text diff and confirm. +5. `import`; migrate all sources. Find origins for `c4-model` and `create-readme`; move own skills to the private repo. +6. bubbletea: picker, diff review, then the dashboard. + +## Out of scope (v1) + +Non-git sources, patches/overlays, per-skill targets, per-skill pins, auto-commit. diff --git a/cmd/skm/import.go b/cmd/skm/import.go new file mode 100644 index 0000000..f761d8d --- /dev/null +++ b/cmd/skm/import.go @@ -0,0 +1,86 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + "path/filepath" + "text/tabwriter" + + "skill-manager/internal/core" +) + +func importCmd(ctx context.Context, store core.Store, args []string) error { + stateDir := os.Getenv("XDG_STATE_HOME") + if stateDir == "" { + home, err := os.UserHomeDir() + if err != nil { + return err + } + stateDir = filepath.Join(home, ".local", "state") + } + fs := flag.NewFlagSet("import", flag.ContinueOnError) + from := fs.String("from", filepath.Join(stateDir, "skills", ".skill-lock.json"), "vercel skills lock to import") + local := fs.String("local", filepath.Join(store.Dir, "skills"), "directory with the committed skill copies to compare against") + showDiff := fs.Bool("diff", false, "print diffs for skills that differ from your copy (a/ yours, b/ upstream)") + pos, err := parse(fs, args) + if err != nil { + return err + } + if len(pos) != 0 { + return errors.New("import takes no arguments") + } + + rep, err := store.Import(ctx, *from, *local) + if err != nil { + return err + } + + groups := map[core.ImportStatus][]core.Imported{} + for _, imp := range rep.Imported { + groups[imp.Status] = append(groups[imp.Status], imp) + } + fmt.Printf("%d skills from %d sources are in %s\n", len(rep.Imported), rep.Sources, core.ManifestFile) + section := func(title string, items []core.Imported) { + if len(items) == 0 { + return + } + fmt.Printf("\n%s (%d):\n", title, len(items)) + w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) + for _, imp := range items { + fmt.Fprintf(w, " %s\t%s\n", imp.Name, imp.Source) + } + w.Flush() + } + section("identical to your copy", groups[core.Identical]) + section("differ from your copy; upstream replaces it on rebuild, `skm remove ` keeps your copy", groups[core.Differs]) + section("no committed copy", groups[core.NoLocalCopy]) + + if len(rep.Skipped) > 0 { + fmt.Printf("\nskipped (%d):\n", len(rep.Skipped)) + for _, s := range rep.Skipped { + fmt.Println(" " + s) + } + } + if len(rep.Untracked) > 0 { + fmt.Printf("\nnot managed by skm, still committed in %s (%d):\n", *local, len(rep.Untracked)) + for _, name := range rep.Untracked { + fmt.Println(" " + name) + } + } + + if *showDiff { + for _, imp := range groups[core.Differs] { + d, err := core.Diff(ctx, core.Change{Name: imp.Name, Old: imp.Local, New: imp.Upstream}) + if err != nil { + return err + } + fmt.Print("\n" + d) + } + } else if len(groups[core.Differs]) > 0 { + fmt.Println("\nrun `skm import --diff` to see the differences") + } + return nil +} diff --git a/cmd/skm/main.go b/cmd/skm/main.go new file mode 100644 index 0000000..74ab0a0 --- /dev/null +++ b/cmd/skm/main.go @@ -0,0 +1,209 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + "path/filepath" + "strings" + "text/tabwriter" + + "skill-manager/internal/core" + "skill-manager/internal/fetch" + "skill-manager/internal/jsonfile" + "skill-manager/internal/manifest" +) + +const usage = `usage: skm [--dir DIR] [args] + +commands: + add [--ref R] [--name N] (--skill a,b=alias,dir/c | --all) + remove | remove --source + list + outdated [source|skill...] + update [source|skill...] [--yes] [--switch] + import [--from vercel-lock] [--local dir] [--diff] + +--dir defaults to manifestDir from ~/.config/skill-manager/config.json. +` + +type config struct { + ManifestDir string `json:"manifestDir"` + SwitchCommand string `json:"switchCommand"` +} + +func main() { + err := run(context.Background(), os.Args[1:]) + if errors.Is(err, flag.ErrHelp) { + os.Exit(0) + } + if err != nil { + fmt.Fprintln(os.Stderr, "skm:", err) + os.Exit(1) + } +} + +func run(ctx context.Context, args []string) error { + global := flag.NewFlagSet("skm", flag.ContinueOnError) + global.Usage = func() { fmt.Fprint(os.Stderr, usage) } + dir := global.String("dir", "", "directory holding skills.json") + if err := global.Parse(args); err != nil { + return err + } + args = global.Args() + if len(args) == 0 { + global.Usage() + return errors.New("no command") + } + + cfg, err := loadConfig(*dir) + if err != nil { + return err + } + store := core.Store{Dir: cfg.ManifestDir, Fetcher: fetch.Nix{}} + + switch cmd, rest := args[0], args[1:]; cmd { + case "add": + return add(ctx, store, rest) + case "remove": + return remove(store, rest) + case "list": + return list(store, rest) + case "outdated": + return outdated(ctx, store, rest) + case "update": + return update(ctx, store, cfg, rest) + case "import": + return importCmd(ctx, store, rest) + default: + global.Usage() + return fmt.Errorf("unknown command %q", cmd) + } +} + +// loadConfig reads the config the home-manager module writes; --dir overrides manifestDir. +func loadConfig(flagDir string) (config, error) { + // XDG on every OS, macOS included: that's where home-manager's xdg.configFile writes. + cfgDir := os.Getenv("XDG_CONFIG_HOME") + if cfgDir == "" { + home, err := os.UserHomeDir() + if err != nil { + return config{}, err + } + cfgDir = filepath.Join(home, ".config") + } + path := filepath.Join(cfgDir, "skill-manager", "config.json") + var cfg config + if _, err := jsonfile.Read(path, &cfg); err != nil { + return config{}, err + } + if flagDir != "" { + cfg.ManifestDir = flagDir + } + if cfg.ManifestDir == "" { + return config{}, fmt.Errorf("no manifest directory: pass --dir or set manifestDir in %s", path) + } + return cfg, nil +} + +// parse allows flags after positional arguments, which flag.Parse alone does not. +func parse(fs *flag.FlagSet, args []string) ([]string, error) { + var pos []string + for { + if err := fs.Parse(args); err != nil { + return nil, err + } + if fs.NArg() == 0 { + return pos, nil + } + pos = append(pos, fs.Arg(0)) + args = fs.Args()[1:] + } +} + +func add(ctx context.Context, store core.Store, args []string) error { + fs := flag.NewFlagSet("add", flag.ContinueOnError) + ref := fs.String("ref", "", "branch or tag to track (default: the default branch)") + name := fs.String("name", "", "source name (default: owner/repo from the url)") + skillList := fs.String("skill", "", "comma-separated skill names or paths; rename with name=alias") + all := fs.Bool("all", false, "install every skill, including ones added upstream later") + pos, err := parse(fs, args) + if err != nil { + return err + } + if len(pos) != 1 { + return errors.New("add takes exactly one url") + } + + req := core.AddRequest{Name: *name, URL: pos[0], Ref: *ref, All: *all} + for item := range strings.SplitSeq(*skillList, ",") { + if item = strings.TrimSpace(item); item == "" { + continue + } + ref, as, _ := strings.Cut(item, "=") + k := manifest.Skill{Name: ref, As: as} + if strings.Contains(ref, "/") { + k = manifest.Skill{Path: ref, As: as} + } + req.Skills = append(req.Skills, k) + } + + key, err := store.Add(ctx, req) + if sel, ok := errors.AsType[*core.NoSelectionError](err); ok { + fmt.Fprintf(os.Stderr, "skills in %s:\n", sel.Source) + w := tabwriter.NewWriter(os.Stderr, 0, 0, 2, ' ', 0) + for _, s := range sel.Available { + fmt.Fprintf(w, " %s\t%s\n", s.Name, s.Path) + } + w.Flush() + return errors.New("choose with --skill a,b (or a path for same-named skills) or --all") + } + if err != nil { + return err + } + fmt.Printf("added to %s; rebuild to install\n", key) + return nil +} + +func remove(store core.Store, args []string) error { + fs := flag.NewFlagSet("remove", flag.ContinueOnError) + source := fs.String("source", "", "remove a whole source") + pos, err := parse(fs, args) + if err != nil { + return err + } + switch { + case *source != "" && len(pos) == 0: + if err := store.RemoveSource(*source); err != nil { + return err + } + fmt.Printf("removed source %s\n", *source) + case *source == "" && len(pos) == 1: + key, err := store.Remove(pos[0]) + if err != nil { + return err + } + fmt.Printf("removed %s (from %s)\n", pos[0], key) + default: + return errors.New("remove takes one skill name, or --source") + } + return nil +} + +func list(store core.Store, args []string) error { + if len(args) != 0 { + return errors.New("list takes no arguments") + } + installed, err := store.List() + if err != nil { + return err + } + w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) + fmt.Fprintln(w, "NAME\tSOURCE\tREV\tPATH") + for _, s := range installed { + fmt.Fprintf(w, "%s\t%s\t%.7s\t%s\n", s.Name, s.Source, s.Rev, s.Path) + } + return w.Flush() +} diff --git a/cmd/skm/update.go b/cmd/skm/update.go new file mode 100644 index 0000000..6a87cac --- /dev/null +++ b/cmd/skm/update.go @@ -0,0 +1,144 @@ +package main + +import ( + "bufio" + "context" + "errors" + "flag" + "fmt" + "io" + "os" + "os/exec" + "strings" + + "skill-manager/internal/core" +) + +func outdated(ctx context.Context, store core.Store, args []string) error { + statuses, err := store.Check(ctx, args...) + if err != nil { + return err + } + failed, n := 0, 0 + for _, st := range statuses { + if st.Err != nil { + fmt.Fprintf(os.Stderr, "%s: %v\n", st.Source, st.Err) + failed++ + continue + } + if st.Outdated() { + printStatus(os.Stdout, st) + n++ + } + } + if n == 0 && failed == 0 { + fmt.Println("all skills up to date") + } + if failed > 0 { + return fmt.Errorf("%d source(s) failed", failed) + } + return nil +} + +func update(ctx context.Context, store core.Store, cfg config, args []string) error { + fs := flag.NewFlagSet("update", flag.ContinueOnError) + yes := fs.Bool("yes", false, "apply without showing diffs or asking") + doSwitch := fs.Bool("switch", false, "run switchCommand afterwards") + names, err := parse(fs, args) + if err != nil { + return err + } + + statuses, err := store.Check(ctx, names...) + if err != nil { + return err + } + in := bufio.NewReader(os.Stdin) + var accepted []core.SourceStatus + failed := 0 + for _, st := range statuses { + if st.Err != nil { + fmt.Fprintf(os.Stderr, "%s: %v\n", st.Source, st.Err) + failed++ + continue + } + if !st.Outdated() { + continue + } + printStatus(os.Stdout, st) + if !*yes { + for _, ch := range st.Changes { + d, err := core.Diff(ctx, ch) + if err != nil { + return err + } + fmt.Print(d) + } + ok, err := confirm(in, fmt.Sprintf("apply %s? [y/N] ", st.Source)) + if err != nil { + return err + } + if !ok { + continue + } + } + accepted = append(accepted, st) + } + + if len(accepted) > 0 { + if err := store.Apply(accepted); err != nil { + return err + } + fmt.Printf("\nupdated %s. Suggested commit message:\n\n%s\n\n", core.LockFile, core.CommitMessage(accepted)) + if err := rebuild(cfg, *doSwitch); err != nil { + return err + } + } else if failed == 0 { + fmt.Println("nothing to update") + } + if failed > 0 { + return fmt.Errorf("%d source(s) failed", failed) + } + return nil +} + +func printStatus(w io.Writer, st core.SourceStatus) { + switch { + case st.OldRev == "": + fmt.Fprintf(w, "%s (new) → %.7s\n", st.Source, st.NewRev) + case st.NewRev == "": + fmt.Fprintf(w, "%s %.7s (removed from skills.json)\n", st.Source, st.OldRev) + default: + fmt.Fprintf(w, "%s %.7s → %.7s\n", st.Source, st.OldRev, st.NewRev) + } + for _, ch := range st.Changes { + fmt.Fprintf(w, " %s %s\n", ch.Kind.Symbol(), ch.Name) + } +} + +func confirm(in *bufio.Reader, prompt string) (bool, error) { + fmt.Print(prompt) + line, err := in.ReadString('\n') + if err != nil && !errors.Is(err, io.EOF) { + return false, err + } + answer := strings.ToLower(strings.TrimSpace(line)) + return answer == "y" || answer == "yes", nil +} + +func rebuild(cfg config, run bool) error { + if cfg.SwitchCommand == "" { + fmt.Println("rebuild to install") + return nil + } + if !run { + fmt.Printf("rebuild to install: %s\n", cfg.SwitchCommand) + return nil + } + cmd := exec.Command("sh", "-c", cfg.SwitchCommand) + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr + if err := cmd.Run(); err != nil { + return fmt.Errorf("switch command: %w", err) + } + return nil +} diff --git a/devenv.lock b/devenv.lock new file mode 100644 index 0000000..619e257 --- /dev/null +++ b/devenv.lock @@ -0,0 +1,65 @@ +{ + "nodes": { + "devenv": { + "locked": { + "dir": "src/modules", + "lastModified": 1792680408, + "narHash": "sha256-YuGsT2+WYaBrbuobaNeeGS7ogjoEgSxl3m2JR4XbfgU=", + "owner": "cachix", + "repo": "devenv", + "rev": "d9f86dc6fe4cb74c0f9377e5535acc0cdacee721", + "type": "github" + }, + "original": { + "dir": "src/modules", + "owner": "cachix", + "repo": "devenv", + "type": "github" + } + }, + "nixpkgs": { + "inputs": { + "nixpkgs-src": "nixpkgs-src" + }, + "locked": { + "lastModified": 1791812882, + "narHash": "sha256-4AdYH2HoD21mys5lk9NoDcM2Z7iPeEUjxJeGE3Pw278=", + "owner": "cachix", + "repo": "devenv-nixpkgs", + "rev": "760b85220489f69855e6df78a6d1dad5873f8bf6", + "type": "github" + }, + "original": { + "owner": "cachix", + "ref": "rolling", + "repo": "devenv-nixpkgs", + "type": "github" + } + }, + "nixpkgs-src": { + "flake": false, + "locked": { + "lastModified": 1791487292, + "narHash": "sha256-tqM7xDEsaeK1p6VvRygeZ9LkQRpUUkbRT02BHv6hnTM=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "8edc0c72e3a38faf5434e40d1f19431125fe4b30", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "devenv": "devenv", + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} \ No newline at end of file diff --git a/devenv.nix b/devenv.nix new file mode 100644 index 0000000..6f8705e --- /dev/null +++ b/devenv.nix @@ -0,0 +1,15 @@ +{ + pkgs, + lib, + config, + inputs, + ... +}: + +{ + packages = with pkgs; [ + git + ]; + + languages.go.enable = true; +} diff --git a/devenv.yaml b/devenv.yaml new file mode 100644 index 0000000..3dcab58 --- /dev/null +++ b/devenv.yaml @@ -0,0 +1,18 @@ +# yaml-language-server: $schema=https://devenv.sh/devenv.schema.json +inputs: + nixpkgs: + url: github:cachix/devenv-nixpkgs/rolling + +# If you're using non-OSS software, you can set allow_unfree to true. +# allow_unfree: true + +# If you're not willing to allow unsupported packages: +# allow_unsupported_system: false + +# If you're willing to use a package that's vulnerable +# permitted_insecure_packages: +# - "openssl-1.1.1w" + +# If you have more than one devenv you can merge them +#imports: +# - ./backend diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..886d2d9 --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1792502884, + "narHash": "sha256-IoNisKcGbUjdd45qCqywGMCYmZ5EnkxezvLII0FWwNA=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "02c087f3fe673c9e317f206a627cb6b910336dbe", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..6c682f9 --- /dev/null +++ b/flake.nix @@ -0,0 +1,60 @@ +{ + description = "skm: pin and update agent skills from git repos"; + + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + + outputs = + { self, nixpkgs }: + let + systems = [ + "x86_64-linux" + "aarch64-linux" + "x86_64-darwin" + "aarch64-darwin" + ]; + forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system}); + in + { + homeModules.default = import ./nix/module.nix self; + + packages = forAllSystems (pkgs: { + skm = pkgs.buildGoModule { + pname = "skm"; + version = "0.1.0"; + # Only the Go sources: path: inputs copy untracked dirs like .devenv too. + src = pkgs.lib.fileset.toSource { + root = ./.; + fileset = pkgs.lib.fileset.unions [ + ./go.mod + ./cmd + ./internal + ]; + }; + vendorHash = null; + # Tests that need nix skip themselves: it isn't on PATH in the sandbox. + nativeCheckInputs = [ pkgs.git ]; + nativeBuildInputs = [ pkgs.makeWrapper ]; + # nix itself comes from the system, so it matches the daemon. + postInstall = '' + wrapProgram $out/bin/skm --prefix PATH : ${pkgs.lib.makeBinPath [ pkgs.diffutils ]} + ''; + meta.mainProgram = "skm"; + }; + default = self.packages.${pkgs.stdenv.hostPlatform.system}.skm; + }); + + devShells = forAllSystems (pkgs: { + default = pkgs.mkShell { + packages = with pkgs; [ + go + gopls + git + ]; + }; + }); + + checks = forAllSystems (pkgs: { + skm = self.packages.${pkgs.stdenv.hostPlatform.system}.skm; + }); + }; +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..9cf08f3 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module skill-manager + +go 1.26 diff --git a/internal/core/core.go b/internal/core/core.go new file mode 100644 index 0000000..a718446 --- /dev/null +++ b/internal/core/core.go @@ -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 +} diff --git a/internal/core/core_test.go b/internal/core/core_test.go new file mode 100644 index 0000000..c5588a6 --- /dev/null +++ b/internal/core/core_test.go @@ -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//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) + } +} diff --git a/internal/core/import.go b/internal/core/import.go new file mode 100644 index 0000000..a0f7f73 --- /dev/null +++ b/internal/core/import.go @@ -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() +} diff --git a/internal/core/import_test.go b/internal/core/import_test.go new file mode 100644 index 0000000..83c1c47 --- /dev/null +++ b/internal/core/import_test.go @@ -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) + } +} diff --git a/internal/core/update.go b/internal/core/update.go new file mode 100644 index 0000000..d3ae7c0 --- /dev/null +++ b/internal/core/update.go @@ -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/ and b/ 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 +} diff --git a/internal/core/update_test.go b/internal/core/update_test.go new file mode 100644 index 0000000..d5b29ed --- /dev/null +++ b/internal/core/update_test.go @@ -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) + } +} diff --git a/internal/fetch/fetch.go b/internal/fetch/fetch.go new file mode 100644 index 0000000..3bfbc23 --- /dev/null +++ b/internal/fetch/fetch.go @@ -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 +} diff --git a/internal/fetch/fetch_test.go b/internal/fetch/fetch_test.go new file mode 100644 index 0000000..6da7033 --- /dev/null +++ b/internal/fetch/fetch_test.go @@ -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) +} diff --git a/internal/jsonfile/jsonfile.go b/internal/jsonfile/jsonfile.go new file mode 100644 index 0000000..4498354 --- /dev/null +++ b/internal/jsonfile/jsonfile.go @@ -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) +} diff --git a/internal/lock/lock.go b/internal/lock/lock.go new file mode 100644 index 0000000..b4a9489 --- /dev/null +++ b/internal/lock/lock.go @@ -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) +} diff --git a/internal/manifest/manifest.go b/internal/manifest/manifest.go new file mode 100644 index 0000000..3efa139 --- /dev/null +++ b/internal/manifest/manifest.go @@ -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)) +} diff --git a/internal/manifest/manifest_test.go b/internal/manifest/manifest_test.go new file mode 100644 index 0000000..37a7bb7 --- /dev/null +++ b/internal/manifest/manifest_test.go @@ -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") + } +} diff --git a/internal/skills/discover.go b/internal/skills/discover.go new file mode 100644 index 0000000..bb5b00a --- /dev/null +++ b/internal/skills/discover.go @@ -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() +} diff --git a/internal/skills/discover_test.go b/internal/skills/discover_test.go new file mode 100644 index 0000000..76bc8ff --- /dev/null +++ b/internal/skills/discover_test.go @@ -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) + } +} diff --git a/nix/module.nix b/nix/module.nix new file mode 100644 index 0000000..7a7e352 --- /dev/null +++ b/nix/module.nix @@ -0,0 +1,76 @@ +self: +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.programs.skill-manager; + inherit (lib) mkOption types; + + # installed name -> store path of the skill directory + skills = lib.concatMapAttrs ( + _: src: + let + tree = builtins.fetchTree src.locked; + in + lib.mapAttrs (_: path: if path == "." then "${tree}" else "${tree}/${path}") src.skills + ) (lib.importJSON cfg.lockFile).sources; +in +{ + options.programs.skill-manager = { + enable = lib.mkEnableOption "skm and the skills pinned in its lock file"; + + package = mkOption { + type = types.package; + default = self.packages.${pkgs.stdenv.hostPlatform.system}.skm; + defaultText = lib.literalExpression "skill-manager.packages.\${system}.skm"; + }; + + manifestDir = mkOption { + type = types.str; + example = "/home/me/Repos/nix/home/agents"; + description = "Working-tree directory holding skills.json and skills.lock.json. skm writes here."; + }; + + lockFile = mkOption { + type = types.path; + example = lib.literalExpression "./home/agents/skills.lock.json"; + description = '' + skills.lock.json as a path inside your flake, read at evaluation time. + Same file as in manifestDir; pure evaluation can't read manifestDir directly. + ''; + }; + + targets = mkOption { + type = types.listOf types.str; + default = [ + ".claude/skills" + ".agents/skills" + ]; + description = "Directories, relative to home, that get one symlink per skill."; + }; + + switchCommand = mkOption { + type = types.str; + default = ""; + example = "cd ~/Repos/nix && devenv shell rebuild"; + description = "Shell command `skm update --switch` runs to apply a new lock."; + }; + }; + + config = lib.mkIf cfg.enable { + home.packages = [ cfg.package ]; + + xdg.configFile."skill-manager/config.json".text = builtins.toJSON { + inherit (cfg) manifestDir switchCommand; + }; + + home.file = lib.listToAttrs ( + lib.concatMap ( + target: lib.mapAttrsToList (name: source: lib.nameValuePair "${target}/${name}" { inherit source; }) skills + ) cfg.targets + ); + }; +}