catalog.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import { spawnSync } from "node:child_process";
  2. import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { fileURLToPath } from "node:url";
  6. import { describe, expect, it } from "vitest";
  7. import { CONFIG, MAX_BYTES, buildCatalog, collectResources, firstSentence, resolveCraft } from "../skills/design/scripts/build-catalog.mjs";
  8. import { parseFrontmatter, splitFrontmatter } from "../skills/design/scripts/frontmatter.mjs";
  9. // references/catalog.md 由 build-catalog.mjs 从 design-resources 生成;这里守住新鲜度、体量、覆盖和配置漂移。
  10. const skillRoot = fileURLToPath(new URL("../skills/design/", import.meta.url));
  11. const resourceRoot = join(skillRoot, "design-resources");
  12. const script = join(skillRoot, "scripts", "build-catalog.mjs");
  13. const committed = readFileSync(join(skillRoot, "references", "catalog.md"), "utf8");
  14. const resources = collectResources(resourceRoot);
  15. const skeletonNames: string[] = [...resources.skeletons.keys()];
  16. const skillNames: string[] = [...resources.skills.keys()];
  17. const systemNames: string[] = [...resources.systems.keys()];
  18. const craftNames: string[] = resources.craft;
  19. type Category = { key: string; title: string; prefix?: string; craft: string[]; members: string[] };
  20. const categories: Category[] = CONFIG.categories;
  21. const sorted = (values: Iterable<string>) => [...new Set(values)].sort();
  22. function section(text: string, title: string): string {
  23. const start = text.indexOf(`\n## ${title}\n`);
  24. if (start < 0) throw new Error(`catalog 缺少 ## ${title}`);
  25. const end = text.indexOf("\n## ", start + 1);
  26. return text.slice(start + 1, end < 0 ? undefined : end);
  27. }
  28. // 从 catalog 文本反解出每一节列出的名称,以及按该节路径模板展开后的文件路径。
  29. function listed(text: string) {
  30. const template = (body: string) => {
  31. const found = body.split("\n")[1]?.match(/`(design-resources\/[^`]*<name>[^`]*)`/)?.[1];
  32. if (!found) throw new Error(`缺少路径模板:${body.split("\n")[0]}`);
  33. return found;
  34. };
  35. const skeletons: string[] = [];
  36. let prefix = "";
  37. for (const line of section(text, "Skeletons").split("\n")) {
  38. if (line.startsWith("### ")) prefix = line.match(/`([a-z0-9-]+-)<x>`/)?.[1] ?? "";
  39. const name = line.match(/^- `([^`]+)`/)?.[1];
  40. if (name) skeletons.push(prefix + name);
  41. }
  42. const rowNames = (title: string) =>
  43. section(text, title)
  44. .split("\n")
  45. .filter((line) => line.startsWith("- "))
  46. .flatMap((line) => [...line.replace(/ — .*$/, "").matchAll(/`([a-z0-9-]+)`/g)].map((m) => m[1] as string));
  47. const names = {
  48. skeletons,
  49. skills: rowNames("Skills"),
  50. systems: rowNames("Design systems"),
  51. craft: rowNames("Craft"),
  52. };
  53. const paths = [
  54. ...names.skeletons.map((n) => template(section(text, "Skeletons")).replace("<name>", n)),
  55. ...names.skills.map((n) => template(section(text, "Skills")).replace("<name>", n)),
  56. ...names.systems.map((n) => template(section(text, "Design systems")).replace("<name>", n)),
  57. ...names.craft.map((n) => template(section(text, "Craft")).replace("<name>", n)),
  58. ];
  59. return { names, paths };
  60. }
  61. const skeletonRow = (name: string) => {
  62. const category = categories.find((c) => c.members.includes(name)) as Category;
  63. const label = category.prefix ? name.slice(category.prefix.length) : name;
  64. return committed.split("\n").find((line) => line.startsWith(`- \`${label}\``)) ?? "";
  65. };
  66. describe("catalog.md 新鲜度与体量", () => {
  67. it("与 build-catalog.mjs 的生成结果逐字节一致", () => {
  68. expect(buildCatalog(resourceRoot), "catalog.md 过期:运行 node apps/zcode-cli/packages/design-plugin/skills/design/scripts/build-catalog.mjs").toBe(committed);
  69. });
  70. it("生成结果确定:两次相同,无时间戳、绝对路径和 CR,以单个 LF 结尾", () => {
  71. expect(buildCatalog(resourceRoot)).toBe(buildCatalog(resourceRoot));
  72. expect(committed).not.toMatch(/\d{4}-\d{2}-\d{2}|\d{2}:\d{2}:\d{2}/);
  73. expect(committed).not.toContain(skillRoot);
  74. expect(committed).not.toMatch(/\]\(\/|`\/|\$\{[A-Z_]+\}/);
  75. expect(committed).not.toContain("\r");
  76. expect(committed.endsWith("\n") && !committed.endsWith("\n\n")).toBe(true);
  77. });
  78. it("不超过 8 KB、500 行;超过 100 行时顶部有指向各节的 Contents", () => {
  79. expect(MAX_BYTES).toBe(8192);
  80. expect(Buffer.byteLength(committed, "utf8")).toBeLessThanOrEqual(MAX_BYTES);
  81. const lines = committed.split("\n").length - 1;
  82. expect(lines).toBeLessThanOrEqual(500);
  83. if (lines > 100) {
  84. const contents = committed.split("\n").slice(0, 12).find((line) => line.startsWith("Contents: ")) ?? "";
  85. for (const heading of committed.matchAll(/^## (.+)$/gm)) {
  86. const title = heading[1] as string;
  87. expect(contents, title).toContain(`[${title}](#${title.toLowerCase().replace(/ /g, "-")})`);
  88. }
  89. }
  90. });
  91. it("超过上限时非零退出、不写文件,并输出分段体量", () => {
  92. const dir = mkdtempSync(join(tmpdir(), "zcode-design-catalog-"));
  93. try {
  94. const out = join(dir, "catalog.md");
  95. const run = spawnSync(process.execPath, [script, "--max-bytes=1000", `--out=${out}`], { encoding: "utf8", timeout: 20000 });
  96. expect(run.status).toBe(1);
  97. expect(run.stderr).toContain("over the 1000 B cap");
  98. for (const title of ["(head)", "Skeletons", "Skills", "Design systems", "Craft"]) expect(run.stderr, title).toContain(title);
  99. expect(existsSync(out)).toBe(false);
  100. const ok = spawnSync(process.execPath, [script, `--out=${out}`], { encoding: "utf8", timeout: 20000 });
  101. expect(ok.status).toBe(0);
  102. expect(readFileSync(out, "utf8")).toBe(committed);
  103. } finally {
  104. rmSync(dir, { force: true, recursive: true });
  105. }
  106. });
  107. });
  108. describe("catalog.md 覆盖与对应", () => {
  109. const { names, paths } = listed(committed);
  110. it("每个骨架、技能、设计系统和 craft 都列出或明确排除;列出的每项都能解析到随包文件", () => {
  111. expect(sorted([...names.skeletons, ...CONFIG.excludeSkeletons])).toEqual(sorted(skeletonNames));
  112. expect(names.skeletons).toHaveLength(skeletonNames.length - CONFIG.excludeSkeletons.length);
  113. expect(sorted([...names.skills, ...CONFIG.skills.exclude])).toEqual(sorted(skillNames));
  114. expect(names.skills.filter((n) => CONFIG.skills.exclude.includes(n))).toEqual([]);
  115. expect(sorted(names.systems)).toEqual(sorted(systemNames));
  116. expect(sorted(names.craft)).toEqual(sorted(craftNames));
  117. expect(paths.length).toBeGreaterThan(100);
  118. expect(paths.filter((path) => !existsSync(join(skillRoot, ...path.split("/"))))).toEqual([]);
  119. });
  120. it("配置里的每个名称都对应真实资源", () => {
  121. const skeletonRefs = [
  122. ...categories.flatMap((c) => c.members),
  123. ...CONFIG.excludeSkeletons,
  124. ...CONFIG.nameOnly,
  125. ...Object.keys(CONFIG.override),
  126. ...CONFIG.notes.flatMap((n: { names: string[] }) => n.names),
  127. ...Object.values(CONFIG.defaults as Record<string, string>),
  128. ...CONFIG.missing.flatMap((m: { usedBy: string[] }) => m.usedBy),
  129. ];
  130. expect(skeletonRefs.filter((n) => !skeletonNames.includes(n))).toEqual([]);
  131. const skillRefs = [...CONFIG.skills.exclude, ...Object.keys(CONFIG.skills.override), ...CONFIG.nameMismatch];
  132. expect(skillRefs.filter((n) => !skillNames.includes(n))).toEqual([]);
  133. const systemRefs = [...Object.keys(CONFIG.systemNotes), ...Object.keys(CONFIG.systemOverride)];
  134. expect(systemRefs.filter((n) => !systemNames.includes(n))).toEqual([]);
  135. const craftRefs = [...CONFIG.craftBaseline, ...CONFIG.craftConditional, ...Object.values(CONFIG.craftAlias as Record<string, string>), ...categories.flatMap((c) => c.craft)];
  136. expect(craftRefs.filter((n) => !craftNames.includes(n))).toEqual([]);
  137. // 未随包的名字一旦随包,丢弃表和别名表就过期了。
  138. expect([...CONFIG.craftDrop, ...Object.keys(CONFIG.craftAlias)].filter((n) => craftNames.includes(n))).toEqual([]);
  139. // 每条注记挂在同一类别下。
  140. for (const note of CONFIG.notes as { names: string[] }[]) {
  141. const keys = new Set(note.names.map((n) => categories.find((c) => c.members.includes(n))?.key));
  142. expect(keys.size, note.names.join(",")).toBe(1);
  143. }
  144. });
  145. it("每个骨架恰好属于一个类别;设计系统的 Category 都在分组表里;craft 目录等于 CONFIG.craft 的键", () => {
  146. const members = categories.flatMap((c) => c.members);
  147. expect(sorted([...members, ...CONFIG.excludeSkeletons])).toEqual(sorted(skeletonNames));
  148. expect(members).toHaveLength(skeletonNames.length - CONFIG.excludeSkeletons.length);
  149. const unknown = systemNames.filter((n) => !(resources.systems.get(n).category in CONFIG.systemGroups)).map((n) => `${n}: ${resources.systems.get(n).category}`);
  150. expect(unknown).toEqual([]);
  151. expect(sorted(Object.keys(CONFIG.craft))).toEqual(sorted(craftNames));
  152. });
  153. it("骨架声明的 craft 都能解析:在 craft/、别名、丢弃或条件表里", () => {
  154. const unresolved: string[] = [];
  155. for (const [name, { frontmatter }] of resources.skeletons) {
  156. for (const craft of frontmatter.od?.craft?.requires ?? []) {
  157. const target = resolveCraft(craft);
  158. if (target !== null && !craftNames.includes(target)) unresolved.push(`${name}: ${craft}`);
  159. }
  160. }
  161. expect(unresolved).toEqual([]);
  162. });
  163. });
  164. describe("design-resources 输入数据质量", () => {
  165. const files = [
  166. ...skeletonNames.map((n) => ({ dir: n, file: join(resourceRoot, "design-skeletons", n, "SKILL.md") })),
  167. ...skillNames.map((n) => ({ dir: n, file: join(resourceRoot, "skills", n, "SKILL.md") })),
  168. ];
  169. it("每个 SKILL.md 有 frontmatter,name 等于目录名(已知例外除外),description 非空,triggers 是字符串数组", () => {
  170. expect(files.length).toBeGreaterThan(80);
  171. const problems: string[] = [];
  172. for (const { dir, file } of files) {
  173. const raw = splitFrontmatter(readFileSync(file, "utf8"));
  174. if (raw === null) {
  175. problems.push(`${dir}: no frontmatter`);
  176. continue;
  177. }
  178. const fm = parseFrontmatter(raw);
  179. if ((fm.name === dir) === CONFIG.nameMismatch.includes(dir)) problems.push(`${dir}: name ${fm.name}`);
  180. if (typeof fm.description !== "string" || fm.description.trim() === "") problems.push(`${dir}: description`);
  181. if (fm.triggers !== undefined && !(Array.isArray(fm.triggers) && fm.triggers.every((t: unknown) => typeof t === "string"))) {
  182. problems.push(`${dir}: triggers`);
  183. }
  184. }
  185. expect(problems).toEqual([]);
  186. });
  187. it("描述首句被截断(不足 20 字符或以 — / : 结尾,如 YAML 把 ` #` 当注释)时必须有覆盖句", () => {
  188. const suspicious = (description: string) => {
  189. const sentence = firstSentence(description);
  190. return [...sentence].length < 20 || /[—:]$/.test(sentence);
  191. };
  192. const bad = [
  193. ...[...resources.skeletons].filter(([n, { frontmatter }]) => !(n in CONFIG.override) && suspicious(frontmatter.description)),
  194. ...[...resources.skills].filter(([n, { frontmatter }]) => !(n in CONFIG.skills.override) && suspicious(frontmatter.description)),
  195. ].map(([n]) => n);
  196. expect(bad).toEqual([]);
  197. expect(suspicious(resources.skeletons.get("html-ppt-hermes-cyber-terminal").frontmatter.description)).toBe(true);
  198. });
  199. describe("frontmatter 解析器", () => {
  200. it("块标量、折叠标量、跨行流式列表、列表里的映射、行内注释", () => {
  201. const fm = parseFrontmatter(
  202. [
  203. "name: demo",
  204. "description: |",
  205. " First line.",
  206. " Second line.",
  207. "summary: >",
  208. " folded",
  209. " text",
  210. "triggers:",
  211. ' - "quoted, with comma"',
  212. " - bare words",
  213. "od:",
  214. " craft:",
  215. " requires: [typography, color,",
  216. " laws-of-ux]",
  217. " default: 198 # Notion-blue",
  218. " note: dark #0a0c10 canvas",
  219. " inputs:",
  220. " - name: title",
  221. " type: string",
  222. " design_system:",
  223. " requires: false",
  224. ].join("\n"),
  225. );
  226. expect(fm.description).toBe("First line.\nSecond line.");
  227. expect(fm.summary).toBe("folded text");
  228. expect(fm.triggers).toEqual(["quoted, with comma", "bare words"]);
  229. expect(fm.od.craft.requires).toEqual(["typography", "color", "laws-of-ux"]);
  230. expect(fm.od.default).toBe(198);
  231. expect(fm.od.note).toBe("dark");
  232. expect(fm.od.inputs).toEqual([{ name: "title", type: "string" }]);
  233. expect(fm.od.design_system.requires).toBe(false);
  234. });
  235. it("兼容 CRLF 与 BOM", () => {
  236. const text = "\uFEFF---\r\nname: demo\r\ndescription: |\r\n a\r\n b\r\n---\r\nbody\r\n";
  237. const raw = splitFrontmatter(text);
  238. expect(raw).not.toBeNull();
  239. expect(parseFrontmatter(raw)).toEqual({ name: "demo", description: "a\nb" });
  240. expect(splitFrontmatter("# no frontmatter\n")).toBeNull();
  241. });
  242. it("不认识的构造直接抛错,不静默跳过", () => {
  243. for (const source of ['description: "starts here', "od: {mode: deck}", "base: &anchor x", "ref: *anchor", "tag: !str x", "just text", "a: 1\n b: 2"]) {
  244. expect(() => parseFrontmatter(source), source).toThrow();
  245. }
  246. });
  247. });
  248. });
  249. describe("catalog.md 内容", () => {
  250. it("头部写出的三个默认骨架都存在,并在各自类别里", () => {
  251. const { deck, web, app } = CONFIG.defaults as Record<string, string>;
  252. const keyOf = (name: string) => categories.find((c) => c.members.includes(name))?.key;
  253. expect(["deck", "zhangzara"]).toContain(keyOf(deck));
  254. expect(keyOf(web)).toBe("web");
  255. expect(keyOf(app)).toBe("app");
  256. const head = committed.slice(0, committed.indexOf("\n## "));
  257. expect(head).toContain(`Defaults: deck \`${deck}\`, web \`${web}\`, app \`${app}\`.`);
  258. });
  259. it("hermes 行用覆盖句而不是被 YAML 截断的描述;broadside 行带 editorial", () => {
  260. const hermes = skeletonRow("html-ppt-hermes-cyber-terminal");
  261. expect(hermes).toContain(CONFIG.override["html-ppt-hermes-cyber-terminal"]);
  262. expect(hermes).not.toMatch(/deck —\s*(\[|$)/);
  263. expect(skeletonRow("html-ppt-zhangzara-broadside")).toContain("editorial");
  264. });
  265. it("缺文件警示仍然成立:被点名的文件依旧未随包,头部写明", () => {
  266. const head = committed.slice(0, committed.indexOf("\n## "));
  267. for (const { label, paths } of CONFIG.missing as { label: string; paths: string[] }[]) {
  268. expect(head, label).toContain(label);
  269. for (const path of paths) {
  270. expect(existsSync(join(resourceRoot, ...path.split("/"))), `${path} 已随包,更新 CONFIG.missing`).toBe(false);
  271. }
  272. }
  273. });
  274. it("open-design-landing-deck 不承诺缺失的同伴文件;gstack 三个方法型技能不再列出", () => {
  275. const note = committed.split("\n").find((line) => line.startsWith("- Note, `open-design-landing-deck`")) ?? "";
  276. for (const phrase of ["`scripts/compose.ts`", "not shipped", "`schema.ts`", "do not run"]) expect(note, phrase).toContain(phrase);
  277. for (const name of ["design-review", "plan-design-review", "design-consultation"]) {
  278. expect(committed, name).not.toContain(`\`${name}\``);
  279. }
  280. expect(skillNames).toEqual(expect.arrayContaining(["design-review", "plan-design-review", "design-consultation"]));
  281. });
  282. it("依赖 OD daemon / connector / 媒体运行时的骨架不在可选目录里,目录说明未列出的不可用", () => {
  283. // 这几个上游骨架的强制步骤要 OD_* 包装命令、artifact 注册或 MP4 生成,本宿主没有,静态流程走不通。
  284. const excluded = ["live-artifact", "live-dashboard", "hyperframes", "video-shortform"];
  285. expect(sorted(CONFIG.excludeSkeletons)).toEqual(sorted(excluded));
  286. const skeletonSection = section(committed, "Skeletons");
  287. for (const name of excluded) {
  288. expect(skeletonNames, name).toContain(name);
  289. expect(committed, name).not.toContain(`\`${name}\``);
  290. expect(categories.flatMap((c) => c.members), name).not.toContain(name);
  291. }
  292. expect(skeletonSection.split("\n")[1]).toContain("Folders not listed need a runtime this host lacks; never use them.");
  293. });
  294. it("设计系统节首行链接 BRAND-DISCLAIMER.md;kami 注明只经 kami-* 骨架选择", () => {
  295. const systems = section(committed, "Design systems");
  296. const first = systems.split("\n")[1] as string;
  297. expect(first).toContain("[BRAND-DISCLAIMER.md](../design-resources/design-systems/BRAND-DISCLAIMER.md)");
  298. expect(existsSync(join(resourceRoot, "design-systems", "BRAND-DISCLAIMER.md"))).toBe(true);
  299. expect(systems).toMatch(/`kami` \(only via kami-\* skeletons\)/);
  300. });
  301. it("no example 标记的集合等于磁盘上没有 example.html 的骨架集合", () => {
  302. const offered = skeletonNames.filter((n) => !CONFIG.excludeSkeletons.includes(n));
  303. const marked = offered.filter((n) => /\[[^\]]*no example[^\]]*\]$/.test(skeletonRow(n)));
  304. const missing = offered.filter((n) => !existsSync(join(resourceRoot, "design-skeletons", n, "example.html")));
  305. expect(missing.length).toBeGreaterThan(0);
  306. expect(sorted(marked)).toEqual(sorted(missing));
  307. expect(readdirSync(join(resourceRoot, "design-skeletons")).length).toBe(skeletonNames.length);
  308. });
  309. });