-
Notifications
You must be signed in to change notification settings - Fork 200
Expand file tree
/
Copy pathcli.ts
More file actions
858 lines (727 loc) · 28.9 KB
/
Copy pathcli.ts
File metadata and controls
858 lines (727 loc) · 28.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
#!/usr/bin/env node
/**
* Frontmatter Spec Validator
*
* Validates SKILL.md frontmatter against agentskills.io specification rules:
* 1. Name must be lowercase alphanumeric + hyphens, no consecutive hyphens,
* no start/end hyphen, length 1–64, and must match the parent directory.
* 2. Description must use inline double-quoted strings — not >- folded
* scalars or | literal blocks (incompatible with skills.sh).
* 3. Frontmatter must not contain XML tags (< or >) — security risk since
* frontmatter appears in the system prompt.
* 4. Name must not start with reserved prefixes (claude- or anthropic-).
*
* Usage:
* npm run frontmatter # Validate all skills
* npm run frontmatter <skill> # Validate a single skill
* npm run frontmatter <path/SKILL.md> # Validate a specific file
*/
import { dirname, resolve, basename, relative } from "node:path";
import { fileURLToPath } from "node:url";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { parseArgs } from "node:util";
import { parseSkillContent } from "../shared/skill-helper.js";
// ── Paths ────────────────────────────────────────────────────────────────────
function getRepoRoot(): string {
const scriptDir = dirname(fileURLToPath(import.meta.url));
return resolve(scriptDir, "../../..");
}
const REPO_ROOT = getRepoRoot();
const PLUGIN_SKILLS_DIR = resolve(REPO_ROOT, "plugin", "skills");
const META_SKILLS_DIR = resolve(REPO_ROOT, ".github", "skills");
// ── Types ────────────────────────────────────────────────────────────────────
export interface ValidationIssue {
check: string; // Check identifier (e.g., "name-format", "description-format")
message: string; // Human-readable explanation
severity?: "error" | "warning"; // Defaults to "error" if omitted
}
export interface ValidationResult {
skill: string;
file: string;
issues: ValidationIssue[];
}
export interface SkillRoutingContext {
name: string;
file: string;
description: string;
triggerPhrases: string[];
broad: boolean;
}
// ── Validation checks ────────────────────────────────────────────────────────
const NAME_RE = /^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/;
const RESERVED_PREFIXES = ["claude-", "anthropic-"];
/**
* Check 1: Validate the `name` field per the agentskills.io spec.
*
* Rules:
* - Lowercase alphanumeric + hyphens only
* - No consecutive hyphens (--)
* - Must not start or end with a hyphen
* - Length 1–64
* - Must match the parent directory name
*/
export function validateName(name: string | null, parentDirName: string): ValidationIssue[] {
const issues: ValidationIssue[] = [];
if (name === null || name === "") {
issues.push({ check: "name-format", message: "Missing required 'name' field" });
return issues;
}
if (name.length > 64) {
issues.push({ check: "name-format", message: `Name is ${name.length} chars (max 64)` });
}
if (!NAME_RE.test(name)) {
if (/[A-Z]/.test(name)) {
issues.push({ check: "name-format", message: `Name contains uppercase characters: ${name}` });
} else if (/[^a-z0-9-]/.test(name)) {
issues.push({ check: "name-format", message: `Name contains invalid characters (only a-z, 0-9, - allowed): ${name}` });
} else if (name.startsWith("-") || name.endsWith("-")) {
issues.push({ check: "name-format", message: `Name must not start or end with a hyphen: ${name}` });
} else {
issues.push({ check: "name-format", message: `Name does not match spec pattern: ${name}` });
}
}
if (name.includes("--")) {
issues.push({ check: "name-format", message: `Name contains consecutive hyphens (--): ${name}` });
}
if (name !== parentDirName) {
issues.push({ check: "name-format", message: `Name "${name}" does not match parent directory "${parentDirName}"` });
}
return issues;
}
/**
* Check 2: Validate the description uses inline double-quoted format.
*
* Rejects >- folded scalars and | literal blocks which are incompatible
* with skills.sh.
*/
export function validateDescriptionFormat(rawFrontmatter: string): ValidationIssue[] {
const issues: ValidationIssue[] = [];
// Match description field followed by a block scalar indicator
if (/^description:\s*>-?\s*$/m.test(rawFrontmatter)) {
issues.push({
check: "description-format",
message: "Description uses >- folded scalar (incompatible with skills.sh) — use inline double-quoted string instead",
});
}
if (/^description:\s*\|\s*$/m.test(rawFrontmatter)) {
issues.push({
check: "description-format",
message: "Description uses | literal block (preserves newlines) — use inline double-quoted string instead",
});
}
if (/^description:\s*\|-\s*$/m.test(rawFrontmatter)) {
issues.push({
check: "description-format",
message: "Description uses |- literal block (strip) — use inline double-quoted string instead",
});
}
return issues;
}
/**
* Check 3: Validate no XML tags (< or >) in frontmatter.
*
* Frontmatter appears in the system prompt — XML tags are a security risk
* (injection vector).
*/
export function validateNoXmlTags(rawFrontmatter: string): ValidationIssue[] {
const issues: ValidationIssue[] = [];
const lines = rawFrontmatter.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Look for < or > that appear to be tags (not comparison operators or arrows)
if (/<[a-zA-Z/!]/.test(line) || />[^-]/.test(line) && /</.test(line)) {
issues.push({
check: "no-xml-tags",
message: `Frontmatter contains XML-like tags on line ${i + 1}: ${line.trim().substring(0, 80)}`,
});
}
}
return issues;
}
/**
* Check 4: Validate the name does not start with reserved prefixes.
*
* Anthropic reserves claude- and anthropic- prefixes.
*/
export function validateNoReservedPrefix(name: string | null): ValidationIssue[] {
const issues: ValidationIssue[] = [];
if (name === null) return issues;
for (const prefix of RESERVED_PREFIXES) {
if (name.startsWith(prefix)) {
issues.push({
check: "reserved-prefix",
message: `Name starts with reserved prefix "${prefix}": ${name}`,
});
}
}
return issues;
}
/**
* Check 5: Validate description length (max 1024 chars per agentskills.io spec).
*/
export function validateDescriptionLength(description: string | null): ValidationIssue[] {
const issues: ValidationIssue[] = [];
if (description === null || description === "") {
return issues; // Missing description is caught by missing-field check
}
if (description.length > 1024) {
issues.push({
check: "description-length",
message: `Description is ${description.length} chars (max 1024)`,
});
}
return issues;
}
const SEMVER_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
/**
* Check 6: Validate that `license` field is present and is a string.
*/
export function validateLicense(license: unknown): ValidationIssue[] {
const issues: ValidationIssue[] = [];
if (license === undefined || license === null || license === "") {
issues.push({
check: "license",
message: "Missing 'license' field in frontmatter",
severity: "warning",
});
} else if (typeof license !== "string") {
issues.push({
check: "license",
message: `'license' field must be a string, got ${typeof license}`,
});
}
return issues;
}
/**
* Check 7: Validate `metadata` field structure (optional, map of string keys to string values per spec).
*/
export function validateMetadata(metadata: unknown): ValidationIssue[] {
const issues: ValidationIssue[] = [];
if (metadata === undefined || metadata === null) {
issues.push({
check: "metadata",
message: "Missing 'metadata' block in frontmatter",
severity: "warning",
});
return issues;
}
if (typeof metadata !== "object" || Array.isArray(metadata)) {
issues.push({
check: "metadata",
message: `'metadata' field must be a key-value mapping, got ${Array.isArray(metadata) ? "array" : typeof metadata}`,
});
return issues;
}
const meta = metadata as Record<string, unknown>;
for (const [key, value] of Object.entries(meta)) {
if (typeof value !== "string") {
issues.push({
check: "metadata",
message: `metadata.${key} must be a string, got ${typeof value}`,
severity: "warning",
});
}
}
return issues;
}
/**
* Check 8: Validate `metadata.version` is present and follows semver (X.Y.Z).
*/
export function validateMetadataVersion(metadata: unknown): ValidationIssue[] {
const issues: ValidationIssue[] = [];
if (metadata === undefined || metadata === null || typeof metadata !== "object") {
issues.push({
check: "metadata-version",
message: "Missing 'metadata' block with 'version' field in frontmatter",
severity: "warning",
});
return issues;
}
const meta = metadata as Record<string, unknown>;
const version = meta.version;
if (version === undefined || version === null || version === "") {
issues.push({
check: "metadata-version",
message: "Missing 'version' in metadata block",
severity: "warning",
});
return issues;
}
const versionStr = String(version);
if (!SEMVER_RE.test(versionStr)) {
issues.push({
check: "metadata-version",
message: `metadata.version "${versionStr}" is not valid semver (expected X.Y.Z)`,
});
}
return issues;
}
/**
* Check 8: Validate `compatibility` field (optional, max 500 chars per spec).
*/
export function validateCompatibility(compatibility: unknown): ValidationIssue[] {
const issues: ValidationIssue[] = [];
if (compatibility === undefined || compatibility === null) {
return issues; // Optional field
}
if (typeof compatibility !== "string") {
issues.push({
check: "compatibility",
message: `'compatibility' field must be a string, got ${typeof compatibility}`,
});
return issues;
}
if (compatibility === "") {
issues.push({
check: "compatibility",
message: "'compatibility' field must not be empty if provided",
});
return issues;
}
if (compatibility.length > 500) {
issues.push({
check: "compatibility",
message: `Compatibility is ${compatibility.length} chars (max 500)`,
});
}
return issues;
}
/**
* Check 9: Validate `allowed-tools` field (optional, space-delimited string per spec).
*/
export function validateAllowedTools(allowedTools: unknown): ValidationIssue[] {
const issues: ValidationIssue[] = [];
if (allowedTools === undefined || allowedTools === null) {
return issues; // Optional field
}
if (typeof allowedTools !== "string") {
issues.push({
check: "allowed-tools",
message: `'allowed-tools' field must be a string, got ${typeof allowedTools}`,
});
return issues;
}
if (allowedTools === "") {
issues.push({
check: "allowed-tools",
message: "'allowed-tools' field must not be empty if provided",
});
}
return issues;
}
const TRIGGER_SECTION_KEYWORDS = ["WHEN", "USE FOR", "TRIGGERS"] as const;
const TRIGGER_SECTION_STOP_HEADERS = ["DO NOT USE FOR", ...TRIGGER_SECTION_KEYWORDS] as const;
// Extracts only explicit trigger sections and stops before disambiguation/next trigger section.
// Section headers must include a trailing colon; `PREFER OVER` is handled separately
// because it may appear without one.
const TRIGGER_SECTION_RE = new RegExp(
`\\b(?:${TRIGGER_SECTION_KEYWORDS.join("|")}):\\s*([^]*?)(?=(?:\\b(?:${TRIGGER_SECTION_STOP_HEADERS.join("|")}):|\\bPREFER OVER\\b|$))`,
"gi",
);
const DO_NOT_USE_FOR_RE = /\bDO NOT USE FOR:/i;
const SANITIZED_DO_NOT_USE_FOR_MARKER = "DO_NOT_USE_FOR:";
const DISAMBIGUATION_CLAUSE_MARKER_RE = new RegExp(`(?:${SANITIZED_DO_NOT_USE_FOR_MARKER}|PREFER OVER\\b)`, "i");
const PREFER_OVER_RE = /\bPREFER OVER\b/i;
const BROAD_SKILL_NAMES = new Set(["azure-prepare", "azure-deploy"]);
const MIN_TRIGGER_PHRASE_LENGTH = 4;
const OVERLAP_PREVIEW_LIMIT = 3;
const DEFAULT_REMOTE_BASE_REF = "origin/main";
function normalizeTriggerPhrase(phrase: string): string {
return phrase
.toLowerCase()
.replace(/^["'`]+|["'`]+$/g, "")
.replace(/\([^)]*\)/g, "")
.replace(/[^a-z0-9]+/g, " ")
.trim();
}
export function extractTriggerPhrases(description: string | null): string[] {
if (!description) return [];
// Prevent `USE FOR:` inside `DO NOT USE FOR:` from being treated as a trigger section.
const sanitizedDescription = description.replace(/\bDO NOT USE FOR:/gi, SANITIZED_DO_NOT_USE_FOR_MARKER);
const phrases: string[] = [];
let match: RegExpExecArray | null;
while ((match = TRIGGER_SECTION_RE.exec(sanitizedDescription)) !== null) {
const section = match[1];
const disambiguationStart = section.search(DISAMBIGUATION_CLAUSE_MARKER_RE);
const triggerSection = disambiguationStart >= 0 ? section.slice(0, disambiguationStart) : section;
for (const rawPhrase of triggerSection.split(/[;,]/)) {
const normalized = normalizeTriggerPhrase(rawPhrase);
if (normalized.length >= MIN_TRIGGER_PHRASE_LENGTH) {
phrases.push(normalized);
}
}
}
return [...new Set(phrases)];
}
export function hasDoNotUseForClause(description: string | null): boolean {
if (!description) return false;
return DO_NOT_USE_FOR_RE.test(description);
}
export function hasPreferOverClause(description: string | null, competingSkillName: string): boolean {
if (!description) return false;
const escapedName = competingSkillName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return new RegExp(`\\bPREFER OVER\\s+${escapedName}\\b`, "i").test(description);
}
function hasAnyPreferOverClause(description: string | null): boolean {
if (!description) return false;
return PREFER_OVER_RE.test(description);
}
function hasAnyDisambiguationClause(description: string | null, competingSkillName: string): boolean {
return hasDoNotUseForClause(description) || hasPreferOverClause(description, competingSkillName);
}
function buildSkillRoutingContexts(skillFiles: string[]): SkillRoutingContext[] {
const contexts: SkillRoutingContext[] = [];
for (const file of skillFiles) {
const content = readFileSync(file, "utf-8");
const parsed = parseSkillContent(content);
if (parsed === null) continue;
const name = typeof parsed.data.name === "string" ? parsed.data.name : basename(dirname(file));
const description = typeof parsed.data.description === "string" ? parsed.data.description : "";
const triggerPhrases = extractTriggerPhrases(description);
contexts.push({
name,
file,
description,
triggerPhrases,
broad: isBroadRoutingSkill(name),
});
}
return contexts;
}
function isBroadRoutingSkill(name: string): boolean {
// Restrict "broad" classification to an explicit allowlist to avoid
// specialized skills being accidentally reclassified as broad.
return BROAD_SKILL_NAMES.has(name);
}
function getMergeBaseRef(): string | null {
// Prefer merge-base with common default branches first (remote then local), then
// fall back to HEAD~1 for environments where base branches are unavailable.
const baseRefCandidates = [DEFAULT_REMOTE_BASE_REF, "origin/master", "main", "master"];
for (const baseRef of baseRefCandidates) {
try {
return execFileSync("git", ["merge-base", "HEAD", baseRef], {
cwd: REPO_ROOT,
encoding: "utf-8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
} catch {
// Try next candidate base ref.
}
}
try {
return execFileSync("git", ["rev-parse", "HEAD~1"], {
cwd: REPO_ROOT,
encoding: "utf-8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
} catch {
return null;
}
}
function getDescriptionFromGitRef(filePath: string, ref: string): string | null {
const relativeFilePath = relative(REPO_ROOT, filePath).replace(/\\/g, "/");
try {
const previousContent = execFileSync("git", ["show", `${ref}:${relativeFilePath}`], {
cwd: REPO_ROOT,
encoding: "utf-8",
stdio: ["ignore", "pipe", "ignore"],
});
const parsed = parseSkillContent(previousContent);
if (parsed === null || typeof parsed.data.description !== "string") {
return null;
}
return parsed.data.description;
} catch {
return null;
}
}
export function validateTriggerOverlapDisambiguation(
skill: SkillRoutingContext,
allSkills: SkillRoutingContext[],
): ValidationIssue[] {
if (skill.broad || skill.triggerPhrases.length === 0) return [];
const issues: ValidationIssue[] = [];
const skillTriggerSet = new Set(skill.triggerPhrases);
for (const competitor of allSkills) {
if (competitor.name === skill.name || !competitor.broad) continue;
if (competitor.triggerPhrases.length === 0) continue;
const overlaps = competitor.triggerPhrases.filter(
(trigger) => skillTriggerSet.has(trigger),
);
if (overlaps.length === 0) continue;
if (!hasAnyDisambiguationClause(skill.description, competitor.name)) {
const overlapPreview = overlaps.slice(0, OVERLAP_PREVIEW_LIMIT).join(", ");
const overlapSuffix = overlaps.length > OVERLAP_PREVIEW_LIMIT ? ", ..." : "";
issues.push({
check: "trigger-overlap-disambiguation",
severity: "error",
message: `Trigger overlap with broad skill "${competitor.name}" (${overlapPreview}${overlapSuffix}). Add DO NOT USE FOR: or PREFER OVER ${competitor.name}.`,
});
}
}
return issues;
}
function validateDisambiguationRemoval(skill: SkillRoutingContext, mergeBaseRef: string | null): ValidationIssue[] {
if (mergeBaseRef === null) return [];
const previousDescription = getDescriptionFromGitRef(skill.file, mergeBaseRef);
return buildDisambiguationRemovalIssues(previousDescription, skill.description);
}
export function isDisambiguationClauseRemoved(previousDescription: string | null, currentDescription: string | null): boolean {
const previousHasDisambiguation = hasDoNotUseForClause(previousDescription) || hasAnyPreferOverClause(previousDescription);
const currentHasDisambiguation = hasDoNotUseForClause(currentDescription) || hasAnyPreferOverClause(currentDescription);
return previousHasDisambiguation && !currentHasDisambiguation;
}
function getRemovedDisambiguationClauses(previousDescription: string | null, currentDescription: string | null): string[] {
const removed: string[] = [];
if (hasDoNotUseForClause(previousDescription) && !hasDoNotUseForClause(currentDescription)) {
removed.push("DO NOT USE FOR");
}
if (hasAnyPreferOverClause(previousDescription) && !hasAnyPreferOverClause(currentDescription)) {
removed.push("PREFER OVER");
}
return removed;
}
export function buildDisambiguationRemovalIssues(
previousDescription: string | null,
currentDescription: string | null,
): ValidationIssue[] {
if (previousDescription === null) return [];
if (!isDisambiguationClauseRemoved(previousDescription, currentDescription)) return [];
const removedClauses = getRemovedDisambiguationClauses(previousDescription, currentDescription);
const clauseLabel = removedClauses.length === 1 ? removedClauses[0] : removedClauses.join(" and ");
const clauseWord = removedClauses.length === 1 ? "clause" : "clauses";
return [{
check: "disambiguation-removal",
severity: "error",
message: `Removed disambiguation ${clauseWord}: ${clauseLabel}. Re-add a DO NOT USE FOR or PREFER OVER clause if trigger overlap still exists.`,
}];
}
// ── Validate a single SKILL.md ──────────────────────────────────────────────
export function validateSkillFile(filePath: string): ValidationResult {
const parentDir = basename(dirname(filePath));
const content = readFileSync(filePath, "utf-8");
const parsed = parseSkillContent(content);
const issues: ValidationIssue[] = [];
if (parsed === null) {
issues.push({ check: "frontmatter", message: "Missing YAML frontmatter (file must start with ---)" });
return { skill: parentDir, file: filePath, issues };
}
const name = typeof parsed.data.name === "string" ? parsed.data.name : null;
const description = typeof parsed.data.description === "string" ? parsed.data.description : null;
// Check required fields
if (description === null) {
issues.push({ check: "missing-field", message: "Missing required 'description' field" });
}
// Check 1: Name validation
issues.push(...validateName(name, parentDir));
// Check 2: Description format (needs raw YAML source)
issues.push(...validateDescriptionFormat(parsed.raw));
// Check 3: No XML tags (needs raw YAML source)
issues.push(...validateNoXmlTags(parsed.raw));
// Check 4: No reserved prefixes
issues.push(...validateNoReservedPrefix(name));
// Check 5: Description length
issues.push(...validateDescriptionLength(description));
// Check 6: License field
issues.push(...validateLicense(parsed.data.license));
// Check 7: Metadata structure
issues.push(...validateMetadata(parsed.data.metadata));
// Check 8: metadata.version (semver)
issues.push(...validateMetadataVersion(parsed.data.metadata));
// Check 9: Compatibility field
issues.push(...validateCompatibility(parsed.data.compatibility));
// Check 10: Allowed tools field
issues.push(...validateAllowedTools(parsed.data["allowed-tools"]));
return { skill: parentDir, file: filePath, issues };
}
// ── Skill discovery ──────────────────────────────────────────────────────────
function findSkillFiles(skillsDir: string): string[] {
if (!existsSync(skillsDir)) return [];
return readdirSync(skillsDir)
.filter((name) => {
const full = resolve(skillsDir, name);
if (!statSync(full).isDirectory()) return false;
return existsSync(resolve(full, "SKILL.md"));
})
.sort()
.map((name) => resolve(skillsDir, name, "SKILL.md"));
}
function getAllSkillFiles(): string[] {
return [...findSkillFiles(PLUGIN_SKILLS_DIR), ...findSkillFiles(META_SKILLS_DIR)];
}
// ── JSON output ──────────────────────────────────────────────────────────────
/** All check identifiers produced by the validator */
const ALL_CHECKS = [
"frontmatter",
"name-format",
"missing-field",
"description-format",
"no-xml-tags",
"reserved-prefix",
"description-length",
"license",
"metadata",
"metadata-version",
"compatibility",
"allowed-tools",
"trigger-overlap-disambiguation",
"disambiguation-removal",
] as const;
export interface FrontmatterSkillResult {
name: string;
path: string;
status: "pass" | "fail" | "warn";
errors: string[];
warnings: string[];
checks: Record<string, boolean>;
}
export interface FrontmatterJsonResult {
skills: FrontmatterSkillResult[];
summary: {
total: number;
passed: number;
failed: number;
warnings: number;
};
}
function buildJsonResult(results: ValidationResult[]): FrontmatterJsonResult {
const skills: FrontmatterSkillResult[] = [];
let passed = 0;
let failed = 0;
let warningCount = 0;
for (const result of results) {
const errors = result.issues.filter(i => i.severity !== "warning");
const warnings = result.issues.filter(i => i.severity === "warning");
// Build checks map: true = passed, false = has issue for that check
const failedChecks = new Set(result.issues.map(i => i.check));
const checks: Record<string, boolean> = {};
for (const check of ALL_CHECKS) {
checks[check] = !failedChecks.has(check);
}
let status: "pass" | "fail" | "warn";
if (errors.length > 0) {
status = "fail";
failed++;
} else if (warnings.length > 0) {
status = "warn";
warningCount++;
} else {
status = "pass";
passed++;
}
skills.push({
name: result.skill,
path: relative(REPO_ROOT, result.file).replace(/\\/g, "/"),
status,
errors: errors.map(e => `[${e.check}] ${e.message}`),
warnings: warnings.map(w => `[${w.check}] ${w.message}`),
checks,
});
}
return {
skills,
summary: {
total: results.length,
passed,
failed,
warnings: warningCount,
},
};
}
// ── CLI entry point ──────────────────────────────────────────────────────────
function main(): void {
const { values, positionals } = parseArgs({
args: process.argv.slice(2),
options: {
json: { type: "boolean", default: false },
},
strict: false,
allowPositionals: true,
});
const jsonOutput = values.json ?? false;
let skillFiles: string[];
if (positionals.length > 0) {
skillFiles = [];
for (const arg of positionals) {
// Accept either a skill name or a direct path to SKILL.md
if (arg.endsWith("SKILL.md") && existsSync(arg)) {
skillFiles.push(resolve(arg));
} else {
// Try as skill name in both directories
const pluginPath = resolve(PLUGIN_SKILLS_DIR, arg, "SKILL.md");
const metaPath = resolve(META_SKILLS_DIR, arg, "SKILL.md");
if (existsSync(pluginPath)) {
skillFiles.push(pluginPath);
} else if (existsSync(metaPath)) {
skillFiles.push(metaPath);
} else {
console.error(`\n❌ Skill "${arg}" not found in plugin/skills/ or .github/skills/\n`);
process.exitCode = 1;
return;
}
}
}
} else {
skillFiles = getAllSkillFiles();
}
// Validate all skill files
const results: ValidationResult[] = [];
const routingContexts = buildSkillRoutingContexts(getAllSkillFiles());
const routingContextByName = new Map(routingContexts.map((context) => [context.name, context]));
const mergeBaseRef = getMergeBaseRef();
for (const file of skillFiles) {
const result = validateSkillFile(file);
const routingContext = routingContextByName.get(result.skill);
if (routingContext) {
result.issues.push(...validateTriggerOverlapDisambiguation(routingContext, routingContexts));
result.issues.push(...validateDisambiguationRemoval(routingContext, mergeBaseRef));
}
results.push(result);
}
// ── JSON output mode ────────────────────────────────────────────────────
if (jsonOutput) {
const jsonResult = buildJsonResult(results);
console.log(JSON.stringify(jsonResult, null, 2));
const hasErrors = results.some(r => r.issues.some(i => i.severity !== "warning"));
if (hasErrors) {
process.exitCode = 1;
}
return;
}
// ── Console output mode (default) ───────────────────────────────────────
console.log("\n📋 Frontmatter Spec Validator\n");
console.log("────────────────────────────────────────────────────────────");
let totalErrors = 0;
let totalWarnings = 0;
let skillsWithIssues = 0;
for (const result of results) {
const errors = result.issues.filter(i => i.severity !== "warning");
const warnings = result.issues.filter(i => i.severity === "warning");
if (result.issues.length === 0) {
console.log(` ✅ ${result.skill}`);
} else {
if (errors.length > 0) skillsWithIssues++;
totalErrors += errors.length;
totalWarnings += warnings.length;
const icon = errors.length > 0 ? "❌" : "⚠️";
console.log(` ${icon} ${result.skill} — ${errors.length} error(s), ${warnings.length} warning(s)`);
for (const issue of errors) {
console.log(` ❌ [${issue.check}] ${issue.message}`);
}
for (const issue of warnings) {
console.log(` ⚠️ [${issue.check}] ${issue.message}`);
}
}
}
console.log("\n────────────────────────────────────────────────────────────");
if (totalErrors === 0 && totalWarnings === 0) {
console.log(`\n✅ All ${skillFiles.length} skill(s) passed frontmatter validation.\n`);
} else if (totalErrors === 0) {
console.log(`\n✅ All ${skillFiles.length} skill(s) passed with ${totalWarnings} warning(s).\n`);
} else {
console.log(`\n❌ ${totalErrors} error(s) and ${totalWarnings} warning(s) found in ${skillsWithIssues} skill(s).\n`);
process.exitCode = 1;
}
}
main();