Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(skills): give every skill one name across brief, directory, and frontmatter (MUL-5529) (#6189)

Bohan Jiang519927878041
diff --git a/server/internal/daemon/execenv/context.go b/server/internal/daemon/execenv/context.go
index b012014d03..978d51099b 100644
--- a/server/internal/daemon/execenv/context.go
+++ b/server/internal/daemon/execenv/context.go
@@ -425,8 +425,8 @@ var nonAlphaNum = regexp.MustCompile(`[^a-z0-9]+`)
// - No frontmatter at all → synthesize one with `name: <slug>` (and the DB
// description when available).
// - Frontmatter present, has a non-empty `name`, AND parses as valid YAML →
-// leave it untouched. The upstream import may have shaped that block
-// deliberately to match a specific runtime, and we don't want to clobber it.
+// rewrite `name` to the slug and keep every other key verbatim. See below
+// for why `name` specifically is not left alone.
// - Frontmatter present and has a non-empty `name` but YAML is invalid (e.g.
// unquoted colon in description) → strip and re-synthesize so runtimes like
// Codex don't discard the skill on parse errors.
@@ -434,33 +434,91 @@ var nonAlphaNum = regexp.MustCompile(`[^a-z0-9]+`)
// YAML only set `description`, with the directory slug filling in for
// `name` at import time) → prepend `name: <slug>` as the first key of
// the existing block so OpenCode can still route the skill.
+//
+// `name` is the one key Multica must own. Runtimes disagree on which field
+// identifies a skill — Claude routes on the directory name, OpenCode on the
+// frontmatter `name` — so letting the two diverge gives a single skill two
+// different invocable names depending on where it runs (MUL-5529). The slug is
+// authoritative because it is what lands on disk and the only value carrying a
+// uniqueness guarantee (allocateCollisionFreeSkillDir); a frontmatter `name` is
+// author-supplied and two imported skills may both claim the same one. Every
+// other key stays byte-identical, so deliberately shaped upstream frontmatter
+// still survives the round-trip.
func ensureSkillFrontmatter(content, slug, description string) string {
fmStart, ok := frontmatterBodyStart(content)
if !ok {
return synthesizeFrontmatter(content, slug, description)
}
- // Frontmatter exists and has a parseable name. If it's valid YAML, leave
- // it untouched so upstream-imported frontmatter survives round-trips.
- if hasFrontmatterName(content[fmStart:]) {
- if isFrontmatterValidYAML(content) {
- return content
+ if isFrontmatterValidYAML(content) {
+ // The parser, not the spelling, decides whether a name exists. A
+ // lexical scan only recognizes a bare `name:` with a value on the same
+ // line, so `"name": x` and a valueless `name:` read as nameless and
+ // earn an injected second `name` — a duplicate mapping key that strict
+ // loaders reject outright, leaving the skill unloadable rather than
+ // merely misnamed.
+ if frontmatterHasNameKey(content) {
+ if rewritten, verified := setFrontmatterName(content, fmStart, slug); verified {
+ return rewritten
+ }
+ // The surgical rewrite could not be proven correct — an anchor on
+ // the name value is one way that happens, since replacing the line
+ // removes the anchor and strands any alias pointing at it. The
+ // block itself is still valid YAML, so rebuild it from the parsed
+ // node instead of re-synthesizing: that keeps every other key,
+ // including policy fields like disable-model-invocation whose loss
+ // would re-expose a skill the author hid from model invocation.
+ if rebuilt, ok := renameFrontmatterNameViaNode(content, slug); ok {
+ return rebuilt
+ }
+ _, body, _ := frontmatterParts(content)
+ return synthesizeFrontmatter(body, slug, description)
}
- // Frontmatter has a name but the YAML is invalid (e.g. unquoted
- // colon in the description). Strip and re-synthesize so runtimes
- // like Codex don't hard-reject the whole skill at load time.
- // frontmatterParts returns the full content as the body when it
- // can't find a closing delimiter, so the malformed block is kept
- // rather than silently dropped.
+ // No name key at all, confirmed by the parser rather than inferred.
+ // Inject one as the first key and keep the rest verbatim (including
+ // `description`, body, and any runtime-specific keys the import path
+ // preserved).
+ return content[:fmStart] + "name: " + slug + "\n" + content[fmStart:]
+ }
+
+ // Invalid YAML: there is no parse to consult, so fall back to the lexical
+ // scan. A block with a name is stripped and re-synthesized so runtimes like
+ // Codex don't hard-reject the whole skill at load time; frontmatterParts
+ // returns the full content as the body when it can't find a closing
+ // delimiter, so the malformed block is kept rather than silently dropped.
+ if hasFrontmatterName(content[fmStart:]) {
_, body, _ := frontmatterParts(content)
return synthesizeFrontmatter(body, slug, description)
}
- // Frontmatter exists but lacks a parseable `name`. Inject one as the
- // first key of the existing block and keep the rest verbatim (including
- // `description`, body, and any runtime-specific keys the import path
- // preserved).
return content[:fmStart] + "name: " + slug + "\n" + content[fmStart:]
}
+// frontmatterHasNameKey reports whether content's frontmatter parses as a
+// mapping carrying a top-level `name` key, whatever its spelling or value.
+//
+// Quoting is syntax, not identity: `"name":` and `name:` are the same key, and
+// a key with an empty value is still the key. Only nesting makes a difference —
+// `metadata:\n name: x` has no top-level name, so one still has to be added.
+func frontmatterHasNameKey(content string) bool {
+ fmBody, _, ok := frontmatterParts(content)
+ if !ok {
+ return false
+ }
+ var doc yaml.Node
+ if err := yaml.Unmarshal([]byte(fmBody), &doc); err != nil {
+ return false
+ }
+ if len(doc.Content) == 0 || doc.Content[0].Kind != yaml.MappingNode {
+ return false
+ }
+ mapping := doc.Content[0]
+ for i := 0; i+1 < len(mapping.Content); i += 2 {
+ if mapping.Content[i].Value == "name" {
+ return true
+ }
+ }
+ return false
+}
+
// synthesizeFrontmatter produces a SKILL.md body with a YAML frontmatter block
// carrying at least `name` and (when non-empty) `description`. The description
// is always escaped as a double-quoted YAML string so values containing colons,
@@ -542,31 +600,276 @@ func frontmatterBodyStart(content string) (int, bool) {
}
// hasFrontmatterName reports whether the frontmatter body (the slice starting
-// just after the opening `---` line) contains a parseable, non-empty `name:`
-// scalar before the closing `---`.
+// just after the opening `---` line) contains a top-level `name` key before
+// the closing `---`, whatever its spelling or value.
+//
+// This is the malformed-block twin of frontmatterHasNameKey: it answers the
+// same question for blocks that do not parse, where the caller is choosing
+// between re-synthesizing (name present) and injecting a fresh `name` (name
+// absent). The invariant is key presence, not value presence — `"name":`,
+// `'name':`, and a valueless `name:` are all the key, and injecting a second
+// one above any of them yields a duplicate mapping key that strict loaders
+// reject, leaving the skill unloadable rather than healed (MUL-5529). Reading
+// a plain scalar like `name:value` as the key over-detects, and deliberately
+// so: the block is already unparseable, and re-synthesis is the route that
+// repairs it.
+//
+// Only unindented keys count. An indented `name:` belongs to a nested mapping
+// (`metadata:\n name: foo`), so the block still has no top-level name.
func hasFrontmatterName(fmBody string) bool {
closeIdx := strings.Index(fmBody, "\n---")
if closeIdx < 0 {
- // Missing close — scan everything we have and fall through. The
- // frontmatter is malformed and OpenCode will reject it anyway, but
- // detecting an existing name keeps us from layering a second one
- // on top.
+ // Missing close — scan everything we have. The frontmatter is
+ // malformed and strict runtimes reject it anyway, but detecting an
+ // existing name keeps us from layering a second one on top.
closeIdx = len(fmBody)
}
for _, line := range strings.Split(fmBody[:closeIdx], "\n") {
- line = strings.TrimSpace(line)
- if !strings.HasPrefix(line, "name:") {
- continue
- }
- v := strings.TrimSpace(strings.TrimPrefix(line, "name:"))
- v = strings.Trim(v, `"'`)
- if v != "" {
+ line = strings.TrimSuffix(line, "\r")
+ if strings.HasPrefix(line, "name:") ||
+ strings.HasPrefix(line, `"name":`) ||
+ strings.HasPrefix(line, `'name':`) {
return true
}
}
return false
}
+// frontmatterNameValueSpan returns the byte range of the whole top-level `name`
+// entry — key plus value, however many lines the value occupies — inside a
+// frontmatter body that is already known to be valid YAML.
+//
+// The extent comes from yaml.v3's own line numbers rather than from
+// indentation, because indentation does not bound a YAML value. A quoted scalar
+// may wrap onto a line at the *same* indentation as its key, and so may a flow
+// collection:
+//
+// name: "upstream
+// continued"
+// name: [a,
+// b]
+//
+// Both parse; an indentation rule stops at the key's line and leaves the
+// remainder stranded, turning a rewrite into invalid YAML. Asking the parser
+// where the next top-level key starts is the only reliable boundary.
+func frontmatterNameValueSpan(fmBody string) (start, end int, ok bool) {
+ closeIdx := strings.Index(fmBody, "\n---")
+ if closeIdx < 0 {
+ closeIdx = len(fmBody)
+ }
+ block := fmBody[:closeIdx]
+
+ var doc yaml.Node
+ if err := yaml.Unmarshal([]byte(block), &doc); err != nil {
+ return 0, 0, false
+ }
+ if len(doc.Content) == 0 || doc.Content[0].Kind != yaml.MappingNode {
+ return 0, 0, false
+ }
+ mapping := doc.Content[0]
+
+ // yaml.Node lines are 1-based.
+ nameLine, nextKeyLine := 0, 0
+ for i := 0; i+1 < len(mapping.Content); i += 2 {
+ key := mapping.Content[i]
+ if key.Value != "name" {
+ continue
+ }
+ nameLine = key.Line
+ if i+2 < len(mapping.Content) {
+ nextKeyLine = mapping.Content[i+2].Line
+ }
+ break
+ }
+ if nameLine == 0 {
+ return 0, 0, false
+ }
+
+ lines := strings.Split(block, "\n")
+ lastLine := len(lines)
+ if nextKeyLine > 0 {
+ lastLine = nextKeyLine - 1
+ }
+ if lastLine > len(lines) {
+ lastLine = len(lines)
+ }
+ // Blank lines and unindented comments sitting between this entry and the
+ // next key are not part of the value: block scalar content must be
+ // indented, so an unindented `#` can only be a comment. Leave them in
+ // place instead of swallowing them into the replacement.
+ for lastLine > nameLine {
+ line := strings.TrimSuffix(lines[lastLine-1], "\r")
+ if strings.TrimSpace(line) == "" || strings.HasPrefix(line, "#") {
+ lastLine--
+ continue
+ }
+ break
+ }
+ if lastLine < nameLine {
+ return 0, 0, false
+ }
+
+ offset := 0
+ for i, line := range lines {
+ if i == nameLine-1 {
+ start = offset
+ }
+ if i == lastLine-1 {
+ return start, offset + len(line), true
+ }
+ offset += len(line) + 1 // +1 for the newline Split consumed
+ }
+ return 0, 0, false
+}
+
+// setFrontmatterName replaces the top-level frontmatter `name` entry — key and
+// full value, however many lines it spans — with a single-line `name: <slug>`,
+// leaving every other byte of content untouched. fmStart is the offset where
+// the YAML body begins (see frontmatterBodyStart).
+//
+// verified reports that the result was re-parsed and its `name` really is slug.
+// Callers must treat false as "do not use this output": the directory ==
+// frontmatter-name invariant is the entire reason this function exists, so a
+// rewrite that cannot prove it is worse than no rewrite at all.
+func setFrontmatterName(content string, fmStart int, slug string) (result string, verified bool) {
+ fmBody := content[fmStart:]
+ start, end, ok := frontmatterNameValueSpan(fmBody)
+ if !ok {
+ return "", false
+ }
+ replacement := "name: " + slug
+ // strings.Split on "\n" leaves the "\r" of a CRLF ending inside the line;
+ // carry it over so the block doesn't end up with mixed terminators.
+ if strings.HasSuffix(fmBody[start:end], "\r") {
+ replacement += "\r"
+ }
+ rewritten := content[:fmStart+start] + replacement + content[fmStart+end:]
+ if !frontmatterNameIs(rewritten, slug) {
+ return "", false
+ }
+ return rewritten, true
+}
+
+// renameFrontmatterNameViaNode rebuilds the frontmatter block from its parsed
+// YAML node with `name` set to slug, and returns the reassembled document.
+//
+// This is the middle ground between the surgical byte rewrite and full
+// re-synthesis. It gives up the original block's exact formatting — the
+// re-marshal normalizes quoting and indentation — but keeps every key and its
+// value, which re-synthesis does not. That difference matters beyond tidiness:
+// synthesizeFrontmatter emits only name and description, so a block carrying
+// `disable-model-invocation: true` would come back out without it and the
+// skill, once on disk, would be advertised by the runtime's native discovery
+// despite the author having hidden it.
+//
+// An anchor on the name value needs care in both directions. Simply dropping it
+// strands any `*alias` that referenced it and invalidates the document. Simply
+// keeping it is worse: every alias then resolves to the slug, so a document
+// that expressed a setting by reusing the name's value silently acquires a
+// different setting. `disable-model-invocation: *shared` against
+// `name: &shared "true"` flips from true to false — the same skill-exposing
+// regression as dropping the key outright, just by another route.
+//
+// So aliases are materialized to the value they resolved to *before* the
+// rename, and the anchor is then removed as unreferenced. Every field keeps the
+// value it had; only `name` changes.
+func renameFrontmatterNameViaNode(content, slug string) (string, bool) {
+ fmBody, body, ok := frontmatterParts(content)
+ if !ok {
+ return "", false
+ }
+ var doc yaml.Node
+ if err := yaml.Unmarshal([]byte(fmBody), &doc); err != nil {
+ return "", false
+ }
+ if len(doc.Content) == 0 || doc.Content[0].Kind != yaml.MappingNode {
+ return "", false
+ }
+
+ mapping := doc.Content[0]
+ var value *yaml.Node
+ for i := 0; i+1 < len(mapping.Content); i += 2 {
+ if mapping.Content[i].Value == "name" {
+ value = mapping.Content[i+1]
+ break
+ }
+ }
+ if value == nil {
+ return "", false
+ }
+
+ // Pin every alias to what it resolves to now, before the rename can change
+ // it out from under them. Done first so the clones capture the original
+ // value rather than the slug.
+ if value.Anchor != "" {
+ materializeAliasesOf(&doc, value)
+ }
+
+ // Collapse whatever the value was (scalar, flow sequence, …) to a plain
+ // string. The anchor goes with it: nothing references it any more.
+ value.Kind = yaml.ScalarNode
+ value.Tag = "!!str"
+ value.Style = 0
+ value.Value = slug
+ value.Content = nil
+ value.Anchor = ""
+
+ marshaled, err := yaml.Marshal(&doc)
+ if err != nil {
+ return "", false
+ }
+ rebuilt := "---\n" + string(marshaled) + "---\n" + body
+ if !frontmatterNameIs(rebuilt, slug) {
+ return "", false
+ }
+ return rebuilt, true
+}
+
+// materializeAliasesOf replaces every alias node under root that points at
+// target with an inline copy of target's current value, so those fields keep
+// that value even after target is rewritten.
+func materializeAliasesOf(root, target *yaml.Node) {
+ for _, child := range root.Content {
+ if child.Kind == yaml.AliasNode && child.Alias == target {
+ // Each alias gets its own copy; sharing one node would make the
+ // encoder re-introduce an anchor and alias pair.
+ *child = *cloneYAMLNode(target)
+ continue
+ }
+ materializeAliasesOf(child, target)
+ }
+}
+
+// cloneYAMLNode deep-copies a node, stripping anchor/alias identity so the copy
+// is emitted inline rather than as a reference.
+func cloneYAMLNode(n *yaml.Node) *yaml.Node {
+ clone := *n
+ clone.Anchor = ""
+ clone.Alias = nil
+ if len(n.Content) > 0 {
+ clone.Content = make([]*yaml.Node, len(n.Content))
+ for i, child := range n.Content {
+ clone.Content[i] = cloneYAMLNode(child)
+ }
+ }
+ return &clone
+}
+
+// frontmatterNameIs reports whether content's frontmatter parses and its
+// top-level `name` is exactly want.
+func frontmatterNameIs(content, want string) bool {
+ fmBody, _, ok := frontmatterParts(content)
+ if !ok {
+ return false
+ }
+ var m map[string]any
+ if err := yaml.Unmarshal([]byte(fmBody), &m); err != nil {
+ return false
+ }
+ name, _ := m["name"].(string)
+ return name == want
+}
+
// yamlEscapeInline returns a double-quoted YAML scalar that always parses as
// a string. Plain scalars are deliberately avoided: values like `[foo]`,
// `{x: y}`, `false`, `null`, or `2024-01-01` would parse as flow sequences,
@@ -615,9 +918,16 @@ func writeSkillFiles(skillsDir string, skills []SkillContextForEnv, manifest *si
return fmt.Errorf("create skills dir: %w", err)
}
- for _, skill := range skills {
- baseSlug := sanitizeSkillName(skill.Name)
- slug, dir, err := allocateCollisionFreeSkillDir(skillsDir, baseSlug)
+ // resolveSkillSlugs deduplicates within the batch first, so two skills whose
+ // names sanitize alike ("A B" / "A-B") get distinct bases here instead of
+ // racing for the same directory. The listings derive from the same function,
+ // which is what keeps them naming the directories this loop creates.
+ // allocateCollisionFreeSkillDir still runs on top, for collisions against
+ // directories we did not write (user-installed skills).
+ batchSlugs := resolveSkillSlugs(skills)
+
+ for i, skill := range skills {
+ slug, dir, err := allocateCollisionFreeSkillDir(skillsDir, batchSlugs[i])
if err != nil {
return fmt.Errorf("allocate skill dir for %q: %w", skill.Name, err)
}
diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.go
index 095022cfb2..b49d68014f 100644
--- a/server/internal/daemon/execenv/execenv_test.go
+++ b/server/internal/daemon/execenv/execenv_test.go
@@ -129,7 +129,8 @@ func TestPrepareDirectoryMode(t *testing.T) {
if err != nil {
t.Fatalf("failed to read issue_context.md: %v", err)
}
- for _, want := range []string{"a1b2c3d4-e5f6-7890-abcd-ef1234567890", "Code Review"} {
+ // "Code Review" is listed by its on-disk slug (MUL-5529).
+ for _, want := range []string{"a1b2c3d4-e5f6-7890-abcd-ef1234567890", "code-review"} {
if !strings.Contains(string(content), want) {
t.Fatalf("issue_context.md missing %q", want)
}
@@ -451,7 +452,9 @@ func TestWriteContextFiles(t *testing.T) {
for _, want := range []string{
"test-issue-id-1234",
"## Agent Skills",
- "Go Conventions",
+ // Listed by on-disk slug, not the "Go Conventions" display name —
+ // the slug is the only name the model can invoke (MUL-5529).
+ "go-conventions",
} {
if !strings.Contains(s, want) {
t.Errorf("content missing %q", want)
@@ -941,14 +944,24 @@ func TestInjectRuntimeConfigClaude(t *testing.T) {
"Multica Agent Runtime",
"multica issue get",
"multica issue comment list",
- "Go Conventions",
- "PR Review",
+ // Skills are listed by on-disk slug: that is the directory
+ // writeSkillFiles creates and the only identifier the model can
+ // actually invoke (MUL-5529).
+ "go-conventions",
+ "pr-review",
"discovered automatically",
} {
if !strings.Contains(s, want) {
t.Errorf("CLAUDE.md missing %q", want)
}
}
+ // The display names must not leak into the listing — a model that reads
+ // "PR Review" and invokes it by that name gets nothing.
+ for _, absent := range []string{"Go Conventions", "PR Review"} {
+ if strings.Contains(s, absent) {
+ t.Errorf("CLAUDE.md lists display name %q instead of its slug", absent)
+ }
+ }
}
func TestInjectRuntimeConfigBackgroundTaskSafetyProviderAgnostic(t *testing.T) {
@@ -1129,7 +1142,8 @@ func TestInjectRuntimeConfigCodex(t *testing.T) {
if !strings.Contains(s, "Multica Agent Runtime") {
t.Error("AGENTS.md missing meta skill header")
}
- if !strings.Contains(s, "Coding") {
+ // Listed by on-disk slug rather than the display name (MUL-5529).
+ if !strings.Contains(s, "coding") {
t.Error("AGENTS.md missing skill name")
}
}
@@ -1278,22 +1292,26 @@ func TestWriteContextFilesOpencodeNativeSkills(t *testing.T) {
}
// Skill content imported from upstream sources (GitHub, ClawHub, Skills.sh)
-// often already carries its own YAML frontmatter — possibly with a `name`
-// that differs from the DB row's display name to match a specific runtime's
-// expectations. The writer must not clobber that block; it should only
-// synthesize when frontmatter is absent.
-func TestWriteContextFilesPreservesExistingSkillFrontmatter(t *testing.T) {
+// often already carries its own YAML frontmatter. The writer keeps that block
+// verbatim with exactly one exception: `name` is forced to the directory slug.
+//
+// The exception exists because runtimes disagree on which field identifies a
+// skill — OpenCode routes on the frontmatter `name`, Claude on the directory
+// name. Leaving an upstream `name` in place therefore gives one skill two
+// different invocable names depending on where it runs (MUL-5529). This test
+// uses opencode precisely because it is the side that would route on the
+// upstream value.
+func TestWriteContextFilesForcesSkillFrontmatterNameToSlug(t *testing.T) {
t.Parallel()
dir := t.TempDir()
- preExisting := "---\nname: upstream-name\ndescription: imported as-is\n---\n\nbody"
ctx := TaskContextForEnv{
- IssueID: "preserve-frontmatter-test",
+ IssueID: "frontmatter-name-test",
AgentSkills: []SkillContextForEnv{
{
Name: "Display Name",
Description: "overridden by upstream frontmatter",
- Content: preExisting,
+ Content: "---\nname: upstream-name\ndescription: imported as-is\ncustom-key: keep me\n---\n\nbody",
},
},
}
@@ -1306,8 +1324,98 @@ func TestWriteContextFilesPreservesExistingSkillFrontmatter(t *testing.T) {
if err != nil {
t.Fatalf("failed to read SKILL.md: %v", err)
}
- if string(skillMd) != preExisting {
- t.Errorf("SKILL.md was rewritten; got:\n%s\nwant:\n%s", skillMd, preExisting)
+
+ // name matches the directory it was written into, so both routing
+ // conventions resolve to the same skill.
+ want := "---\nname: display-name\ndescription: imported as-is\ncustom-key: keep me\n---\n\nbody"
+ if string(skillMd) != want {
+ t.Errorf("frontmatter name was not normalized to the slug; got:\n%s\nwant:\n%s", skillMd, want)
+ }
+}
+
+// The directory-name == frontmatter-name invariant must survive collision
+// fallback, where the allocated slug is NOT sanitizeSkillName(Name). A
+// user-installed skill already sitting at the natural slug pushes Multica's
+// copy to `<slug>-multica`; the frontmatter has to follow it there, or the
+// skill answers to the user's slug on Claude and to its own stale name on
+// OpenCode.
+func TestWriteContextFilesFrontmatterNameFollowsCollisionSlug(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+
+ // Pre-create a user-owned skill at the natural slug.
+ userSkill := filepath.Join(dir, ".opencode", "skills", "review")
+ if err := os.MkdirAll(userSkill, 0o755); err != nil {
+ t.Fatalf("seed user skill: %v", err)
+ }
+ userContent := "---\nname: review\n---\n\nuser's own skill"
+ if err := os.WriteFile(filepath.Join(userSkill, "SKILL.md"), []byte(userContent), 0o644); err != nil {
+ t.Fatalf("seed user SKILL.md: %v", err)
+ }
+
+ ctx := TaskContextForEnv{
+ IssueID: "collision-test",
+ AgentSkills: []SkillContextForEnv{
+ {Name: "Review", Content: "---\nname: whatever-upstream-said\n---\n\nmultica body"},
+ },
+ }
+
+ if err := writeContextFiles(dir, "opencode", ctx, nil); err != nil {
+ t.Fatalf("writeContextFiles failed: %v", err)
+ }
+
+ // The user's directory is untouched.
+ got, err := os.ReadFile(filepath.Join(userSkill, "SKILL.md"))
+ if err != nil {
+ t.Fatalf("read user SKILL.md: %v", err)
+ }
+ if string(got) != userContent {
+ t.Errorf("user skill was overwritten; got:\n%s", got)
+ }
+
+ // Multica's copy landed at the fallback slug and names itself after it.
+ moved, err := os.ReadFile(filepath.Join(dir, ".opencode", "skills", "review-multica", "SKILL.md"))
+ if err != nil {
+ t.Fatalf("read relocated SKILL.md: %v", err)
+ }
+ want := "---\nname: review-multica\n---\n\nmultica body"
+ if string(moved) != want {
+ t.Errorf("frontmatter name did not follow the collision slug; got:\n%s\nwant:\n%s", moved, want)
+ }
+}
+
+// The name rewrite must not disturb neighbouring keys, including a nested
+// mapping that happens to contain its own `name`. Only the top-level key is
+// the skill's identity; rewriting an indented one would splice a top-level key
+// into the middle of the nested block and corrupt the YAML.
+func TestWriteContextFilesLeavesNestedFrontmatterNameAlone(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+
+ ctx := TaskContextForEnv{
+ IssueID: "nested-name-test",
+ AgentSkills: []SkillContextForEnv{
+ {
+ Name: "Nested",
+ Content: "---\nmetadata:\n name: inner\n---\n\nbody",
+ },
+ },
+ }
+
+ if err := writeContextFiles(dir, "opencode", ctx, nil); err != nil {
+ t.Fatalf("writeContextFiles failed: %v", err)
+ }
+
+ skillMd, err := os.ReadFile(filepath.Join(dir, ".opencode", "skills", "nested", "SKILL.md"))
+ if err != nil {
+ t.Fatalf("failed to read SKILL.md: %v", err)
+ }
+
+ // The block has no top-level name, so one is injected; `metadata.name`
+ // stays put.
+ want := "---\nname: nested\nmetadata:\n name: inner\n---\n\nbody"
+ if string(skillMd) != want {
+ t.Errorf("nested name handling is wrong; got:\n%s\nwant:\n%s", skillMd, want)
}
}
@@ -1504,7 +1612,8 @@ func TestInjectRuntimeConfigOpencode(t *testing.T) {
if !strings.Contains(s, "Multica Agent Runtime") {
t.Error("AGENTS.md missing meta skill header")
}
- if !strings.Contains(s, "Coding") {
+ // Listed by on-disk slug rather than the display name (MUL-5529).
+ if !strings.Contains(s, "coding") {
t.Error("AGENTS.md missing skill name")
}
if !strings.Contains(s, "discovered automatically") {
@@ -1539,7 +1648,8 @@ func TestInjectRuntimeConfigKiro(t *testing.T) {
if !strings.Contains(s, "Multica Agent Runtime") {
t.Error("AGENTS.md missing meta skill header")
}
- if !strings.Contains(s, "Coding") {
+ // Listed by on-disk slug rather than the display name (MUL-5529).
+ if !strings.Contains(s, "coding") {
t.Error("AGENTS.md missing skill name")
}
if !strings.Contains(s, "discovered automatically") {
@@ -1569,7 +1679,8 @@ func TestInjectRuntimeConfigQoder(t *testing.T) {
if !strings.Contains(s, "Multica Agent Runtime") {
t.Error("AGENTS.md missing meta skill header")
}
- if !strings.Contains(s, "Coding") {
+ // Listed by on-disk slug rather than the display name (MUL-5529).
+ if !strings.Contains(s, "coding") {
t.Error("AGENTS.md missing skill name")
}
if !strings.Contains(s, "discovered automatically") {
@@ -1602,7 +1713,8 @@ func TestInjectRuntimeConfigAntigravity(t *testing.T) {
if !strings.Contains(s, "Multica Agent Runtime") {
t.Error("AGENTS.md missing meta skill header")
}
- if !strings.Contains(s, "Coding") {
+ // Listed by on-disk slug rather than the display name (MUL-5529).
+ if !strings.Contains(s, "coding") {
t.Error("AGENTS.md missing skill name")
}
if !strings.Contains(s, "discovered automatically") {
@@ -2051,7 +2163,8 @@ func TestInjectRuntimeConfigHermes(t *testing.T) {
if !strings.Contains(s, "Multica Agent Runtime") {
t.Error("AGENTS.md missing meta skill header")
}
- if !strings.Contains(s, "Coding") {
+ // Listed by on-disk slug rather than the display name (MUL-5529).
+ if !strings.Contains(s, "coding") {
t.Error("AGENTS.md missing skill name")
}
// Hermes now discovers skills from the daemon-seeded per-task
diff --git a/server/internal/daemon/execenv/sidecar_manifest.go b/server/internal/daemon/execenv/sidecar_manifest.go
index b98b646000..0e84ecf49e 100644
--- a/server/internal/daemon/execenv/sidecar_manifest.go
+++ b/server/internal/daemon/execenv/sidecar_manifest.go
@@ -176,15 +176,7 @@ func recordWriteFile(path string, data []byte, perm os.FileMode, m *sidecarManif
func allocateCollisionFreeSkillDir(skillsParent, baseSlug string) (slug, dir string, err error) {
const maxAttempts = 64
for i := 0; i < maxAttempts; i++ {
- var candidate string
- switch {
- case i == 0:
- candidate = baseSlug
- case i == 1:
- candidate = baseSlug + "-multica"
- default:
- candidate = fmt.Sprintf("%s-multica-%d", baseSlug, i)
- }
+ candidate := skillSlugCandidate(baseSlug, i)
path := filepath.Join(skillsParent, candidate)
if _, statErr := os.Lstat(path); statErr != nil {
if errors.Is(statErr, fs.ErrNotExist) {
@@ -196,6 +188,24 @@ func allocateCollisionFreeSkillDir(skillsParent, baseSlug string) (slug, dir str
return "", "", fmt.Errorf("allocate collision-free skill dir under %s: exhausted %d attempts for base %q", skillsParent, maxAttempts, baseSlug)
}
+// skillSlugCandidate is the nth name to try for a skill whose natural slug is
+// baseSlug: the bare slug first, then `-multica`, then numbered variants.
+//
+// Two callers must agree on this sequence — allocateCollisionFreeSkillDir,
+// which probes the filesystem, and resolveSkillSlugs, which deduplicates a
+// batch in memory before anything is written. If they disagreed, a skill would
+// be listed under one name and written under another.
+func skillSlugCandidate(baseSlug string, attempt int) string {
+ switch {
+ case attempt <= 0:
+ return baseSlug
+ case attempt == 1:
+ return baseSlug + "-multica"
+ default:
+ return fmt.Sprintf("%s-multica-%d", baseSlug, attempt)
+ }
+}
+
// writeSidecarManifest persists m to {envRoot}/{sidecarManifestFile}.
// Empty manifests are still written so a later Cleanup that finds the
// file knows tracking was attempted (vs. an old build that predates this
diff --git a/server/internal/daemon/execenv/skill_frontmatter_test.go b/server/internal/daemon/execenv/skill_frontmatter_test.go
index 7a6a89cdb1..2d63069259 100644
--- a/server/internal/daemon/execenv/skill_frontmatter_test.go
+++ b/server/internal/daemon/execenv/skill_frontmatter_test.go
@@ -33,25 +33,52 @@ func parseFrontmatter(t *testing.T, content string) map[string]any {
// is not valid YAML (an unquoted `: ` in the description is the canonical case)
// must be rewritten into a parseable block instead of being shipped as-is, or a
// strict runtime drops the whole skill on load.
+//
+// The name key's spelling must not change the route: `"name":`, `'name':`, and
+// a valueless `name:` are the same top-level key as a bare `name: x`, so a
+// block carrying any of them already has a name. Misreading them as nameless
+// injects a second `name` above the malformed block — a duplicate mapping key,
+// so the output stays unloadable instead of being healed (MUL-5529).
func TestEnsureSkillFrontmatterReSynthesizesInvalidYAML(t *testing.T) {
t.Parallel()
const body = "# Heading\n\nReal skill body.\n"
- // `description: bad: value` is the exact failure mode from the issue: the
- // second `: ` makes YAML treat the tail as a nested mapping.
- broken := "---\nname: keep-me\ndescription: bad: value here\n---\n\n" + body
+ cases := []struct {
+ name string
+ nameLine string
+ }{
+ {name: "bare name key", nameLine: "name: keep-me"},
+ {name: "double quoted name key", nameLine: `"name": keep-me`},
+ {name: "single quoted name key", nameLine: `'name': keep-me`},
+ {name: "name key with no value", nameLine: "name:"},
+ }
- got := ensureSkillFrontmatter(broken, "my-slug", "DB description: with a colon")
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ // `description: bad: value here` is the exact failure mode from
+ // the issue: the second `: ` makes YAML treat the tail as a
+ // nested mapping.
+ broken := "---\n" + tc.nameLine + "\ndescription: bad: value here\n---\n\n" + body
+ if isFrontmatterValidYAML(broken) {
+ t.Fatalf("fixture parses; it no longer exercises the malformed branch:\n%s", broken)
+ }
- fm := parseFrontmatter(t, got)
- if name, _ := fm["name"].(string); name != "my-slug" {
- t.Errorf("name = %#v, want %q", fm["name"], "my-slug")
- }
- if desc, _ := fm["description"].(string); desc != "DB description: with a colon" {
- t.Errorf("description = %#v, want the DB description verbatim", fm["description"])
- }
- if !strings.Contains(got, "Real skill body.") {
- t.Errorf("body was dropped during re-synthesis:\n%s", got)
+ got := ensureSkillFrontmatter(broken, "my-slug", "DB description: with a colon")
+
+ // parseFrontmatter fails the test on output a strict runtime
+ // would reject — including the duplicate `name` this guards.
+ fm := parseFrontmatter(t, got)
+ if name, _ := fm["name"].(string); name != "my-slug" {
+ t.Errorf("name = %#v, want %q\noutput:\n%s", fm["name"], "my-slug", got)
+ }
+ if desc, _ := fm["description"].(string); desc != "DB description: with a colon" {
+ t.Errorf("description = %#v, want the DB description verbatim\noutput:\n%s", fm["description"], got)
+ }
+ if !strings.Contains(got, "Real skill body.") {
+ t.Errorf("body was dropped during re-synthesis:\n%s", got)
+ }
+ })
}
}
@@ -77,16 +104,351 @@ func TestEnsureSkillFrontmatterReSynthesizesInvalidYAMLWithEmptyDescription(t *t
}
}
-// Valid frontmatter that already carries a name must survive untouched —
-// re-synthesis is only for the broken case, so upstream import formatting is
-// preserved on the happy path.
-func TestEnsureSkillFrontmatterLeavesValidYAMLUntouched(t *testing.T) {
+// Valid frontmatter survives re-synthesis: every key keeps its upstream
+// formatting and only `name` is retargeted at the slug. Re-synthesis proper is
+// still reserved for the broken case.
+//
+// `name` cannot be left alone because runtimes disagree on which field
+// identifies a skill (OpenCode: frontmatter `name`; Claude: directory name), so
+// an upstream value that differs from the slug makes the skill answer to two
+// names depending on the runtime (MUL-5529).
+func TestEnsureSkillFrontmatterRetargetsNameAndKeepsOtherKeys(t *testing.T) {
t.Parallel()
valid := "---\nname: upstream\ndescription: \"colon: safe because quoted\"\nextra-key: kept\n---\n\nbody\n"
+ want := "---\nname: my-slug\ndescription: \"colon: safe because quoted\"\nextra-key: kept\n---\n\nbody\n"
+
+ if got := ensureSkillFrontmatter(valid, "my-slug", "ignored"); got != want {
+ t.Errorf("frontmatter name was not retargeted;\n got: %q\nwant: %q", got, want)
+ }
+}
+
+// A YAML value can span several lines. Replacing only the key's own line
+// leaves the continuation behind, and YAML folds it into the new value:
+// `name: >-\n upstream` became "my-slug upstream", so the directory name and
+// the frontmatter name diverged again — exactly the invariant this rewrite
+// exists to hold.
+//
+// These assert on the *parsed* value rather than the output text, because the
+// text's first line looked correct in every one of these cases.
+func TestEnsureSkillFrontmatterReplacesMultiLineNameValues(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ content string
+ }{
+ {
+ name: "folded block scalar",
+ content: "---\nname: >-\n upstream-name\ndescription: kept\n---\n\nbody\n",
+ },
+ {
+ name: "literal block scalar",
+ content: "---\nname: |-\n upstream-name\ndescription: kept\n---\n\nbody\n",
+ },
+ {
+ name: "multi-line plain scalar",
+ content: "---\nname: upstream\n continued\ndescription: kept\n---\n\nbody\n",
+ },
+ {
+ name: "wrapped quoted scalar",
+ content: "---\nname: \"upstream\n continued\"\ndescription: kept\n---\n\nbody\n",
+ },
+ {
+ name: "value entirely on the next line",
+ content: "---\nname:\n upstream-name\ndescription: kept\n---\n\nbody\n",
+ },
+ // A quoted scalar may wrap onto a line at the SAME indentation as its
+ // key, and so may a flow collection. Indentation therefore cannot bound
+ // a YAML value: an indentation rule stops at the key's line and strands
+ // the remainder, so the rewrite emitted invalid YAML rather than a
+ // wrong-but-parseable name.
+ {
+ name: "double quoted continued at same indent",
+ content: "---\nname: \"upstream\ncontinued\"\ndescription: kept\n---\n\nbody\n",
+ },
+ {
+ name: "single quoted continued at same indent",
+ content: "---\nname: 'upstream\ncontinued'\ndescription: kept\n---\n\nbody\n",
+ },
+ {
+ name: "flow sequence continued at same indent",
+ content: "---\nname: [a,\nb]\ndescription: kept\n---\n\nbody\n",
+ },
+ {
+ name: "flow mapping continued at same indent",
+ content: "---\nname: {a: 1,\nb: 2}\ndescription: kept\n---\n\nbody\n",
+ },
+ {
+ name: "name is the last key",
+ content: "---\ndescription: kept\nname: \"upstream\ncontinued\"\n---\n\nbody\n",
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ // Assert the *input* is valid YAML first. Otherwise a case could
+ // pass for the wrong reason — ensureSkillFrontmatter re-synthesizes
+ // malformed blocks, which would produce the right name without ever
+ // exercising the surgical path these cases exist to cover.
+ parseFrontmatter(t, tc.content)
+
+ got := ensureSkillFrontmatter(tc.content, "my-slug", "")
+
+ fm := parseFrontmatter(t, got)
+ if name, _ := fm["name"].(string); name != "my-slug" {
+ t.Errorf("parsed name = %#v, want %q\noutput:\n%s", fm["name"], "my-slug", got)
+ }
+ // Neighbouring keys still survive the surgery.
+ if desc, _ := fm["description"].(string); desc != "kept" {
+ t.Errorf("description = %#v, want %q\noutput:\n%s", fm["description"], "kept", got)
+ }
+ if !strings.Contains(got, "body") {
+ t.Errorf("body was dropped:\n%s", got)
+ }
+ })
+ }
+}
+
+// An anchor on the name value defeats the surgical rewrite: replacing the line
+// removes `&skill_name`, so an alias pointing at it no longer resolves and the
+// post-condition check correctly rejects the result. What must NOT happen next
+// is a drop to bare re-synthesis, which emits only name and description.
+//
+// The stakes are higher than lost formatting. `disable-model-invocation: true`
+// is the author's instruction that a runtime must not surface this skill on its
+// own; if the written SKILL.md loses it, native discovery advertises a skill
+// that was deliberately hidden — the opposite of the author's intent.
+func TestEnsureSkillFrontmatterKeepsPolicyKeysWhenSurgicalRewriteFails(t *testing.T) {
+ t.Parallel()
+
+ in := "---\nname: &skill_name upstream\ndescription: *skill_name\ndisable-model-invocation: true\ncustom-key: kept\n---\n\nbody\n"
+
+ // The input is valid YAML, so this exercises the fallback rather than the
+ // invalid-YAML re-synthesis path.
+ parseFrontmatter(t, in)
+
+ got := ensureSkillFrontmatter(in, "my-slug", "")
+
+ fm := parseFrontmatter(t, got)
+ if name, _ := fm["name"].(string); name != "my-slug" {
+ t.Errorf("name = %#v, want %q\noutput:\n%s", fm["name"], "my-slug", got)
+ }
+ if fm["disable-model-invocation"] != true {
+ t.Errorf("disable-model-invocation was dropped (%#v); the written skill would be exposed to native discovery\noutput:\n%s", fm["disable-model-invocation"], got)
+ }
+ if custom, _ := fm["custom-key"].(string); custom != "kept" {
+ t.Errorf("custom-key = %#v, want %q\noutput:\n%s", fm["custom-key"], "kept", got)
+ }
+ // The alias resolved to "upstream" before the rename and must still, rather
+ // than following name to the slug. See
+ // TestEnsureSkillFrontmatterKeepsAliasedValuesWhenNameIsRenamed for why
+ // letting it follow is a policy bypass and not just a cosmetic difference.
+ if desc, _ := fm["description"].(string); desc != "upstream" {
+ t.Errorf("aliased description = %#v, want %q\noutput:\n%s", fm["description"], "upstream", got)
+ }
+ // The written file must still read as hidden to the visibility check that
+ // gates whether a skill is advertised.
+ if !skillDisablesModelInvocation(got) {
+ t.Errorf("written skill no longer reads as disable-model-invocation:\n%s", got)
+ }
+ if !strings.Contains(got, "body") {
+ t.Errorf("body was dropped:\n%s", got)
+ }
+}
+
+// lookupPath resolves a dotted key path through nested frontmatter mappings,
+// returning nil when any segment is missing.
+func lookupPath(fm map[string]any, path string) any {
+ var cur any = fm
+ for _, seg := range strings.Split(path, ".") {
+ m, ok := cur.(map[string]any)
+ if !ok {
+ return nil
+ }
+ cur, ok = m[seg]
+ if !ok {
+ return nil
+ }
+ }
+ return cur
+}
+
+// Keeping the anchor alive is not enough: a document can express another
+// setting by *reusing* the name's value, and then renaming the anchored node
+// silently rewrites that setting too. Here `disable-model-invocation` is an
+// alias of a name whose value is "true", so binding the alias to the renamed
+// node turns the skill visible again — the same exposure as dropping the key,
+// reached by a different route.
+//
+// Preserving a key is therefore not the invariant. Preserving each key's
+// resolved *value* is.
+func TestEnsureSkillFrontmatterKeepsAliasedValuesWhenNameIsRenamed(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ content string
+ // alsoAliased names further keys whose resolved value must still be
+ // the anchor's original "true" — asserting the invariant on every
+ // alias, not only the one that happens to gate visibility.
+ alsoAliased []string
+ }{
+ {
+ name: "alias carries the policy value",
+ content: "---\nname: &shared \"true\"\ndisable-model-invocation: *shared\ncustom-key: kept\n---\n\nbody\n",
+ },
+ {
+ name: "alias nested inside another mapping",
+ content: "---\nname: &shared \"true\"\nmeta:\n inner: *shared\ndisable-model-invocation: *shared\n---\n\nbody\n",
+ alsoAliased: []string{"meta.inner"},
+ },
+ {
+ name: "two aliases of the same anchor",
+ content: "---\nname: &shared \"true\"\ndisable-model-invocation: *shared\nother: *shared\n---\n\nbody\n",
+ alsoAliased: []string{"other"},
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ // Valid YAML in, so this is the node-rebuild fallback rather than
+ // the invalid-YAML re-synthesis path.
+ parseFrontmatter(t, tc.content)
+
+ // The skill starts out hidden from model invocation...
+ if !skillDisablesModelInvocation(tc.content) {
+ t.Fatalf("fixture is not hidden to begin with; the test proves nothing")
+ }
+
+ got := ensureSkillFrontmatter(tc.content, "my-slug", "")
+
+ // ...and must still be hidden afterwards.
+ if !skillDisablesModelInvocation(got) {
+ t.Errorf("rewrite exposed a hidden skill\noutput:\n%s", got)
+ }
+
+ fm := parseFrontmatter(t, got)
+ if name, _ := fm["name"].(string); name != "my-slug" {
+ t.Errorf("name = %#v, want %q\noutput:\n%s", fm["name"], "my-slug", got)
+ }
+ if _, stillAliased := fm["disable-model-invocation"]; !stillAliased {
+ t.Errorf("disable-model-invocation disappeared\noutput:\n%s", got)
+ }
+ // Every other alias of the same anchor must also hold its
+ // pre-rename value, not just the one gating visibility.
+ for _, path := range tc.alsoAliased {
+ if v := lookupPath(fm, path); v != "true" {
+ t.Errorf("aliased %s = %#v, want %q\noutput:\n%s", path, v, "true", got)
+ }
+ }
+ if strings.Contains(got, "*shared") || strings.Contains(got, "&shared") {
+ t.Errorf("anchor/alias survived instead of being materialized\noutput:\n%s", got)
+ }
+ })
+ }
+}
+
+// Whether a name exists is a question about the parsed document, not about how
+// the key happens to be spelled. A lexical scan only recognizes a bare `name:`
+// with a value on the same line, so a quoted key or an empty value read as
+// "nameless" and got a second `name` injected above them.
+//
+// The result is a duplicate mapping key, which strict loaders reject outright:
+// the skill does not merely carry the wrong name, it fails to load at all.
+func TestEnsureSkillFrontmatterRecognizesQuotedAndEmptyNameKeys(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ content string
+ }{
+ {
+ name: "double quoted key",
+ content: "---\n\"name\": upstream\ndisable-model-invocation: true\ncustom-key: kept\n---\n\nbody\n",
+ },
+ {
+ name: "single quoted key",
+ content: "---\n'name': upstream\ndisable-model-invocation: true\ncustom-key: kept\n---\n\nbody\n",
+ },
+ {
+ name: "key present with no value",
+ content: "---\nname:\ndisable-model-invocation: true\ncustom-key: kept\n---\n\nbody\n",
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ parseFrontmatter(t, tc.content)
+
+ got := ensureSkillFrontmatter(tc.content, "my-slug", "")
+
+ // parseFrontmatter fails the test on a duplicate `name`, which is
+ // the exact symptom this guards.
+ fm := parseFrontmatter(t, got)
+ if name, _ := fm["name"].(string); name != "my-slug" {
+ t.Errorf("name = %#v, want %q\noutput:\n%s", fm["name"], "my-slug", got)
+ }
+ if fm["disable-model-invocation"] != true {
+ t.Errorf("disable-model-invocation = %#v, want true\noutput:\n%s", fm["disable-model-invocation"], got)
+ }
+ if custom, _ := fm["custom-key"].(string); custom != "kept" {
+ t.Errorf("custom-key = %#v, want %q\noutput:\n%s", fm["custom-key"], "kept", got)
+ }
+ if !skillDisablesModelInvocation(got) {
+ t.Errorf("written skill no longer reads as hidden:\n%s", got)
+ }
+ })
+ }
+}
+
+// Comments and blank lines between the name entry and the next key are not part
+// of the value, so the rewrite must step over them rather than absorb them into
+// the replaced span.
+func TestEnsureSkillFrontmatterKeepsCommentsAroundName(t *testing.T) {
+ t.Parallel()
+
+ in := "---\nname: >-\n upstream\n\n# keep this comment\ndescription: kept\n---\n\nbody\n"
+ want := "---\nname: my-slug\n\n# keep this comment\ndescription: kept\n---\n\nbody\n"
+
+ if got := ensureSkillFrontmatter(in, "my-slug", ""); got != want {
+ t.Errorf("comment or spacing was swallowed;\n got: %q\nwant: %q", got, want)
+ }
+}
+
+// A block scalar may legitimately contain a line that looks like a comment.
+// Because block scalar content is always indented, the "step over comments"
+// rule must only skip *unindented* ones — otherwise this content is left
+// stranded outside the replaced span.
+func TestEnsureSkillFrontmatterHandlesHashInsideBlockScalarName(t *testing.T) {
+ t.Parallel()
+
+ in := "---\nname: |-\n upstream\n # not a comment\ndescription: kept\n---\n\nbody\n"
+
+ got := ensureSkillFrontmatter(in, "my-slug", "")
+
+ fm := parseFrontmatter(t, got)
+ if name, _ := fm["name"].(string); name != "my-slug" {
+ t.Errorf("parsed name = %#v, want %q\noutput:\n%s", fm["name"], "my-slug", got)
+ }
+ if strings.Contains(got, "# not a comment") {
+ t.Errorf("block scalar content was stranded outside the replaced span:\n%s", got)
+ }
+}
+
+// The rewrite is byte-surgical: a CRLF block keeps its line endings instead of
+// acquiring a lone LF on the name line.
+func TestEnsureSkillFrontmatterPreservesCRLFOnNameRewrite(t *testing.T) {
+ t.Parallel()
+
+ valid := "---\r\nname: upstream\r\ndescription: kept\r\n---\r\n\r\nbody\r\n"
+ want := "---\r\nname: my-slug\r\ndescription: kept\r\n---\r\n\r\nbody\r\n"
- if got := ensureSkillFrontmatter(valid, "my-slug", "ignored"); got != valid {
- t.Errorf("valid frontmatter was rewritten;\n got: %q\nwant: %q", got, valid)
+ if got := ensureSkillFrontmatter(valid, "my-slug", "ignored"); got != want {
+ t.Errorf("CRLF frontmatter mangled;\n got: %q\nwant: %q", got, want)
}
}
diff --git a/server/internal/daemon/execenv/skill_visibility.go b/server/internal/daemon/execenv/skill_visibility.go
index 1edaea47ab..832433c77e 100644
--- a/server/internal/daemon/execenv/skill_visibility.go
+++ b/server/internal/daemon/execenv/skill_visibility.go
@@ -6,19 +6,73 @@ import (
"gopkg.in/yaml.v3"
)
+// modelVisibleSkills returns the skills a model may invoke, with Name
+// normalized to the on-disk slug.
+//
+// The normalization is not cosmetic. Every caller renders these entries into a
+// listing the model reads to pick a skill, and the only name it can actually
+// invoke is the directory slug writeSkillFiles lays down — sanitizeSkillName of
+// the same field. A workspace skill's Name is its human display name ("PR
+// review"), so listing it verbatim hands the model an identifier that does not
+// resolve (MUL-5529). Normalizing here rather than at each call site keeps the
+// four listings (runtime brief + the three issue_context renderers) from
+// drifting apart.
+//
+// Slugs come from resolveSkillSlugs over the *unfiltered* batch, because
+// writeSkillFiles lays down every skill — including the ones hidden here — and
+// each one consumes a slug. Filtering first would shift the suffixes and make
+// the listing disagree with the directories.
+//
+// Known gap: resolveSkillSlugs cannot see the filesystem, so a skill that
+// collides with a *user-installed* directory is still written to
+// `<slug>-multica` while the listing shows the bare slug. Closing that needs
+// the allocated slug threaded back from Prepare, which these renderers
+// deliberately cannot reach — they are pure so the brief stays byte-identical
+// across runs. Tracked in MUL-5550.
func modelVisibleSkills(skills []SkillContextForEnv) []SkillContextForEnv {
if len(skills) == 0 {
return nil
}
+ slugs := resolveSkillSlugs(skills)
visible := make([]SkillContextForEnv, 0, len(skills))
- for _, skill := range skills {
+ for i, skill := range skills {
if skillModelInvocationVisible(skill) {
+ skill.Name = slugs[i]
visible = append(visible, skill)
}
}
return visible
}
+// resolveSkillSlugs assigns each skill in a batch its on-disk directory slug,
+// deduplicating within the batch so two skills never claim the same directory.
+//
+// sanitizeSkillName alone is not injective: "A B" and "A-B" both reduce to
+// "a-b". writeSkillFiles resolves that at write time via
+// allocateCollisionFreeSkillDir, so the second skill lands in `a-b-multica` —
+// but a listing built from sanitizeSkillName alone would name both `a-b`,
+// leaving the second skill with no invocable name and silently pointing the
+// model at the first. Deriving both sides from this function keeps them in
+// step. It is deterministic in the batch (index order only), so the brief stays
+// byte-identical across runs for identical input.
+func resolveSkillSlugs(skills []SkillContextForEnv) []string {
+ slugs := make([]string, len(skills))
+ taken := make(map[string]struct{}, len(skills))
+ for i, skill := range skills {
+ base := sanitizeSkillName(skill.Name)
+ slug := base
+ for attempt := 1; ; attempt++ {
+ if _, clash := taken[slug]; !clash {
+ break
+ }
+ slug = skillSlugCandidate(base, attempt)
+ }
+ taken[slug] = struct{}{}
+ slugs[i] = slug
+ }
+ return slugs
+}
+
func skillModelInvocationVisible(skill SkillContextForEnv) bool {
return !skillDisablesModelInvocation(skill.Content)
}
diff --git a/server/internal/daemon/execenv/skill_visibility_test.go b/server/internal/daemon/execenv/skill_visibility_test.go
index 6aae92bd3a..c6bc7c9bd4 100644
--- a/server/internal/daemon/execenv/skill_visibility_test.go
+++ b/server/internal/daemon/execenv/skill_visibility_test.go
@@ -139,15 +139,107 @@ Hidden body.`,
}
for name, out := range rendered {
- if !strings.Contains(out, "Visible Skill") {
+ // Listings carry the on-disk slug, not the display name (MUL-5529).
+ if !strings.Contains(out, "visible-skill") {
t.Errorf("%s missing visible skill:\n%s", name, out)
}
- if strings.Contains(out, "Hidden Skill") || strings.Contains(out, "hidden description") {
+ if strings.Contains(out, "Visible Skill") {
+ t.Errorf("%s lists the display name instead of the slug:\n%s", name, out)
+ }
+ if strings.Contains(out, "hidden-skill") || strings.Contains(out, "hidden description") {
t.Errorf("%s advertised disable-model-invocation skill:\n%s", name, out)
}
}
}
+// sanitizeSkillName is not injective — "A B" and "A-B" both reduce to "a-b" —
+// so a listing built from it alone names two skills identically while
+// writeSkillFiles puts the second in `a-b-multica`. The second skill then has
+// no invocable name and the model is silently pointed at the first. This needs
+// no user-installed skill and no local_directory: an ordinary task with two
+// such skills bound reproduces it in a clean workdir.
+//
+// The assertion is set equality between what is listed and what exists on
+// disk, so any future drift between the two allocators fails here.
+func TestSkillListingNamesMatchDirectoriesOnBatchSlugCollision(t *testing.T) {
+ t.Parallel()
+
+ skills := []SkillContextForEnv{
+ {Name: "A B", Content: "---\nname: one\n---\n\nfirst"},
+ {Name: "A-B", Content: "---\nname: two\n---\n\nsecond"},
+ {Name: "a.b", Content: "---\nname: three\n---\n\nthird"},
+ }
+
+ dir := t.TempDir()
+ if err := writeSkillFiles(dir, skills, nil); err != nil {
+ t.Fatalf("writeSkillFiles failed: %v", err)
+ }
+
+ onDisk := map[string]struct{}{}
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatalf("read skills dir: %v", err)
+ }
+ for _, e := range entries {
+ onDisk[e.Name()] = struct{}{}
+ if _, err := os.Stat(filepath.Join(dir, e.Name(), "SKILL.md")); err != nil {
+ t.Errorf("no SKILL.md under %s: %v", e.Name(), err)
+ }
+ }
+
+ listed := map[string]struct{}{}
+ for _, s := range modelVisibleSkills(skills) {
+ if _, dup := listed[s.Name]; dup {
+ t.Errorf("listing repeats the name %q, so one skill has no invocable name", s.Name)
+ }
+ listed[s.Name] = struct{}{}
+ }
+
+ if len(listed) != len(skills) {
+ t.Errorf("listed %d distinct names for %d skills: %v", len(listed), len(skills), listed)
+ }
+ for name := range listed {
+ if _, ok := onDisk[name]; !ok {
+ t.Errorf("listing advertises %q but no such directory exists; on disk: %v", name, onDisk)
+ }
+ }
+ for name := range onDisk {
+ if _, ok := listed[name]; !ok {
+ t.Errorf("directory %q was written but never listed; listed: %v", name, listed)
+ }
+ }
+}
+
+// Hidden skills still occupy a directory, so they must still consume a slug.
+// Allocating over the filtered list instead of the full batch would shift every
+// later suffix and desynchronize the listing from disk.
+func TestBatchSlugAllocationCountsHiddenSkills(t *testing.T) {
+ t.Parallel()
+
+ skills := []SkillContextForEnv{
+ {Name: "A B", Content: "---\nname: hidden\ndisable-model-invocation: true\n---\n\nhidden"},
+ {Name: "A-B", Content: "---\nname: visible\n---\n\nvisible"},
+ }
+
+ dir := t.TempDir()
+ if err := writeSkillFiles(dir, skills, nil); err != nil {
+ t.Fatalf("writeSkillFiles failed: %v", err)
+ }
+
+ visible := modelVisibleSkills(skills)
+ if len(visible) != 1 {
+ t.Fatalf("expected 1 visible skill, got %d", len(visible))
+ }
+ // The hidden skill took `a-b`, so the visible one must be listed — and
+ // written — as `a-b-multica`.
+ if visible[0].Name != "a-b-multica" {
+ t.Errorf("visible skill listed as %q, want %q", visible[0].Name, "a-b-multica")
+ }
+ if _, err := os.Stat(filepath.Join(dir, "a-b-multica", "SKILL.md")); err != nil {
+ t.Errorf("listed name has no matching directory: %v", err)
+ }
+}
+
func TestRenderedSkillListsOmitSectionWhenOnlyDisabledSkills(t *testing.T) {
t.Parallel()