From d6821c6d7c9868b4770826e3fd8a717891af034e Mon Sep 17 00:00:00 2001 From: m3ta-chiron Date: Thu, 5 Nov 2026 08:48:52 +0100 Subject: [PATCH] feat(vendor): add rename command for deployed item names - Add `vendor rename [upstream-id=name ...] [--reset ids]` to change deployed names after `vendor add`, without moving the pinned rev or selection - Persist renames in the lockfile so they survive `vendor update` and `vendor select` - Rewrite SKILL.md frontmatter `name:` to the folder name so OpenCode loads renamed skills - Validate rename targets: single path segment, no leading dot, and OpenCode skill naming rules for skills - Re-run collision checks before writing; failed renames leave lockfile and external area untouched - Add unit tests for frontmatter rewrite and name validation, plus e2e rename coverage - Document renames in README; sync beads issue export --- .beads/.auto-import-issues.jsonl | 1 + .beads/issues.jsonl | 1 + README.md | 26 +++++ internal/cli/vendor.go | 35 ++++++ internal/e2e/rename_test.go | 89 +++++++++++++++ internal/vendor/add.go | 3 + internal/vendor/collide.go | 6 +- internal/vendor/rename.go | 180 ++++++++++++++++++++++++++++++ internal/vendor/skillname.go | 91 +++++++++++++++ internal/vendor/skillname_test.go | 39 +++++++ internal/vendor/update.go | 3 + 11 files changed, 472 insertions(+), 2 deletions(-) create mode 100644 .beads/.auto-import-issues.jsonl create mode 100644 internal/e2e/rename_test.go create mode 100644 internal/vendor/rename.go create mode 100644 internal/vendor/skillname.go create mode 100644 internal/vendor/skillname_test.go diff --git a/.beads/.auto-import-issues.jsonl b/.beads/.auto-import-issues.jsonl new file mode 100644 index 0000000..7261e4d --- /dev/null +++ b/.beads/.auto-import-issues.jsonl @@ -0,0 +1 @@ +{"size":51360,"mtime_ns":1793863936779644645} \ No newline at end of file diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 3f44884..33935fa 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -1,3 +1,4 @@ +{"_type":"issue","id":"agent-lib-u5t","title":"vendor rename: Vendor-Skills nachträglich umbenennen","description":"Kuratoren sollen vendored Items nachträglich (nicht nur bei vendor add) benutzerfreundlich umbenennen können. Neuer Befehl vendor rename \u003csource\u003e up=new / --reset; umbenannte Skills bekommen den name: im SKILL.md-Frontmatter angepasst (OpenCode verlangt name == Ordnername).","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"m3ta-chiron@agentmail.to","created_at":"2026-11-05T07:43:31Z","created_by":"m3ta-chiron","updated_at":"2026-11-05T07:45:14Z","started_at":"2026-11-05T07:43:50Z","closed_at":"2026-11-05T07:45:14Z","close_reason":"vendor rename implemented with SKILL.md name rewrite, tests + README","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"agent-lib-4wx.11","title":"Deliver end-to-end documentation and release gate","description":"Finish the MVP by documenting the full workflow and proving it through an offline end-to-end acceptance path. The slice should provide README content, quickstart, CLI reference, Home Manager examples, security/trust notes, troubleshooting, and a release gate that demonstrates init, Source add, inspect, snippet, Home Manager eval/render, target Manifests, and a green offline check.","acceptance_criteria":"- Documentation covers installation, quickstart, CLI reference, Home Manager configuration, Lockfile behavior, discovery conventions, security/trust model, troubleshooting, MVP scope, and non-goals\n- An offline end-to-end fixture workflow demonstrates initialization, Source discovery, selection, Pi and Opencode Rendered output, target Manifests, and no unmanaged overwrites\n- nix flake check is green without external network access and verifies the MVP acceptance criteria","notes":"E2E fixture check green. All steps verified: init creates lockfile, discover finds all items, lockfile has rev/narHash/HM-compatible schema, inspect/snippet/validate commands work, managed-file protection present. nix flake check passes.","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:50:02Z","created_by":"m3tam3re","updated_at":"2026-05-28T08:13:15Z","started_at":"2026-05-28T07:46:50Z","closed_at":"2026-05-28T08:13:15Z","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:50:01Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.1","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.10","type":"blocks","created_at":"2026-05-27T19:50:03Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.2","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.3","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.4","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.5","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.6","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.7","type":"blocks","created_at":"2026-05-27T19:50:02Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.8","type":"blocks","created_at":"2026-05-27T19:50:03Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.11","depends_on_id":"agent-lib-4wx.9","type":"blocks","created_at":"2026-05-27T19:50:03Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":10,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"agent-lib-4wx.10","title":"Complete CLI operational workflows and snippets","description":"Complete the day-to-day CLI workflow around existing Sources, Profiles, and Targets. The slice should make update/review/switch workflows practical with added/removed Item reports, offline and fetch validation modes, minimal and full Nix snippets, JSON output, non-interactive defaults, and an optional interactive entry point without automatic Nix edits.","acceptance_criteria":"- source update and source update --all report added and removed Items without changing Home Manager selection\n- validate runs offline by default, validate --fetch performs explicit reachability checks, and list/inspect/validate support stable JSON output\n- snippet emits both minimal Profile include snippets and full example configuration, while the CLI remains non-interactive by default and never edits Nix files","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:49:57Z","created_by":"m3tam3re","updated_at":"2026-05-28T07:46:28Z","started_at":"2026-05-28T07:39:36Z","closed_at":"2026-05-28T07:46:28Z","close_reason":"Closed","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:49:56Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx.3","type":"blocks","created_at":"2026-05-27T19:49:57Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx.5","type":"blocks","created_at":"2026-05-27T19:49:57Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx.7","type":"blocks","created_at":"2026-05-27T19:49:57Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.10","depends_on_id":"agent-lib-4wx.8","type":"blocks","created_at":"2026-05-27T19:49:57Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":4,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"agent-lib-4wx.9","title":"Apply item-specific patches and deployment safety controls","description":"Add safety and customization controls around selected Items, including item-specific patches, target-specific overrides, targetName collision handling, editable-copy escape hatch, license propagation, and configurable incompatibility policy. The slice should prove that patches affect only copied Artifacts and never mutate original source content.","acceptance_criteria":"- Item-specific patches apply only to copied Artifacts, while original Canonical source content remains immutable and auditable\n- targetName overrides, target-specific enable/disable overrides, collision detection, and onIncompatible policies are enforced for both Pi and Opencode\n- License files, provenance headers for rendered Markdown, preserved file permissions, and editable-copy deployment mode are covered by tests","status":"closed","priority":2,"issue_type":"feature","assignee":"m3ta-chiron","owner":"p@m3ta.dev","created_at":"2026-05-27T17:49:51Z","created_by":"m3tam3re","updated_at":"2026-05-28T07:39:25Z","started_at":"2026-05-28T07:25:13Z","closed_at":"2026-05-28T07:39:25Z","close_reason":"Closed","labels":["ready-for-agent"],"dependencies":[{"issue_id":"agent-lib-4wx.9","depends_on_id":"agent-lib-4wx","type":"parent-child","created_at":"2026-05-27T19:49:51Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.9","depends_on_id":"agent-lib-4wx.7","type":"blocks","created_at":"2026-05-27T19:49:52Z","created_by":"m3tam3re","metadata":"{}"},{"issue_id":"agent-lib-4wx.9","depends_on_id":"agent-lib-4wx.8","type":"blocks","created_at":"2026-05-27T19:49:52Z","created_by":"m3tam3re","metadata":"{}"}],"dependency_count":2,"dependent_count":1,"comment_count":0} diff --git a/README.md b/README.md index 675e729..c55328c 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,32 @@ agent-lib vendor add superpowers "$URL" --rename review=superpowers-review The on-disk folder always carries exactly the deployed name. Renaming onto another collision is an error. +### Friendlier names for your users + +Renames are not only for collisions — use them to give vendored items names +your colleagues recognize. `vendor rename` changes them at any time, without +moving the pinned revision or the selection: + +```sh +agent-lib vendor rename superpowers brainstorming=ideen-sammeln tdd=test-first +agent-lib vendor rename superpowers --reset tdd # back to the upstream id +agent-lib vendor rename superpowers # list current renames +``` + +- The rename map lives in the lockfile and survives `vendor update` and + `vendor select`. +- A renamed skill gets the `name:` in its `SKILL.md` frontmatter rewritten to + the new folder name (OpenCode requires both to match and shows that name). + Commands and agents are renamed via their file name only. +- Skill names must be 1–64 lowercase letters, digits and single hyphens + (`code-review`, not `Code Review`). No name of any type may contain path + separators or start with a dot. +- Renaming an id that is not selected yet is allowed; it applies once the + item is added via `vendor select --add`. +- On the next `agent-lib sync`, clients receive the item under the new name; + the old name is removed from their machine like any upstream deletion + (locally modified copies stay, as usual). + ### The maintenance loop ```sh diff --git a/internal/cli/vendor.go b/internal/cli/vendor.go index e60e55b..f7ff950 100644 --- a/internal/cli/vendor.go +++ b/internal/cli/vendor.go @@ -16,6 +16,7 @@ func newVendorCmd() *cobra.Command { } cmd.AddCommand(newVendorAddCmd()) cmd.AddCommand(newVendorSelectCmd()) + cmd.AddCommand(newVendorRenameCmd()) cmd.AddCommand(newVendorListCmd()) cmd.AddCommand(newVendorInspectCmd()) cmd.AddCommand(newVendorUpdateCmd()) @@ -70,6 +71,40 @@ func newVendorAddCmd() *cobra.Command { return cmd } +func newVendorRenameCmd() *cobra.Command { + var reset []string + cmd := &cobra.Command{ + Use: "rename [upstream-id=deployed-name ...]", + Short: "Give vendored items user-friendly deployed names", + Long: "Sets or resets deployed-name overrides for a vendored source after\n" + + "vendor add. The rename map is pinned in the lockfile and survives\n" + + "vendor update and vendor select. Renamed skills get their SKILL.md\n" + + "frontmatter name rewritten to the new folder name, so OpenCode lists\n" + + "them under the new name. Skill names must be lowercase letters, digits\n" + + "and single hyphens (e.g. code-review). The pinned revision and the\n" + + "selection never change; collisions re-run before anything is written.\n" + + "Without arguments the current renames are listed.\n\n" + + "Examples:\n" + + " agent-lib vendor rename superpowers brainstorming=ideen-sammeln\n" + + " agent-lib vendor rename superpowers --reset brainstorming\n" + + " agent-lib vendor rename superpowers", + Args: cobra.MinimumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + set, err := vendor.ParseRenames(args[1:]) + if err != nil { + return err + } + opts := vendor.RenameOptions{Set: set, Reset: splitList(reset)} + if err := vendor.Rename(".", args[0], opts, cmd.OutOrStdout()); err != nil { + return fmt.Errorf("vendor rename: %w", err) + } + return nil + }, + } + cmd.Flags().StringSliceVar(&reset, "reset", nil, "comma-separated upstream ids whose rename is dropped (deploy under the upstream id again)") + return cmd +} + func splitList(in []string) []string { var out []string for _, s := range in { diff --git a/internal/e2e/rename_test.go b/internal/e2e/rename_test.go new file mode 100644 index 0000000..17f1c61 --- /dev/null +++ b/internal/e2e/rename_test.go @@ -0,0 +1,89 @@ +package e2e + +import ( + "os" + "path/filepath" + "testing" +) + +func TestVendorRenameAfterAdd(t *testing.T) { + h := newHarness(t) + standardFixture(h, t) + h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir) + + out := h.mustRun(t, "vendor", "rename", "superpowers", "good-skill=gute-skill", "review=pruefen") + for _, want := range []string{"good-skill → gute-skill", "review → pruefen"} { + if !contains(out, want) { + t.Errorf("report must contain %q:\n%s", want, out) + } + } + + skill := readFile(t, filepath.Join(h.workDir, "external/superpowers/skills/gute-skill/SKILL.md")) + if !contains(skill, "name: gute-skill\n") || !contains(skill, "description: works") { + t.Errorf("renamed skill must carry the new frontmatter name and keep the rest:\n%s", skill) + } + if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/skills/gute-skill/helper.py")); err != nil { + t.Error("skill artifacts must move with the rename") + } + if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/skills/good-skill")); err == nil { + t.Error("old skill folder must be gone") + } + if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/commands/pruefen.md")); err != nil { + t.Error("renamed command must exist under the new name") + } + lock := readLock(t, h.workDir) + if got := lock.Sources["superpowers"].Renames["good-skill"]; got != "gute-skill" { + t.Errorf("lockfile rename = %q", got) + } + h.mustRun(t, "validate") + + // Listing. + if out := h.mustRun(t, "vendor", "rename", "superpowers"); !contains(out, "good-skill → gute-skill") { + t.Errorf("listing must show renames:\n%s", out) + } + + // Survives update with new upstream content. + h.write(t, "skills/good-skill/SKILL.md", "---\nname: Good Skill\ndescription: v2\n---\n# Good v2\n") + h.commitUpstream(t, "v2") + h.mustRun(t, "vendor", "update", "superpowers") + skill = readFile(t, filepath.Join(h.workDir, "external/superpowers/skills/gute-skill/SKILL.md")) + if !contains(skill, "name: gute-skill\n") || !contains(skill, "description: v2") { + t.Errorf("update must keep the rename and frontmatter rewrite:\n%s", skill) + } + + // Reset. + h.mustRun(t, "vendor", "rename", "superpowers", "--reset", "good-skill") + if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/skills/good-skill/SKILL.md")); err != nil { + t.Error("reset must restore the upstream folder name") + } + if got := readLock(t, h.workDir).Sources["superpowers"].Renames["good-skill"]; got != "" { + t.Errorf("reset must drop the rename, got %q", got) + } + h.mustRun(t, "validate") +} + +func TestVendorRenameRejectsBadInput(t *testing.T) { + h := newHarness(t) + ownSkillFixture(h, t) // own skills/good-skill + standardFixture(h, t) + h.mustRun(t, "vendor", "add", "superpowers", h.upstreamDir, "--rename", "good-skill=sp-good") + before := readFile(t, filepath.Join(h.workDir, "agent-lib.lock.json")) + + for _, args := range [][]string{ + {"broken-skill=good-skill"}, // collides with own skill + {"good-skill=Gute Skill"}, // invalid skill name + {"does-not-exist=whatever"}, // unknown upstream id + {"--reset", "broken-skill"}, // nothing to reset + } { + out, err := h.run(t, append([]string{"vendor", "rename", "superpowers"}, args...)...) + if err == nil { + t.Errorf("rename %v must fail:\n%s", args, out) + } + } + if after := readFile(t, filepath.Join(h.workDir, "agent-lib.lock.json")); after != before { + t.Error("failed renames must not touch the lockfile") + } + if _, err := os.Stat(filepath.Join(h.workDir, "external/superpowers/skills/sp-good")); err != nil { + t.Error("failed renames must not touch the external area") + } +} diff --git a/internal/vendor/add.go b/internal/vendor/add.go index 68cbb85..8d9be11 100644 --- a/internal/vendor/add.go +++ b/internal/vendor/add.go @@ -310,6 +310,9 @@ func materialize(workDir, name string, tree discovery.Tree, selected []discovery case lockfile.TypeSkill: dst = filepath.Join(base, dep) err = deploy.Dir(tree, it.RelPath, dst) + if err == nil && dep != it.UpstreamID { + err = rewriteSkillName(dst, dep) + } default: dst = filepath.Join(base, dep+filepath.Ext(it.RelPath)) err = deploy.File(tree, it.RelPath, dst) diff --git a/internal/vendor/collide.go b/internal/vendor/collide.go index e7d12d9..aead13b 100644 --- a/internal/vendor/collide.go +++ b/internal/vendor/collide.go @@ -103,8 +103,10 @@ func checkCollisions(workDir string, lf *lockfile.Lockfile, source string, selec seen := map[string]string{} for _, it := range selected { deployed := deployedName(it.UpstreamID, renames) - if deployed == "" { - return fmt.Errorf("source %q: rename of %q maps to an empty name", source, it.UpstreamID) + if deployed != it.UpstreamID { + if err := validateRenameTarget(it.Type, it.UpstreamID, deployed); err != nil { + return fmt.Errorf("source %q: %w", source, err) + } } if prev, dup := seen[deployed]; dup { return &CollisionError{ diff --git a/internal/vendor/rename.go b/internal/vendor/rename.go new file mode 100644 index 0000000..a0c4bdd --- /dev/null +++ b/internal/vendor/rename.go @@ -0,0 +1,180 @@ +package vendor + +import ( + "fmt" + "io" + "os" + "path/filepath" + "sort" + + "github.com/m3tam3re/agent-lib/internal/discovery" + "github.com/m3tam3re/agent-lib/internal/gitsource" + "github.com/m3tam3re/agent-lib/internal/lockfile" +) + +// RenameOptions parameterize vendor rename. +type RenameOptions struct { + // Set maps upstream ids to new deployed names. Mapping an id onto itself + // is the same as resetting it. + Set map[string]string + // Reset drops existing renames so the items deploy under their upstream id. + Reset []string +} + +// Rename changes the deployed names of a vendored source's items after the +// fact — without advancing the pinned revision or touching the selection. +// Ids are validated against the pinned upstream, collisions re-run, and the +// external area is rewritten atomically. With no options it only lists the +// current renames. +func Rename(workDir, name string, opts RenameOptions, stdout io.Writer) error { + lockPath := filepath.Join(workDir, lockfile.FileName) + lf, err := lockfile.Load(lockPath) + if err != nil { + return err + } + src, ok := lf.Sources[name] + if !ok { + return fmt.Errorf("source %q is not in the lockfile", name) + } + + if len(opts.Set) == 0 && len(opts.Reset) == 0 { + printRenames(stdout, name, src.Renames) + return nil + } + + newRenames := map[string]string{} + for k, v := range src.Renames { + newRenames[k] = v + } + for _, id := range opts.Reset { + if _, ok := newRenames[id]; !ok { + return fmt.Errorf("source %q: --reset %q has no rename to reset", name, id) + } + delete(newRenames, id) + } + for up, dep := range opts.Set { + if up == dep { + delete(newRenames, up) + continue + } + newRenames[up] = dep + } + + repo, err := gitsource.Clone(src.URL, src.Ref) + if err != nil { + return err + } + pinned, err := repo.Pin(src.Rev) + if err != nil { + return fmt.Errorf("%w — run vendor update to re-pin", err) + } + tree, err := pinned.Tree() + if err != nil { + return err + } + items, err := discovery.Scan(tree, discovery.FromLockfileDiscovery(derefDiscovery(src))) + if err != nil { + return err + } + + ids := append(sortedKeys(boolSet(keysOf(opts.Set))), opts.Reset...) + if err := checkIDEntries(items, ids, name, "rename"); err != nil { + return err + } + types := map[string]string{} + for _, it := range items { + if !it.Skipped { + types[it.UpstreamID] = it.Type + } + } + for up, dep := range opts.Set { + if up == dep { + continue + } + if err := validateRenameTarget(types[up], up, dep); err != nil { + return fmt.Errorf("source %q: %w", name, err) + } + } + + selected := applySelection(items, src.Selection) + if err := checkCollisions(workDir, lf, name, selected, newRenames); err != nil { + return err + } + + cleanupStaleStaging(workDir) + staging := filepath.Join(workDir, externalDir, ".staging-"+name) + if err := os.RemoveAll(staging); err != nil { + return err + } + if err := materializeTree(tree, selected, newRenames, staging); err != nil { + os.RemoveAll(staging) + return err + } + oldDir := filepath.Join(workDir, externalDir, name) + if err := os.RemoveAll(oldDir); err != nil { + return fmt.Errorf("replacing %s: %w", oldDir, err) + } + if err := os.Rename(staging, oldDir); err != nil { + return fmt.Errorf("swapping in new external area: %w", err) + } + + oldRenames := src.Renames + if len(newRenames) == 0 { + newRenames = nil + } + src.Renames = newRenames + src.Inventory = inventoryOf(selected) + src.Warnings = dedupe(warningsOf(items)) + if err := lf.Save(lockPath); err != nil { + return err + } + + inSelection := idSet(selected) + fmt.Fprintf(stdout, "source %s: renames updated at pinned rev %s\n", name, short(src.Rev)) + for _, id := range ids { + before := deployedName(id, oldRenames) + after := deployedName(id, newRenames) + note := "" + if !inSelection[types[id]][id] { + note = " (not selected — applies once added)" + } + if before == after { + fmt.Fprintf(stdout, " %s %s: unchanged (%s)%s\n", types[id], id, after, note) + continue + } + fmt.Fprintf(stdout, " %s %s: %s → %s%s\n", types[id], id, before, after, note) + } + return nil +} + +func printRenames(w io.Writer, name string, renames map[string]string) { + if len(renames) == 0 { + fmt.Fprintf(w, "source %s: no renames\n", name) + return + } + fmt.Fprintf(w, "source %s renames (upstream → deployed):\n", name) + ups := make([]string, 0, len(renames)) + for up := range renames { + ups = append(ups, up) + } + sort.Strings(ups) + for _, up := range ups { + fmt.Fprintf(w, " %s → %s\n", up, renames[up]) + } +} + +func keysOf(m map[string]string) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + return out +} + +func boolSet(ids []string) map[string]bool { + out := map[string]bool{} + for _, id := range ids { + out[id] = true + } + return out +} diff --git a/internal/vendor/skillname.go b/internal/vendor/skillname.go new file mode 100644 index 0000000..fc9076a --- /dev/null +++ b/internal/vendor/skillname.go @@ -0,0 +1,91 @@ +package vendor + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + + "github.com/m3tam3re/agent-lib/internal/lockfile" +) + +// skillNameRe is the OpenCode / Agent Skills naming rule: lowercase +// alphanumerics with single hyphen separators. OpenCode additionally requires +// the SKILL.md frontmatter name to equal the folder name. +var skillNameRe = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`) + +const maxSkillNameLen = 64 + +// validateRenameTarget checks a deployed-name override before it becomes a +// path segment. Every type rejects path separators and dot-names; skills must +// additionally follow the OpenCode skill naming rule so the renamed skill +// still loads. +func validateRenameTarget(typ, upstreamID, deployed string) error { + if deployed == "" { + return fmt.Errorf("rename of %q maps to an empty name", upstreamID) + } + if strings.ContainsAny(deployed, `/\`) || strings.HasPrefix(deployed, ".") || strings.TrimSpace(deployed) != deployed { + return fmt.Errorf("rename of %q to %q: name must be a single path segment without leading dot or surrounding whitespace", upstreamID, deployed) + } + if typ == lockfile.TypeSkill { + if len(deployed) > maxSkillNameLen || !skillNameRe.MatchString(deployed) { + return fmt.Errorf("rename of skill %q to %q: skill names must be 1-%d lowercase letters, digits and single hyphens (e.g. \"code-review\")", upstreamID, deployed, maxSkillNameLen) + } + } + return nil +} + +// rewriteSkillName sets the frontmatter `name:` of dir/SKILL.md to name so a +// renamed skill matches its folder (OpenCode loads skills by that pairing and +// shows the frontmatter name to the user). A missing name key is inserted, a +// missing frontmatter block is created. Everything else stays byte-identical. +func rewriteSkillName(dir, name string) error { + path := filepath.Join(dir, "SKILL.md") + info, err := os.Stat(path) + if err != nil { + return err + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + out := setFrontmatterName(string(data), name) + if out == string(data) { + return nil + } + tmp := path + ".agent-lib-tmp" + if err := os.WriteFile(tmp, []byte(out), info.Mode().Perm()); err != nil { + return err + } + return os.Rename(tmp, path) +} + +func setFrontmatterName(content, name string) string { + lines := strings.SplitAfter(content, "\n") + if len(lines) == 0 || strings.TrimRight(lines[0], "\r\n") != "---" { + return "---\nname: " + name + "\n---\n" + content + } + eol := "\n" + if strings.HasSuffix(lines[0], "\r\n") { + eol = "\r\n" + } + for i := 1; i < len(lines); i++ { + bare := strings.TrimRight(lines[i], "\r\n") + if bare == "---" { + break + } + if bare == "" || bare[0] == ' ' || bare[0] == '\t' { + continue // nested/continuation lines never carry the top-level name + } + key, _, ok := strings.Cut(bare, ":") + if ok && strings.EqualFold(strings.TrimSpace(key), "name") { + lineEOL := lines[i][len(bare):] + lines[i] = "name: " + name + lineEOL + return strings.Join(lines, "") + } + } + // No name key: insert one right after the opening fence. + rest := strings.Join(lines[1:], "") + return lines[0] + "name: " + name + eol + rest +} diff --git a/internal/vendor/skillname_test.go b/internal/vendor/skillname_test.go new file mode 100644 index 0000000..7eae461 --- /dev/null +++ b/internal/vendor/skillname_test.go @@ -0,0 +1,39 @@ +package vendor + +import "testing" + +func TestSetFrontmatterName(t *testing.T) { + cases := []struct{ name, in, want string }{ + {"replace", "---\nname: Good Skill\ndescription: d\n---\nbody\n", "---\nname: ideen\ndescription: d\n---\nbody\n"}, + {"crlf", "---\r\nname: x\r\n---\r\nb", "---\r\nname: ideen\r\n---\r\nb"}, + {"insert", "---\ndescription: d\n---\n", "---\nname: ideen\ndescription: d\n---\n"}, + {"no frontmatter", "# Title\n", "---\nname: ideen\n---\n# Title\n"}, + {"nested name untouched", "---\nmeta:\n name: inner\n---\n", "---\nname: ideen\nmeta:\n name: inner\n---\n"}, + {"name in body untouched", "---\ndescription: d\n---\nname: body\n", "---\nname: ideen\ndescription: d\n---\nname: body\n"}, + } + for _, c := range cases { + if got := setFrontmatterName(c.in, "ideen"); got != c.want { + t.Errorf("%s:\n got %q\nwant %q", c.name, got, c.want) + } + } +} + +func TestValidateRenameTarget(t *testing.T) { + ok := []struct{ typ, dep string }{ + {"skills", "code-review"}, {"skills", "a1"}, {"commands", "Review_Things"}, + } + for _, c := range ok { + if err := validateRenameTarget(c.typ, "up", c.dep); err != nil { + t.Errorf("%s %q should be valid: %v", c.typ, c.dep, err) + } + } + bad := []struct{ typ, dep string }{ + {"skills", "Code Review"}, {"skills", "code--review"}, {"skills", "-x"}, {"skills", "Gross"}, + {"commands", "../x"}, {"agents", "a/b"}, {"commands", ".hidden"}, {"skills", ""}, + } + for _, c := range bad { + if err := validateRenameTarget(c.typ, "up", c.dep); err == nil { + t.Errorf("%s %q should be rejected", c.typ, c.dep) + } + } +} diff --git a/internal/vendor/update.go b/internal/vendor/update.go index dc3aafe..dfc8191 100644 --- a/internal/vendor/update.go +++ b/internal/vendor/update.go @@ -264,6 +264,9 @@ func materializeTree(tree discovery.Tree, selected []discovery.Item, renames map case lockfile.TypeSkill: target = filepath.Join(base, dep) err = deploy.Dir(tree, it.RelPath, target) + if err == nil && dep != it.UpstreamID { + err = rewriteSkillName(target, dep) + } default: target = filepath.Join(base, dep+filepath.Ext(it.RelPath)) err = deploy.File(tree, it.RelPath, target)