feat(vendor): add rename command for deployed item names

- Add `vendor rename <source> [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
This commit is contained in:
m3ta-chiron committed 2026-11-05 08:48:52 +01:00
1 parent f37c3dce5e
commit d6821c6d7c
11 files changed
+472 -2

No files matched your search

+35
View File
@@ -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 <name> [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 {
+89
View File
@@ -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")
}
}
+3
View File
@@ -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)
+4 -2
View File
@@ -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{
+180
View File
@@ -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
}
+91
View File
@@ -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
}
+39
View File
@@ -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)
}
}
}
+3
View File
@@ -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)