Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(skills): parse multi-line YAML frontmatter in SKILL.md (#3495) (#3543)
YOMXXX801c201d4c7e
diff --git a/packages/core/package.json b/packages/core/package.jsonindex b84d72b952..3eec2e7fe2 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -98,7 +98,9 @@"./analytics": "./analytics/index.ts","./i18n": "./i18n/index.ts","./i18n/react": "./i18n/react.ts",- "./i18n/browser": "./i18n/browser.ts"+ "./i18n/browser": "./i18n/browser.ts",+ "./skills": "./skills/index.ts",+ "./skills/frontmatter": "./skills/frontmatter.ts"},"dependencies": {"@formatjs/intl-localematcher": "catalog:",@@ -107,6 +109,7 @@"i18next": "catalog:","posthog-js": "catalog:","react-i18next": "catalog:",+ "yaml": "catalog:","zod": "catalog:","zustand": "catalog:"},diff --git a/packages/core/skills/frontmatter.test.ts b/packages/core/skills/frontmatter.test.tsnew file mode 100644index 0000000000..7c6b3571fe--- /dev/null+++ b/packages/core/skills/frontmatter.test.ts@@ -0,0 +1,100 @@+import { describe, it, expect } from "vitest";+import { parseFrontmatter } from "./frontmatter";++describe("parseFrontmatter", () => {+ it("parses single-line values", () => {+ const { frontmatter, body } = parseFrontmatter(+ "---\nname: foo\ndescription: bar\n---\nbody content",+ );+ expect(frontmatter).toEqual({ name: "foo", description: "bar" });+ expect(body).toBe("body content");+ });++ it("strips double quotes", () => {+ const { frontmatter } = parseFrontmatter(+ '---\nname: "foo"\ndescription: "hello world"\n---\n',+ );+ expect(frontmatter).toEqual({ name: "foo", description: "hello world" });+ });++ it("strips single quotes", () => {+ const { frontmatter } = parseFrontmatter(+ "---\nname: 'foo'\ndescription: 'hello world'\n---\n",+ );+ expect(frontmatter).toEqual({ name: "foo", description: "hello world" });+ });++ it("preserves newlines in literal block scalar", () => {+ const { frontmatter } = parseFrontmatter(+ "---\nname: foo\ndescription: |\n line1\n line2\n---\n",+ );+ expect(frontmatter?.description).toBe("line1\nline2\n");+ });++ it("drops trailing newline with strip chomping", () => {+ const { frontmatter } = parseFrontmatter(+ "---\nname: foo\ndescription: |-\n line1\n line2\n---\n",+ );+ expect(frontmatter?.description).toBe("line1\nline2");+ });++ it("joins folded block scalar with spaces", () => {+ const { frontmatter } = parseFrontmatter(+ "---\nname: foo\ndescription: >\n line1\n line2\n---\n",+ );+ expect(frontmatter?.description).toBe("line1 line2\n");+ });++ it("handles CRLF line endings", () => {+ const { frontmatter } = parseFrontmatter(+ "---\r\nname: foo\r\ndescription: bar\r\n---\r\nbody",+ );+ expect(frontmatter).toEqual({ name: "foo", description: "bar" });+ });++ it("returns null when no frontmatter", () => {+ const result = parseFrontmatter("plain markdown");+ expect(result.frontmatter).toBeNull();+ expect(result.body).toBe("plain markdown");+ });++ it("returns null when frontmatter is unterminated", () => {+ const result = parseFrontmatter("---\nname: foo\ndescription: bar\n");+ expect(result.frontmatter).toBeNull();+ });++ it("returns null when YAML is invalid", () => {+ const result = parseFrontmatter("---\n: : : not valid\n---\nbody");+ expect(result.frontmatter).toBeNull();+ });++ it("reproduces issue 3495 with Chinese block scalar", () => {+ const content =+ "---\n" ++ "name: requirements-workshop\n" ++ "description: |\n" ++ " 当用户想要开发新功能、讨论需求、梳理业务逻辑时触发。通过多轮对话将模糊的想法转化为结构化的需求文档,为后续技术方案设计提供输入。\n" ++ ' 适用场景:用户说"我想实现XX功能"、"讨论一下这个需求"、"帮我分析一下怎么做"、"这个需求该怎么设计"、"写个需求文档"等。\n' ++ " 本skill只负责产出需求文档,不进入技术设计或代码实现阶段。\n" ++ "---\nbody";++ const { frontmatter } = parseFrontmatter(content);+ expect(frontmatter?.name).toBe("requirements-workshop");+ expect(frontmatter?.description).toBe(+ "当用户想要开发新功能、讨论需求、梳理业务逻辑时触发。通过多轮对话将模糊的想法转化为结构化的需求文档,为后续技术方案设计提供输入。\n" ++ '适用场景:用户说"我想实现XX功能"、"讨论一下这个需求"、"帮我分析一下怎么做"、"这个需求该怎么设计"、"写个需求文档"等。\n' ++ "本skill只负责产出需求文档,不进入技术设计或代码实现阶段。\n",+ );+ });++ it("coerces non-string values to strings", () => {+ const { frontmatter } = parseFrontmatter(+ "---\nname: foo\nversion: 1\nenabled: true\n---\n",+ );+ expect(frontmatter).toEqual({+ name: "foo",+ version: "1",+ enabled: "true",+ });+ });+});diff --git a/packages/core/skills/frontmatter.ts b/packages/core/skills/frontmatter.tsnew file mode 100644index 0000000000..21445e1a8d--- /dev/null+++ b/packages/core/skills/frontmatter.ts@@ -0,0 +1,60 @@+import { parse as parseYaml } from "yaml";++// Keeping the trailing newline inside the capture group matters: yaml's `|`+// clip chomping only preserves a final newline when the input itself contains+// one. Mirrors the regex used by the Go side in `server/internal/skill`.+const FRONTMATTER_RE = /^---\r?\n([\s\S]*?\r?\n)---\r?\n?/;++export type SkillFrontmatter = Record<string, string>;++export interface ParsedFrontmatter {+ frontmatter: SkillFrontmatter | null;+ body: string;+}++export function parseFrontmatter(raw: string): ParsedFrontmatter {+ const match = FRONTMATTER_RE.exec(raw);+ if (!match) return { frontmatter: null, body: raw };++ const yamlBlock = match[1]!;+ const body = raw.slice(match[0].length);++ let parsed: unknown;+ try {+ parsed = parseYaml(yamlBlock);+ } catch {+ return { frontmatter: null, body };+ }++ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ return { frontmatter: null, body };+ }++ const result: SkillFrontmatter = {};+ for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {+ if (value == null) continue;+ if (typeof value === "string") {+ result[key] = value;+ } else if (typeof value === "number" || typeof value === "boolean") {+ result[key] = String(value);+ } else {+ result[key] = JSON.stringify(value);+ }+ }++ return {+ frontmatter: Object.keys(result).length > 0 ? result : null,+ body,+ };+}++export function parseSkillFrontmatter(content: string): {+ name: string;+ description: string;+} {+ const { frontmatter } = parseFrontmatter(content);+ return {+ name: frontmatter?.name ?? "",+ description: frontmatter?.description ?? "",+ };+}diff --git a/packages/core/skills/index.ts b/packages/core/skills/index.tsnew file mode 100644index 0000000000..9340abdbde--- /dev/null+++ b/packages/core/skills/index.ts@@ -0,0 +1 @@+export * from "./frontmatter";diff --git a/packages/views/skills/components/file-viewer.tsx b/packages/views/skills/components/file-viewer.tsxindex 26fcc17e1e..9457bfc5df 100644--- a/packages/views/skills/components/file-viewer.tsx+++ b/packages/views/skills/components/file-viewer.tsx@@ -5,6 +5,10 @@ import { Pencil, Eye } from "lucide-react";import { Button } from "@multica/ui/components/ui/button";import { Textarea } from "@multica/ui/components/ui/textarea";import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";+import {+ parseFrontmatter,+ type SkillFrontmatter,+} from "@multica/core/skills/frontmatter";import { Markdown } from "../../common/markdown";import { useT } from "../../i18n";@@ -12,53 +16,11 @@ function isMarkdown(path: string) {return path.endsWith(".md") || path.endsWith(".mdx");}-// ----------------------------------------------------------------------------// YAML frontmatter parsing-// -----------------------------------------------------------------------------interface Frontmatter {- [key: string]: string;-}--const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;--function parseFrontmatter(raw: string): {- frontmatter: Frontmatter | null;- body: string;-} {- const match = FRONTMATTER_RE.exec(raw);- if (!match) return { frontmatter: null, body: raw };-- const yamlBlock = match[1]!;- const body = raw.slice(match[0].length);- const frontmatter: Frontmatter = {};-- for (const line of yamlBlock.split("\n")) {- const idx = line.indexOf(":");- if (idx === -1) continue;- const key = line.slice(0, idx).trim();- let value = line.slice(idx + 1).trim();- // Strip surrounding quotes- if (- (value.startsWith('"') && value.endsWith('"')) ||- (value.startsWith("'") && value.endsWith("'"))- ) {- value = value.slice(1, -1);- }- if (key) frontmatter[key] = value;- }-- return {- frontmatter: Object.keys(frontmatter).length > 0 ? frontmatter : null,- body,- };-}-// ---------------------------------------------------------------------------// Frontmatter display// ----------------------------------------------------------------------------function FrontmatterCard({ data }: { data: Frontmatter }) {+function FrontmatterCard({ data }: { data: SkillFrontmatter }) {return (<div className="mb-4 rounded-lg border bg-muted/30 px-4 py-3"><div className="grid gap-1.5">@@ -67,7 +29,9 @@ function FrontmatterCard({ data }: { data: Frontmatter }) {<span className="shrink-0 font-medium text-muted-foreground min-w-[80px]">{key}</span>- <span className="text-foreground">{value}</span>+ <span className="text-foreground whitespace-pre-wrap break-words">+ {value.trimEnd()}+ </span></div>))}</div>diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9d59136156..89c49482e7 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -93,6 +93,9 @@ catalogs:vitest:specifier: ^4.1.0version: 4.1.0+ yaml:+ specifier: ^2.6.0+ version: 2.9.0zod:specifier: ^4.1.5version: 4.3.6@@ -743,6 +746,9 @@ importers:react-i18next:specifier: 'catalog:'version: 17.0.6([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])+ yaml:+ specifier: 'catalog:'+ version: 2.9.0zod:specifier: 'catalog:'version: 4.3.6diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 31e0c248e2..2db8c624e5 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -52,6 +52,9 @@ catalog:# Product analyticsposthog-js: "^1.176.1"+ # YAML parsing (skill frontmatter)+ yaml: "^2.6.0"+# Testingvitest: "^4.1.0"jsdom: "^29.0.1"diff --git a/server/go.mod b/server/go.modindex 7f4a6da844..d3c5a44df3 100644--- a/server/go.mod+++ b/server/go.mod@@ -23,6 +23,7 @@ require (github.com/resend/resend-go/v2 v2.28.0github.com/robfig/cron/v3 v3.0.1github.com/spf13/cobra v1.10.2+ gopkg.in/yaml.v3 v3.0.1)require (diff --git a/server/internal/daemon/local_skills.go b/server/internal/daemon/local_skills.goindex 05a6f184fa..59e3c0a5db 100644--- a/server/internal/daemon/local_skills.go+++ b/server/internal/daemon/local_skills.go@@ -7,6 +7,8 @@ import ("path/filepath""sort""strings"++ "github.com/multica-ai/multica/server/internal/skill")const (@@ -130,26 +132,6 @@ func relativizeHomePath(path string) string {return filepath.ToSlash(path)}-func parseLocalSkillFrontmatter(content string) (name, description string) {- if !strings.HasPrefix(content, "---") {- return "", ""- }- end := strings.Index(content[3:], "---")- if end < 0 {- return "", ""- }- frontmatter := content[3 : 3+end]- for _, line := range strings.Split(frontmatter, "\n") {- line = strings.TrimSpace(line)- if strings.HasPrefix(line, "name:") {- name = strings.Trim(strings.TrimSpace(strings.TrimPrefix(line, "name:")), "\"'")- } else if strings.HasPrefix(line, "description:") {- description = strings.Trim(strings.TrimSpace(strings.TrimPrefix(line, "description:")), "\"'")- }- }- return name, description-}-func readLocalSkillMainFile(skillDir string) (string, error) {mainPath := filepath.Join(skillDir, "SKILL.md")info, err := os.Stat(mainPath)@@ -336,7 +318,7 @@ func enumerateLocalSkills(if err != nil {continue}- skillName, description := parseLocalSkillFrontmatter(content)+ skillName, description := skill.ParseFrontmatter(content)if skillName == "" {skillName = filepath.Base(path)}@@ -394,7 +376,7 @@ func loadRuntimeLocalSkillBundle(provider, skillKey string) (*runtimeLocalSkillBif err != nil {return nil, true, err}- name, description := parseLocalSkillFrontmatter(content)+ name, description := skill.ParseFrontmatter(content)if name == "" {name = filepath.Base(skillDir)}diff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.goindex dd280eba80..69691364c0 100644--- a/server/internal/handler/skill.go+++ b/server/internal/handler/skill.go@@ -17,6 +17,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/skill"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -995,7 +996,7 @@ func fetchFromSkillsSh(httpClient *http.Client, rawURL string) (*importedSkill,if skillMdBody == nil {body, err := fetchRawFile(httpClient, buildRawGitHubURL(rawPrefix, "SKILL.md"))if err == nil {- if name, _ := parseSkillFrontmatter(string(body)); name == skillName {+ if name, _ := skill.ParseFrontmatter(string(body)); name == skillName {skillMdBody = bodyskillDir = ""}@@ -1009,7 +1010,7 @@ func fetchFromSkillsSh(httpClient *http.Client, rawURL string) (*importedSkill,}// Parse name and description from YAML frontmatter- name, description := parseSkillFrontmatter(string(skillMdBody))+ name, description := skill.ParseFrontmatter(string(skillMdBody))if name == "" {name = skillName}@@ -1281,7 +1282,7 @@ func findMatchingSkillDirByFrontmatter(httpClient *http.Client, rawPrefix, skillslog.Warn("github import: fallback SKILL.md fetch failed", "path", skillPath, "error", err)continue}- name, _ := parseSkillFrontmatter(string(body))+ name, _ := skill.ParseFrontmatter(string(body))if name == skillName {return skillDirFromSkillFilePath(skillPath), body, true}@@ -1328,29 +1329,6 @@ func skillNameHints(skillName string) []string {return hints}-// parseSkillFrontmatter extracts name and description from YAML frontmatter in SKILL.md.-func parseSkillFrontmatter(content string) (name, description string) {- if !strings.HasPrefix(content, "---") {- return "", ""- }- end := strings.Index(content[3:], "---")- if end < 0 {- return "", ""- }- frontmatter := content[3 : 3+end]- for _, line := range strings.Split(frontmatter, "\n") {- line = strings.TrimSpace(line)- if strings.HasPrefix(line, "name:") {- name = strings.TrimSpace(strings.TrimPrefix(line, "name:"))- name = strings.Trim(name, "\"'")- } else if strings.HasPrefix(line, "description:") {- description = strings.TrimSpace(strings.TrimPrefix(line, "description:"))- description = strings.Trim(description, "\"'")- }- }- return name, description-}-// --- GitHub import ---// errGitHubAPIBlocked signals that an api.github.com probe was rejected for@@ -1592,7 +1570,7 @@ func fetchFromGitHub(httpClient *http.Client, rawURL string) (*importedSkill, erskillMdPath, spec.owner, spec.repo, spec.ref, err)}- name, description := parseSkillFrontmatter(string(skillMdBody))+ name, description := skill.ParseFrontmatter(string(skillMdBody))if name == "" {if spec.skillDir != "" {name = filepath.Base(spec.skillDir)diff --git a/server/internal/skill/frontmatter.go b/server/internal/skill/frontmatter.gonew file mode 100644index 0000000000..9e01768a7e--- /dev/null+++ b/server/internal/skill/frontmatter.go@@ -0,0 +1,36 @@+// Package skill provides shared utilities for working with SKILL.md files.+package skill++import (+ "regexp"+ "strings"++ "gopkg.in/yaml.v3"+)++// Keeping the trailing newline inside group 1 matters: yaml.v3's `|` clip+// chomping only preserves a final newline when the input itself contains one.+var frontmatterPattern = regexp.MustCompile(`(?s)\A---\r?\n(.*?\r?\n)---`)++// ParseFrontmatter extracts name and description from the YAML frontmatter+// block of a SKILL.md file. Returns empty strings when the frontmatter is+// absent or malformed so callers can keep treating missing metadata as a+// non-fatal condition, matching the behaviour of the legacy line-based parser.+func ParseFrontmatter(content string) (name, description string) {+ if !strings.HasPrefix(content, "---") {+ return "", ""+ }+ match := frontmatterPattern.FindStringSubmatch(content)+ if match == nil {+ return "", ""+ }++ var fm struct {+ Name string `yaml:"name"`+ Description string `yaml:"description"`+ }+ if err := yaml.Unmarshal([]byte(match[1]), &fm); err != nil {+ return "", ""+ }+ return fm.Name, fm.Description+}diff --git a/server/internal/skill/frontmatter_test.go b/server/internal/skill/frontmatter_test.gonew file mode 100644index 0000000000..cb88757fef--- /dev/null+++ b/server/internal/skill/frontmatter_test.go@@ -0,0 +1,100 @@+package skill++import "testing"++func TestParseFrontmatter(t *testing.T) {+ tests := []struct {+ name string+ content string+ wantName string+ wantDesc string+ }{+ {+ name: "single line",+ content: "---\nname: foo\ndescription: bar\n---\nbody",+ wantName: "foo",+ wantDesc: "bar",+ },+ {+ name: "double quoted",+ content: "---\nname: \"foo\"\ndescription: \"hello world\"\n---\nbody",+ wantName: "foo",+ wantDesc: "hello world",+ },+ {+ name: "single quoted",+ content: "---\nname: 'foo'\ndescription: 'hello world'\n---\nbody",+ wantName: "foo",+ wantDesc: "hello world",+ },+ {+ name: "literal block scalar keeps newlines",+ content: "---\nname: foo\ndescription: |\n line1\n line2\n---\nbody",+ wantName: "foo",+ wantDesc: "line1\nline2\n",+ },+ {+ name: "literal strip chomping drops trailing newline",+ content: "---\nname: foo\ndescription: |-\n line1\n line2\n---\nbody",+ wantName: "foo",+ wantDesc: "line1\nline2",+ },+ {+ name: "folded block scalar joins with spaces",+ content: "---\nname: foo\ndescription: >\n line1\n line2\n---\nbody",+ wantName: "foo",+ wantDesc: "line1 line2\n",+ },+ {+ name: "CRLF line endings",+ content: "---\r\nname: foo\r\ndescription: bar\r\n---\r\nbody",+ wantName: "foo",+ wantDesc: "bar",+ },+ {+ name: "no frontmatter returns empty",+ content: "no frontmatter here",+ wantName: "",+ wantDesc: "",+ },+ {+ name: "unterminated frontmatter returns empty",+ content: "---\nname: foo\ndescription: bar\n",+ wantName: "",+ wantDesc: "",+ },+ {+ name: "invalid YAML falls back to empty",+ content: "---\n: : : not valid\n---\nbody",+ wantName: "",+ wantDesc: "",+ },+ {+ // Reproduction for issue #3495: Chinese block scalar.+ name: "issue 3495 chinese literal block scalar",+ content: "---\n" ++ "name: requirements-workshop\n" ++ "description: |\n" ++ " 当用户想要开发新功能、讨论需求、梳理业务逻辑时触发。通过多轮对话将模糊的想法转化为结构化的需求文档,为后续技术方案设计提供输入。\n" ++ " 适用场景:用户说\"我想实现XX功能\"、\"讨论一下这个需求\"、\"帮我分析一下怎么做\"、\"这个需求该怎么设计\"、\"写个需求文档\"等。\n" ++ " 本skill只负责产出需求文档,不进入技术设计或代码实现阶段。\n" ++ "---\nbody",+ wantName: "requirements-workshop",+ wantDesc: "当用户想要开发新功能、讨论需求、梳理业务逻辑时触发。通过多轮对话将模糊的想法转化为结构化的需求文档,为后续技术方案设计提供输入。\n" ++ "适用场景:用户说\"我想实现XX功能\"、\"讨论一下这个需求\"、\"帮我分析一下怎么做\"、\"这个需求该怎么设计\"、\"写个需求文档\"等。\n" ++ "本skill只负责产出需求文档,不进入技术设计或代码实现阶段。\n",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ gotName, gotDesc := ParseFrontmatter(tt.content)+ if gotName != tt.wantName {+ t.Errorf("name: got %q, want %q", gotName, tt.wantName)+ }+ if gotDesc != tt.wantDesc {+ t.Errorf("description: got %q, want %q", gotDesc, tt.wantDesc)+ }+ })+ }+}