validate-frontmatter.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. #!/usr/bin/env bun
  2. /**
  3. * Validates YAML frontmatter in agent, skill, and command .md files.
  4. *
  5. * Usage:
  6. * bun validate-frontmatter.ts # scan current directory
  7. * bun validate-frontmatter.ts /path/to/dir # scan specific directory
  8. * bun validate-frontmatter.ts file1.md file2.md # validate specific files
  9. */
  10. import { parse as parseYaml } from "yaml";
  11. import { readdir, readFile } from "fs/promises";
  12. import { basename, join, relative, resolve } from "path";
  13. // Characters that require quoting in YAML values when unquoted:
  14. // {} [] flow indicators, * anchor/alias, & anchor, # comment,
  15. // ! tag, | > block scalars, % directive, @ ` reserved
  16. const YAML_SPECIAL_CHARS = /[{}[\]*&#!|>%@`]/;
  17. const FRONTMATTER_REGEX = /^---\s*\n([\s\S]*?)---\s*\n?/;
  18. /**
  19. * Pre-process frontmatter text to quote values containing special YAML
  20. * characters. This allows glob patterns like **\/*.{ts,tsx} to parse.
  21. */
  22. function quoteSpecialValues(text: string): string {
  23. const lines = text.split("\n");
  24. const result: string[] = [];
  25. for (const line of lines) {
  26. const match = line.match(/^([a-zA-Z_-]+):\s+(.+)$/);
  27. if (match) {
  28. const [, key, value] = match;
  29. if (!key || !value) {
  30. result.push(line);
  31. continue;
  32. }
  33. // Skip already-quoted values
  34. if (
  35. (value.startsWith('"') && value.endsWith('"')) ||
  36. (value.startsWith("'") && value.endsWith("'"))
  37. ) {
  38. result.push(line);
  39. continue;
  40. }
  41. if (YAML_SPECIAL_CHARS.test(value)) {
  42. const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
  43. result.push(`${key}: "${escaped}"`);
  44. continue;
  45. }
  46. }
  47. result.push(line);
  48. }
  49. return result.join("\n");
  50. }
  51. interface ParseResult {
  52. frontmatter: Record<string, unknown>;
  53. content: string;
  54. error?: string;
  55. }
  56. function parseFrontmatter(markdown: string): ParseResult {
  57. const match = markdown.match(FRONTMATTER_REGEX);
  58. if (!match) {
  59. return {
  60. frontmatter: {},
  61. content: markdown,
  62. error: "No frontmatter found",
  63. };
  64. }
  65. const frontmatterText = quoteSpecialValues(match[1] || "");
  66. const content = markdown.slice(match[0].length);
  67. try {
  68. const parsed = parseYaml(frontmatterText);
  69. if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
  70. return { frontmatter: parsed as Record<string, unknown>, content };
  71. }
  72. return {
  73. frontmatter: {},
  74. content,
  75. error: `YAML parsed but result is not an object (got ${typeof parsed}${Array.isArray(parsed) ? " array" : ""})`,
  76. };
  77. } catch (err) {
  78. return {
  79. frontmatter: {},
  80. content,
  81. error: `YAML parse failed: ${err instanceof Error ? err.message : err}`,
  82. };
  83. }
  84. }
  85. // --- Validation ---
  86. type FileType = "agent" | "skill" | "command";
  87. interface ValidationIssue {
  88. level: "error" | "warning";
  89. message: string;
  90. }
  91. function validateAgent(
  92. frontmatter: Record<string, unknown>
  93. ): ValidationIssue[] {
  94. const issues: ValidationIssue[] = [];
  95. if (!frontmatter["name"] || typeof frontmatter["name"] !== "string") {
  96. issues.push({ level: "error", message: 'Missing required "name" field' });
  97. }
  98. if (
  99. !frontmatter["description"] ||
  100. typeof frontmatter["description"] !== "string"
  101. ) {
  102. issues.push({
  103. level: "error",
  104. message: 'Missing required "description" field',
  105. });
  106. }
  107. return issues;
  108. }
  109. function validateSkill(
  110. frontmatter: Record<string, unknown>
  111. ): ValidationIssue[] {
  112. const issues: ValidationIssue[] = [];
  113. if (!frontmatter["description"] && !frontmatter["when_to_use"]) {
  114. issues.push({
  115. level: "error",
  116. message: 'Missing required "description" field',
  117. });
  118. }
  119. return issues;
  120. }
  121. function validateCommand(
  122. frontmatter: Record<string, unknown>
  123. ): ValidationIssue[] {
  124. const issues: ValidationIssue[] = [];
  125. if (
  126. !frontmatter["description"] ||
  127. typeof frontmatter["description"] !== "string"
  128. ) {
  129. issues.push({
  130. level: "error",
  131. message: 'Missing required "description" field',
  132. });
  133. }
  134. return issues;
  135. }
  136. // --- File type detection ---
  137. function detectFileType(filePath: string): FileType | null {
  138. // Only match agents/ and commands/ at the plugin root level, not nested
  139. // inside skill content (e.g. plugins/foo/skills/bar/agents/ is skill content,
  140. // not an agent definition).
  141. const inSkillContent = /\/skills\/[^/]+\//.test(filePath);
  142. if (filePath.includes("/agents/") && !inSkillContent) return "agent";
  143. if (filePath.includes("/skills/") && basename(filePath) === "SKILL.md")
  144. return "skill";
  145. if (filePath.includes("/commands/") && !inSkillContent) return "command";
  146. return null;
  147. }
  148. // --- File discovery ---
  149. async function findMdFiles(
  150. baseDir: string
  151. ): Promise<{ path: string; type: FileType }[]> {
  152. const results: { path: string; type: FileType }[] = [];
  153. async function walk(dir: string) {
  154. const entries = await readdir(dir, { withFileTypes: true });
  155. for (const entry of entries) {
  156. const fullPath = join(dir, entry.name);
  157. if (entry.isDirectory()) {
  158. await walk(fullPath);
  159. } else if (entry.name.endsWith(".md")) {
  160. const type = detectFileType(fullPath);
  161. if (type) {
  162. results.push({ path: fullPath, type });
  163. }
  164. }
  165. }
  166. }
  167. await walk(baseDir);
  168. return results;
  169. }
  170. // --- Main ---
  171. async function main() {
  172. const args = process.argv.slice(2);
  173. let files: { path: string; type: FileType }[];
  174. let baseDir: string;
  175. if (args.length > 0 && args.every((a) => a.endsWith(".md"))) {
  176. baseDir = process.cwd();
  177. files = [];
  178. for (const arg of args) {
  179. const fullPath = resolve(arg);
  180. const type = detectFileType(fullPath);
  181. if (type) {
  182. files.push({ path: fullPath, type });
  183. }
  184. }
  185. } else {
  186. baseDir = args[0] || process.cwd();
  187. files = await findMdFiles(baseDir);
  188. }
  189. let totalErrors = 0;
  190. let totalWarnings = 0;
  191. console.log(`Validating ${files.length} frontmatter files...\n`);
  192. for (const { path: filePath, type } of files) {
  193. const rel = relative(baseDir, filePath);
  194. const content = await readFile(filePath, "utf-8");
  195. const result = parseFrontmatter(content);
  196. const issues: ValidationIssue[] = [];
  197. if (result.error) {
  198. issues.push({ level: "error", message: result.error });
  199. }
  200. if (!result.error) {
  201. switch (type) {
  202. case "agent":
  203. issues.push(...validateAgent(result.frontmatter));
  204. break;
  205. case "skill":
  206. issues.push(...validateSkill(result.frontmatter));
  207. break;
  208. case "command":
  209. issues.push(...validateCommand(result.frontmatter));
  210. break;
  211. }
  212. }
  213. if (issues.length > 0) {
  214. console.log(`${rel} (${type})`);
  215. for (const issue of issues) {
  216. const prefix = issue.level === "error" ? " ERROR" : " WARN ";
  217. console.log(`${prefix}: ${issue.message}`);
  218. if (issue.level === "error") totalErrors++;
  219. else totalWarnings++;
  220. }
  221. console.log();
  222. }
  223. }
  224. console.log("---");
  225. console.log(
  226. `Validated ${files.length} files: ${totalErrors} errors, ${totalWarnings} warnings`
  227. );
  228. if (totalErrors > 0) {
  229. process.exit(1);
  230. }
  231. }
  232. main().catch((err) => {
  233. console.error("Fatal error:", err);
  234. process.exit(2);
  235. });