forked from zocomputer/skills
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
1877 lines (1745 loc) · 55.8 KB
/
index.ts
File metadata and controls
1877 lines (1745 loc) · 55.8 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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
cp,
mkdtemp,
mkdir,
readFile,
readdir,
rename,
rm,
stat,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import matter from "gray-matter";
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
type Issue = {
skillPath: string;
message: string;
level: "error" | "warning";
};
const ROOT_DIR = process.cwd();
const INSTALL_AGENT = "codex";
const ZO_DIR = "Zo";
const EXTERNAL_DIR = "External";
const OFFICIAL_DIR = "Official";
const CONNECTIONS_DIR = "Connections";
const OFFICIAL_CATEGORIES = new Set([OFFICIAL_DIR, CONNECTIONS_DIR]);
const OFFICIAL_PREFIX = "zo-";
// Skip non-skill dirs and any gitignored folders during validation.
const NON_SKILL_DIRS = new Set([
".git",
".github",
".agents",
".codex",
".clawdhub",
".skills",
"node_modules",
]);
const ALLOWED_SKILL_DIRS = new Set(["assets", "references", "scripts"]);
const NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
const toDisplayPath = (fullPath: string) => path.relative(ROOT_DIR, fullPath);
const isDirectory = async (targetPath: string) => {
try {
return (await stat(targetPath)).isDirectory();
} catch {
return false;
}
};
const isGitIgnored = (targetPath: string) => {
const result = Bun.spawnSync(["git", "check-ignore", "-q", targetPath], {
stdout: "ignore",
stderr: "ignore",
});
return result.exitCode === 0;
};
const getCategoryDirs = async () => {
const categories: string[] = [];
const entries = await readdir(ROOT_DIR, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) {
continue;
}
if (NON_SKILL_DIRS.has(entry.name)) {
continue;
}
const fullPath = path.join(ROOT_DIR, entry.name);
if (isGitIgnored(fullPath)) {
continue;
}
categories.push(entry.name);
}
return categories;
};
const getCategorySet = async () => new Set(await getCategoryDirs());
const isSkillDirectory = async (targetPath: string) => {
try {
return (await stat(path.join(targetPath, "SKILL.md"))).isFile();
} catch {
return false;
}
};
const loadSkillDirectories = async () => {
const skillDirs: string[] = [];
const categories = await getCategoryDirs();
for (const category of categories) {
const groupPath = path.join(ROOT_DIR, category);
const entries = await readdir(groupPath, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) {
continue;
}
const fullPath = path.join(groupPath, entry.name);
if (isGitIgnored(fullPath)) {
continue;
}
if (await isSkillDirectory(fullPath)) {
skillDirs.push(fullPath);
}
}
}
// Backward-compatible: catch any skills still at repo root.
const rootEntries = await readdir(ROOT_DIR, { withFileTypes: true });
for (const entry of rootEntries) {
if (!entry.isDirectory()) {
continue;
}
if (NON_SKILL_DIRS.has(entry.name)) {
continue;
}
const fullPath = path.join(ROOT_DIR, entry.name);
if (isGitIgnored(fullPath)) {
continue;
}
if (await isSkillDirectory(fullPath)) {
skillDirs.push(fullPath);
}
}
return skillDirs;
};
// External sources live in external.yml (repository + optional skill + notice).
const EXTERNAL_CONFIG = path.join(ROOT_DIR, "external.yml");
type ExternalSkill = {
repository: string;
skill?: string;
notice?: string;
overrides?: Record<string, unknown>;
};
const parseExternalConfig = (content: string) => {
let parsed: unknown;
try {
parsed = parseYaml(content);
} catch {
return [];
}
if (!Array.isArray(parsed)) {
return [];
}
const sources: ExternalSkill[] = [];
for (const entry of parsed) {
if (!entry || typeof entry !== "object") {
continue;
}
const record = entry as Record<string, unknown>;
const repository = typeof record.repository === "string" ? record.repository.trim() : "";
if (!repository) {
continue;
}
const skill = typeof record.skill === "string" ? record.skill.trim() : undefined;
const notice = typeof record.notice === "string" ? record.notice : undefined;
const overrides: Record<string, unknown> = {};
for (const [key, value] of Object.entries(record)) {
if (key === "repository" || key === "skill" || key === "notice" || key === "name") {
continue;
}
overrides[key] = value;
}
const source: ExternalSkill = { repository };
if (skill) {
source.skill = skill;
}
if (notice) {
source.notice = notice;
}
if (Object.keys(overrides).length > 0) {
source.overrides = overrides;
}
sources.push(source);
}
return sources;
};
const countExternalMetadataFields = (entry: Record<string, unknown>) => {
let count = 0;
for (const key of Object.keys(entry)) {
if (key === "repository" || key === "skill") {
continue;
}
if (entry[key] !== undefined) {
count += 1;
}
}
return count;
};
const resolveRecordSlug = (entry: Record<string, unknown>) => {
const overrideSlug = typeof entry.slug === "string" ? entry.slug.trim() : "";
if (overrideSlug) {
return overrideSlug;
}
const skill = typeof entry.skill === "string" ? entry.skill.trim() : "";
if (skill) {
return skill;
}
const repository = typeof entry.repository === "string" ? entry.repository : "";
return repository.split("/").pop() ?? "";
};
const escapeTableValue = (value: string) => value.replace(/\|/g, "\\|");
const normalizeTableText = (value: string) => value.replace(/\s+/g, " ").trim();
const resolveSkillGroup = (
slug: string,
externalSlugs: Set<string>,
currentCategory: string,
defaultCategory: string,
) => {
if (externalSlugs.has(slug)) {
return EXTERNAL_DIR;
}
if (currentCategory) {
return currentCategory;
}
return defaultCategory;
};
const collectSkillDirectoriesForReorg = async () => {
const skillDirs = new Map<string, string>();
const rootEntries = await readdir(ROOT_DIR, { withFileTypes: true });
for (const entry of rootEntries) {
if (!entry.isDirectory()) {
continue;
}
if (NON_SKILL_DIRS.has(entry.name)) {
continue;
}
const fullPath = path.join(ROOT_DIR, entry.name);
if (isGitIgnored(fullPath)) {
continue;
}
if (await isSkillDirectory(fullPath)) {
skillDirs.set(entry.name, fullPath);
}
}
const categories = await getCategoryDirs();
for (const category of categories) {
const groupPath = path.join(ROOT_DIR, category);
if (!(await isDirectory(groupPath))) {
continue;
}
const entries = await readdir(groupPath, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) {
continue;
}
const fullPath = path.join(groupPath, entry.name);
if (isGitIgnored(fullPath)) {
continue;
}
if (await isSkillDirectory(fullPath)) {
skillDirs.set(entry.name, fullPath);
}
}
}
return skillDirs;
};
const reorganizeSkillDirectories = async (externalSlugs: Set<string>) => {
await mkdir(path.join(ROOT_DIR, EXTERNAL_DIR), { recursive: true });
const categoryDirs = await getCategoryDirs();
const sortedCategories = [...categoryDirs].sort((a, b) => a.localeCompare(b));
const nonExternalCategories = sortedCategories.filter((name) => name !== EXTERNAL_DIR);
const defaultCategory = nonExternalCategories.includes(ZO_DIR)
? ZO_DIR
: nonExternalCategories[0] ?? EXTERNAL_DIR;
const categorySet = await getCategorySet();
categorySet.add(EXTERNAL_DIR);
categorySet.add(ZO_DIR);
const skillDirs = await collectSkillDirectoriesForReorg();
let moved = 0;
for (const [slug, currentPath] of skillDirs.entries()) {
const currentCategory = path.basename(path.dirname(currentPath));
const group = resolveSkillGroup(
slug,
externalSlugs,
categorySet.has(currentCategory) ? currentCategory : "",
defaultCategory,
);
const targetPath = path.join(ROOT_DIR, group, slug);
if (path.resolve(currentPath) === path.resolve(targetPath)) {
continue;
}
try {
await mkdir(path.join(ROOT_DIR, group), { recursive: true });
await rm(targetPath, { recursive: true, force: true });
await rename(currentPath, targetPath);
moved += 1;
} catch {
console.log(`Unable to move ${slug} to ${group}.`);
}
}
return moved;
};
const ensureMetadataCategoryForAllSkills = async () => {
const categorySet = await getCategorySet();
const skillDirs = await loadSkillDirectories();
let updated = 0;
for (const skillDir of skillDirs) {
const skillFile = path.join(skillDir, "SKILL.md");
try {
const parsed = await readSkillFile(skillFile);
if (!parsed) {
continue;
}
const category = resolveCategoryFromSkillPath(skillFile, categorySet);
if (!category) {
continue;
}
const metadata = parsed.data.metadata;
const updatedMetadata =
metadata && typeof metadata === "object" ? { ...metadata } : {};
const current = (updatedMetadata as Record<string, unknown>).category;
if (current === category) {
continue;
}
(updatedMetadata as Record<string, unknown>).category = category;
parsed.data.metadata = updatedMetadata;
const updatedFile = serializeSkillFile(parsed.data, parsed.body);
await writeFile(skillFile, updatedFile);
updated += 1;
} catch {
console.log(`Unable to set metadata.category for ${skillDir}.`);
}
}
return updated;
};
const ensureOfficialSlugPrefixForAllSkills = async () => {
let moved = 0;
for (const category of OFFICIAL_CATEGORIES) {
const officialRoot = path.join(ROOT_DIR, category);
if (!(await isDirectory(officialRoot))) {
continue;
}
const entries = await readdir(officialRoot, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) {
continue;
}
const currentPath = path.join(officialRoot, entry.name);
if (isGitIgnored(currentPath)) {
continue;
}
if (!(await isSkillDirectory(currentPath))) {
continue;
}
if (entry.name.startsWith(OFFICIAL_PREFIX)) {
continue;
}
const targetSlug = `${OFFICIAL_PREFIX}${entry.name}`;
const targetPath = path.join(officialRoot, targetSlug);
try {
if (await isDirectory(targetPath)) {
console.log(
`Unable to rename ${entry.name} to ${targetSlug} (target exists).`,
);
continue;
}
await rename(currentPath, targetPath);
moved += 1;
} catch {
console.log(`Unable to rename ${entry.name} to ${targetSlug}.`);
}
}
}
return moved;
};
const ensureSkillNameSlugForAllSkills = async () => {
const skillDirs = await loadSkillDirectories();
let updated = 0;
for (const skillDir of skillDirs) {
const skillFile = path.join(skillDir, "SKILL.md");
const slug = path.basename(skillDir);
const parentCategory = path.basename(path.dirname(skillDir));
const expectedName =
OFFICIAL_CATEGORIES.has(parentCategory) && slug.startsWith(OFFICIAL_PREFIX)
? slug.slice(OFFICIAL_PREFIX.length)
: slug;
try {
const parsed = await readSkillFile(skillFile);
if (!parsed) {
continue;
}
const currentName = typeof parsed.data.name === "string" ? parsed.data.name : "";
if (!currentName || currentName === expectedName) {
if (!currentName) {
parsed.data.name = expectedName;
const updatedFile = serializeSkillFile(parsed.data, parsed.body);
await writeFile(skillFile, updatedFile);
updated += 1;
}
continue;
}
const metadata =
parsed.data.metadata && typeof parsed.data.metadata === "object"
? { ...(parsed.data.metadata as Record<string, unknown>) }
: {};
if (!("display-name" in metadata) || !metadata["display-name"]) {
metadata["display-name"] = currentName;
}
parsed.data.name = expectedName;
parsed.data.metadata = metadata;
const updatedFile = serializeSkillFile(parsed.data, parsed.body);
await writeFile(skillFile, updatedFile);
updated += 1;
} catch {
console.log(`Unable to normalize name for ${skillDir}.`);
}
}
return updated;
};
const resolveRecordDescription = (
entry: Record<string, unknown>,
manifestDescriptions: Map<string, string>,
) => {
const slug = resolveRecordSlug(entry);
if (slug && manifestDescriptions.has(slug)) {
return escapeTableValue(normalizeTableText(manifestDescriptions.get(slug) ?? ""));
}
if (typeof entry.description === "string" && entry.description.trim()) {
return escapeTableValue(normalizeTableText(entry.description));
}
if (typeof entry.name === "string" && entry.name.trim()) {
return escapeTableValue(normalizeTableText(entry.name));
}
return "";
};
const resolveRecordAuthor = (entry: Record<string, unknown>, manifestAuthors: Map<string, string>) => {
const slug = resolveRecordSlug(entry);
if (slug && manifestAuthors.has(slug)) {
return escapeTableValue(normalizeTableText(manifestAuthors.get(slug) ?? ""));
}
return "";
};
const SKILLS_TABLE_START = "<!-- skills-table-start -->";
const SKILLS_TABLE_END = "<!-- skills-table-end -->";
const getRepoHttpUrl = () => {
const remote = Bun.spawnSync(["git", "remote", "get-url", "origin"], {
stdout: "pipe",
stderr: "ignore",
});
const remoteUrl = remote.success ? remote.stdout.toString().trim() : "";
const repo = remoteUrl ? parseGitHubRepo(remoteUrl) : null;
if (!repo) {
return "https://github.com/zocomputer/skills";
}
return `https://github.com/${repo.owner}/${repo.repo}`;
};
const getRepoRef = () => {
const branch = Bun.spawnSync(["git", "rev-parse", "--abbrev-ref", "HEAD"], {
stdout: "pipe",
stderr: "ignore",
});
return branch.success ? branch.stdout.toString().trim() : "main";
};
const buildSkillsTable = (
entries: Record<string, unknown>[],
manifestDescriptions: Map<string, string>,
manifestAuthors: Map<string, string>,
) => {
const lines = [
"| Skill | Author | Description |",
"| --- | --- | --- |",
];
const repoUrl = getRepoHttpUrl();
const ref = getRepoRef();
for (const entry of entries) {
const slug = resolveRecordSlug(entry);
if (!slug) {
continue;
}
const description = resolveRecordDescription(entry, manifestDescriptions);
const author = resolveRecordAuthor(entry, manifestAuthors);
const link = `${repoUrl}/blob/${ref}/${EXTERNAL_DIR}/${slug}/SKILL.md`;
lines.push(`| [${slug}](${link}) | ${author} | ${description} |`);
}
lines.push("");
return lines.join("\n");
};
const upsertSkillsTableInReadme = async (table: string) => {
const readmePath = path.join(ROOT_DIR, "README.md");
let readme = "";
try {
readme = await readFile(readmePath, "utf8");
} catch {
console.log("Unable to read README.md.");
return;
}
const tableBlock = `${SKILLS_TABLE_START}\n${table}\n${SKILLS_TABLE_END}`;
const markerRegex = new RegExp(
`${SKILLS_TABLE_START}[\\s\\S]*?${SKILLS_TABLE_END}`,
"m",
);
if (markerRegex.test(readme)) {
const updated = readme.replace(markerRegex, tableBlock);
await writeFile(readmePath, updated);
return;
}
const section = `## Skills\n\n${tableBlock}\n\n`;
const contributingIndex = readme.indexOf("# Contributing");
if (contributingIndex !== -1) {
const updated =
readme.slice(0, contributingIndex) + section + readme.slice(contributingIndex);
await writeFile(readmePath, updated);
return;
}
await writeFile(readmePath, `${readme.trimEnd()}\n\n${section}`);
};
const loadManifestDescriptions = async () => {
const manifestPath = path.join(ROOT_DIR, "manifest.json");
let raw = "";
try {
raw = await readFile(manifestPath, "utf8");
} catch {
console.log("manifest.json not found; using external.yml metadata for descriptions.");
return new Map<string, string>();
}
try {
const parsed = JSON.parse(raw) as SkillManifest;
const descriptions = new Map<string, string>();
for (const skill of parsed.skills ?? []) {
if (skill && typeof skill.slug === "string" && typeof skill.description === "string") {
descriptions.set(skill.slug, skill.description.trim());
}
}
return descriptions;
} catch {
console.log("Unable to parse manifest.json; using external.yml metadata for descriptions.");
return new Map<string, string>();
}
};
const loadManifestAuthors = async () => {
const manifestPath = path.join(ROOT_DIR, "manifest.json");
let raw = "";
try {
raw = await readFile(manifestPath, "utf8");
} catch {
console.log("manifest.json not found; using external.yml metadata for authors.");
return new Map<string, string>();
}
try {
const parsed = JSON.parse(raw) as SkillManifest;
const authors = new Map<string, string>();
for (const skill of parsed.skills ?? []) {
if (!skill || typeof skill.slug !== "string") {
continue;
}
const metadata = (skill as Record<string, unknown>).metadata;
if (!metadata || typeof metadata !== "object") {
continue;
}
const author = (metadata as Record<string, unknown>).author;
if (typeof author === "string" && author.trim()) {
authors.set(skill.slug, author.trim());
}
}
return authors;
} catch {
console.log("Unable to parse manifest.json; using external.yml metadata for authors.");
return new Map<string, string>();
}
};
const organizeExternalConfig = async () => {
let config: string;
try {
config = await readFile(EXTERNAL_CONFIG, "utf8");
} catch {
console.log("No external.yml found. Nothing to organize.");
return 0;
}
let parsed: unknown;
try {
parsed = parseYaml(config);
} catch {
console.log("Unable to parse external.yml.");
return 1;
}
if (!Array.isArray(parsed)) {
console.log("external.yml must be a list.");
return 1;
}
const entries = parsed.filter((entry) => entry && typeof entry === "object");
const grouped = new Map<string, Record<string, unknown>[]>();
const repoOrder: string[] = [];
for (const entry of entries) {
const record = entry as Record<string, unknown>;
const repository = typeof record.repository === "string" ? record.repository : "";
if (!repository) {
continue;
}
if (!grouped.has(repository)) {
grouped.set(repository, []);
repoOrder.push(repository);
}
grouped.get(repository)?.push(record);
}
const preferredRepoOrder = ["clawdbot/clawdbot", "clawdbot/skills"];
const preferredRepos = new Set(preferredRepoOrder);
const orderedRepos = preferredRepoOrder
.filter((repo) => repoOrder.includes(repo))
.concat(
repoOrder
.filter((repo) => !preferredRepos.has(repo))
.sort((a, b) => {
const sizeA = grouped.get(a)?.length ?? 0;
const sizeB = grouped.get(b)?.length ?? 0;
if (sizeA !== sizeB) {
return sizeA - sizeB;
}
return a.localeCompare(b);
}),
);
const organized: Record<string, unknown>[] = [];
for (const repository of orderedRepos) {
const group = grouped.get(repository) ?? [];
group.sort((a, b) => {
const countA = countExternalMetadataFields(a);
const countB = countExternalMetadataFields(b);
if (countA !== countB) {
return countB - countA;
}
const skillA = typeof a.skill === "string" ? a.skill : "";
const skillB = typeof b.skill === "string" ? b.skill : "";
return skillA.localeCompare(skillB);
});
organized.push(
...group.map((record) => {
const { name: _name, ...rest } = record;
return rest;
}),
);
}
const output = stringifyYaml(organized, { lineWidth: 0 });
await writeFile(EXTERNAL_CONFIG, output);
const externalSlugs = new Set(
organized.map((entry) => resolveRecordSlug(entry)).filter(Boolean),
);
const moved = await reorganizeSkillDirectories(externalSlugs);
const officialMoves = await ensureOfficialSlugPrefixForAllSkills();
const nameUpdates = await ensureSkillNameSlugForAllSkills();
const categoryUpdates = await ensureMetadataCategoryForAllSkills();
const manifestDescriptions = await loadManifestDescriptions();
const manifestAuthors = await loadManifestAuthors();
const table = buildSkillsTable(organized, manifestDescriptions, manifestAuthors);
await upsertSkillsTableInReadme(table);
console.log(`Organized ${organized.length} external skill entries.`);
if (moved > 0) {
console.log(`Moved ${moved} skill(s) into category folders.`);
}
if (officialMoves > 0) {
console.log(`Prefixed ${officialMoves} Official skill slug(s) with ${OFFICIAL_PREFIX}.`);
}
if (nameUpdates > 0) {
console.log(`Normalized name field for ${nameUpdates} skill(s).`);
}
if (categoryUpdates > 0) {
console.log(`Updated metadata.category for ${categoryUpdates} skill(s).`);
}
return 0;
};
const hasFrontmatter = (content: string) => content.trimStart().startsWith("---");
// Use gray-matter for parsing, but serialize ourselves to keep metadata deterministic.
const parseSkillFile = (content: string) => {
const parsed = matter(content);
return {
data: parsed.data as Record<string, unknown>,
body: parsed.content,
};
};
const readSkillFile = async (skillFile: string) => {
const content = await readFile(skillFile, "utf8");
if (!hasFrontmatter(content)) {
return null;
}
return parseSkillFile(content);
};
const serializeFrontmatterValue = (value: unknown) => {
if (typeof value === "string") {
if (value.includes("\n")) {
const lines = value.split("\n").map((line) => ` ${line}`);
return `|\n${lines.join("\n")}`;
}
return value;
}
if (value === null || value === undefined) {
return "";
}
if (typeof value === "object") {
return JSON.stringify(value);
}
return String(value);
};
// Metadata is a YAML block with JSON-serialized nested values.
const serializeMetadataBlock = (value: unknown) => {
if (!value || typeof value !== "object") {
return serializeFrontmatterValue(value);
}
const entries = Object.entries(value as Record<string, unknown>).sort(([a], [b]) =>
a.localeCompare(b),
);
const lines = ["metadata:"];
for (const [key, metaValue] of entries) {
if (metaValue === undefined) {
continue;
}
if (metaValue !== null && typeof metaValue === "object") {
lines.push(` ${key}: ${JSON.stringify(metaValue)}`);
} else {
lines.push(` ${key}: ${serializeFrontmatterValue(metaValue)}`);
}
}
return lines.join("\n");
};
// Frontmatter order is stable; metadata keys are alphabetized.
const serializeSkillFile = (data: Record<string, unknown>, body: string) => {
const preferredOrder = [
"name",
"description",
"homepage",
"license",
"compatibility",
"allowed-tools",
"metadata",
];
const keys = Object.keys(data);
const orderedKeys = [
...preferredOrder.filter((key) => keys.includes(key)),
...keys.filter((key) => !preferredOrder.includes(key)).sort(),
];
const lines = ["---"];
for (const key of orderedKeys) {
const value = data[key];
if (value === undefined) {
continue;
}
if (key === "metadata") {
const serialized = serializeMetadataBlock(value);
if (serialized.startsWith("metadata:")) {
lines.push(serialized);
} else {
lines.push(`metadata: ${serialized}`);
}
continue;
}
const serialized = serializeFrontmatterValue(value);
lines.push(`${key}: ${serialized}`);
}
lines.push("---");
const trimmedBody = body.replace(/^\s+/, "");
return `${lines.join("\n")}\n\n${trimmedBody}`;
};
const validateSkill = async (skillDir: string): Promise<Issue[]> => {
const issues: Issue[] = [];
const skillName = path.basename(skillDir);
const parentCategory = path.basename(path.dirname(skillDir));
const skillFile = path.join(skillDir, "SKILL.md");
try {
const entries = await readdir(skillDir, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) {
continue;
}
if (!ALLOWED_SKILL_DIRS.has(entry.name)) {
issues.push({
skillPath: toDisplayPath(skillDir),
message:
"Only 'assets', 'references', or 'scripts' directories are allowed at the skill root.",
level: parentCategory === EXTERNAL_DIR ? "warning" : "error",
});
break;
}
}
} catch {
issues.push({
skillPath: toDisplayPath(skillDir),
message: "Unable to read skill directory contents.",
level: "error",
});
return issues;
}
let content: string;
try {
content = await readFile(skillFile, "utf8");
} catch {
issues.push({
skillPath: toDisplayPath(skillDir),
message: "Missing SKILL.md file.",
level: "error",
});
return issues;
}
if (!hasFrontmatter(content)) {
issues.push({
skillPath: toDisplayPath(skillFile),
message: "Missing frontmatter start '---'.",
level: "error",
});
return issues;
}
const { data } = parseSkillFile(content);
const name = typeof data.name === "string" ? data.name : "";
const description = typeof data.description === "string" ? data.description : "";
const metadata = data.metadata;
const author =
metadata && typeof metadata === "object" && "author" in metadata
? String((metadata as Record<string, unknown>).author ?? "")
: "";
if (!name) {
issues.push({
skillPath: toDisplayPath(skillFile),
message: "Missing required 'name' field in frontmatter.",
level: "error",
});
} else {
if (name.length > 64) {
issues.push({
skillPath: toDisplayPath(skillFile),
message: "Field 'name' exceeds 64 characters.",
level: "error",
});
}
if (!NAME_PATTERN.test(name)) {
issues.push({
skillPath: toDisplayPath(skillFile),
message:
"Field 'name' must be lowercase alphanumeric with single hyphens only.",
level: "error",
});
}
const expectedName =
OFFICIAL_CATEGORIES.has(parentCategory) && skillName.startsWith(OFFICIAL_PREFIX)
? skillName.slice(OFFICIAL_PREFIX.length)
: skillName;
if (name !== expectedName) {
issues.push({
skillPath: toDisplayPath(skillFile),
message:
OFFICIAL_CATEGORIES.has(parentCategory)
? "Field 'name' must match the parent directory name without the 'zo-' prefix."
: "Field 'name' must match the parent directory name.",
level: "error",
});
}
}
if (!description) {
issues.push({
skillPath: toDisplayPath(skillFile),
message: "Missing required 'description' field in frontmatter.",
level: parentCategory === EXTERNAL_DIR ? "warning" : "error",
});
} else {
if (description.length > 1024) {
issues.push({
skillPath: toDisplayPath(skillFile),
message: "Field 'description' exceeds 1024 characters.",
level: "error",
});
}
}
if (!author) {
issues.push({
skillPath: toDisplayPath(skillFile),
message: "Missing required 'metadata.author' field in frontmatter.",
level: "error",
});
}
if (OFFICIAL_CATEGORIES.has(parentCategory) && !skillName.startsWith(OFFICIAL_PREFIX)) {
issues.push({
skillPath: toDisplayPath(skillDir),
message: `Official skill directories must start with '${OFFICIAL_PREFIX}'.`,
level: "error",
});
}
return issues;
};
type SkillInfo = {
slug: string;
path: string;
} & Record<string, unknown>;
type SkillManifest = {
tarball_url: string;
archive_root: string;
skills: SkillInfo[];
};
const parseGitHubRepo = (remoteUrl: string) => {
const httpsMatch = remoteUrl.match(/github\.com\/([^/]+)\/([^/.]+)(?:\.git)?$/);
if (httpsMatch) {
return { owner: httpsMatch[1], repo: httpsMatch[2] };
}
const sshMatch = remoteUrl.match(/git@github\.com:([^/]+)\/([^/.]+)(?:\.git)?$/);
if (sshMatch) {
return { owner: sshMatch[1], repo: sshMatch[2] };
}
return null;
};
const appendCompatibilityNote = (current: unknown, note: string) => {
if (typeof current !== "string" || !current.trim()) {
return note;
}
if (current.includes(note)) {
return current;
}
return `${current}; ${note}`;
};
const inferCompatibilityNote = (data: Record<string, unknown>) => {
const metadata = data.metadata;
if (!metadata || typeof metadata !== "object") {
return undefined;
}
const clawdbot = (metadata as Record<string, unknown>).clawdbot;
if (!clawdbot || typeof clawdbot !== "object") {
return undefined;
}
const requires = (clawdbot as Record<string, unknown>).requires;
if (!requires || typeof requires !== "object") {
return undefined;
}
return "see metadata.clawdbot.requires";
};
const normalizeClawdbotInstall = (data: Record<string, unknown>) => {
const metadata = data.metadata;
if (!metadata || typeof metadata !== "object") {
return { data, changed: false };
}
const metadataRecord = metadata as Record<string, unknown>;
const clawdbot = metadataRecord.clawdbot;
if (!clawdbot || typeof clawdbot !== "object") {
return { data, changed: false };
}
const clawdbotRecord = clawdbot as Record<string, unknown>;
const install = clawdbotRecord.install;
if (!Array.isArray(install)) {
return { data, changed: false };
}
if (install.length <= 1) {
return { data, changed: false };
}
const filtered = install.filter((entry) => {
if (!entry || typeof entry !== "object") {
return true;
}
return (entry as Record<string, unknown>).kind !== "brew";
});