catalog.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. import { spawnSync } from "node:child_process";
  2. import { cpSync, existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } 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 { BLOCK_BEGIN, BLOCK_END, CONFIG, TARGETS, TRACKS, buildAll, collectResources, firstSentence, resolveCraft } from "../skills/design/scripts/build-catalog.mjs";
  8. import { parseFrontmatter, splitFrontmatter } from "../skills/design/scripts/frontmatter.mjs";
  9. // references/catalog.md 与 deck / app / page.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 referencesDir = join(skillRoot, "references");
  14. const committed = readFileSync(join(referencesDir, "catalog.md"), "utf8");
  15. const trackText: Record<string, string> = Object.fromEntries(TRACKS.map((t: string) => [t, readFileSync(join(referencesDir, `${t}.md`), "utf8")]));
  16. const blockOf = (text: string) => text.slice(text.indexOf(BLOCK_BEGIN), text.indexOf(BLOCK_END) + BLOCK_END.length);
  17. // 骨架清单分在三份交付物文件的生成块里,合起来才等于旧 catalog 的 Skeletons 一节。
  18. const skeletonText = TRACKS.map((t: string) => blockOf(trackText[t] as string)).join("\n");
  19. const generated = () => buildAll(resourceRoot, referencesDir) as Map<string, string>;
  20. const resources = collectResources(resourceRoot);
  21. const allSkeletonNames: string[] = [...resources.skeletons.keys()];
  22. const excluded: string[] = CONFIG.excludeSkeletons;
  23. // 依赖 Open Design 运行时的骨架留在磁盘上但不列出;其余都要恰好列一次。
  24. const skeletonNames: string[] = allSkeletonNames.filter((n) => !excluded.includes(n));
  25. const skillNames: string[] = [...resources.skills.keys()];
  26. const systemNames: string[] = [...resources.systems.keys()];
  27. const craftNames: string[] = resources.craft;
  28. type Category = { key: string; title: string; prefix?: string; craft: string[]; members: string[] };
  29. type Missing = { label?: string; inline?: string; paths: string[]; usedBy: string[] };
  30. const categories: Category[] = CONFIG.categories;
  31. const sorted = (values: Iterable<string>) => [...new Set(values)].sort();
  32. function section(text: string, title: string): string {
  33. const start = text.indexOf(`\n## ${title}\n`);
  34. if (start < 0) throw new Error(`catalog 缺少 ## ${title}`);
  35. const end = text.indexOf("\n## ", start + 1);
  36. return text.slice(start + 1, end < 0 ? undefined : end);
  37. }
  38. // 从 catalog 文本反解出每一节列出的名称,以及按该节路径模板展开后的文件路径。
  39. function listed(text: string) {
  40. const template = (body: string) => {
  41. const found = body.split("\n")[1]?.match(/`(design-resources\/[^`]*<name>[^`]*)`/)?.[1];
  42. if (!found) throw new Error(`缺少路径模板:${body.split("\n")[0]}`);
  43. return found;
  44. };
  45. const skeletons: string[] = [];
  46. let prefix = "";
  47. for (const line of skeletonText.split("\n")) {
  48. if (line.startsWith("### ")) prefix = line.match(/`([a-z0-9-]+-)<x>`/)?.[1] ?? "";
  49. const name = line.match(/^- `([^`]+)`/)?.[1];
  50. if (name) skeletons.push(prefix + name);
  51. }
  52. const rowNames = (title: string) =>
  53. section(text, title)
  54. .split("\n")
  55. .filter((line) => line.startsWith("- "))
  56. .flatMap((line) => [...line.replace(/ — .*$/, "").matchAll(/`([a-z0-9-]+)`/g)].map((m) => m[1] as string));
  57. const names = {
  58. skeletons,
  59. skills: rowNames("Skills"),
  60. systems: rowNames("Design systems"),
  61. craft: rowNames("Craft"),
  62. };
  63. const paths = [
  64. ...names.skeletons.map((n) => template(`skeletons\n${skeletonText.split("\n").find((l) => l.startsWith("`design-resources/")) ?? ""}`).replace("<name>", n)),
  65. ...names.skills.map((n) => template(section(text, "Skills")).replace("<name>", n)),
  66. ...names.systems.map((n) => template(section(text, "Design systems")).replace("<name>", n)),
  67. ...names.craft.map((n) => template(section(text, "Craft")).replace("<name>", n)),
  68. ];
  69. return { names, paths };
  70. }
  71. const skeletonRow = (name: string) => {
  72. const category = categories.find((c) => c.members.includes(name)) as Category;
  73. const label = category.prefix ? name.slice(category.prefix.length) : name;
  74. return skeletonText.split("\n").find((line) => line.startsWith(`- \`${label}\``)) ?? "";
  75. };
  76. describe("生成文件的新鲜度与体量", () => {
  77. it("catalog.md 与三份交付物文件的骨架块都与 build-catalog.mjs 的生成结果逐字节一致", () => {
  78. const built = generated();
  79. expect([...built.keys()].sort()).toEqual(["app.md", "catalog.md", "deck.md", "page.md"]);
  80. expect(Object.values(TARGETS).map((t) => (t as { file: string }).file).sort()).toEqual([...built.keys()].sort());
  81. for (const [file, text] of built) {
  82. expect(text, `${file} 过期:运行 node skills/design/scripts/build-catalog.mjs`).toBe(readFileSync(join(referencesDir, file), "utf8"));
  83. }
  84. });
  85. it("生成结果确定:两次相同,无时间戳、绝对路径和 CR;catalog 以单个 LF 结尾;每份交付物文件恰有一对标记", () => {
  86. expect(generated()).toEqual(generated());
  87. for (const text of [committed, skeletonText]) {
  88. expect(text).not.toMatch(/\d{4}-\d{2}-\d{2}|\d{2}:\d{2}:\d{2}/);
  89. expect(text).not.toContain(skillRoot);
  90. expect(text).not.toMatch(/\]\(\/|`\/|\$\{[A-Z_]+\}/);
  91. expect(text).not.toContain("\r");
  92. }
  93. expect(committed.endsWith("\n") && !committed.endsWith("\n\n")).toBe(true);
  94. for (const t of TRACKS) {
  95. expect(trackText[t]?.split(BLOCK_BEGIN).length, t).toBe(2);
  96. expect(trackText[t]?.split(BLOCK_END).length, t).toBe(2);
  97. }
  98. });
  99. it("每份生成目标不超过自己的体量上限和 500 行;超过 100 行时顶部有 Contents", () => {
  100. expect(Object.fromEntries(Object.entries(TARGETS).map(([k, v]) => [k, (v as { maxBytes: number }).maxBytes]))).toEqual({ catalog: 6144, deck: 6144, app: 5120, page: 5120 });
  101. for (const [file, text] of generated()) {
  102. const target = Object.values(TARGETS).find((t) => (t as { file: string }).file === file) as { maxBytes: number };
  103. expect(Buffer.byteLength(text, "utf8"), file).toBeLessThanOrEqual(target.maxBytes);
  104. const lines = text.split("\n").length - 1;
  105. expect(lines, file).toBeLessThanOrEqual(500);
  106. if (lines > 100) expect(text.split("\n").slice(0, 12).some((line) => line.startsWith("Contents: ")), file).toBe(true);
  107. }
  108. });
  109. it("超过上限时非零退出、不写任何文件,并输出分段体量;未超时重写出同样的内容", () => {
  110. const dir = mkdtempSync(join(tmpdir(), "zcode-design-catalog-"));
  111. try {
  112. cpSync(referencesDir, dir, { recursive: true });
  113. const before = Object.fromEntries(readdirSync(dir).map((f) => [f, readFileSync(join(dir, f), "utf8")]));
  114. const run = spawnSync(process.execPath, [script, "--max-bytes=1000", `--dir=${dir}`], { encoding: "utf8", timeout: 20000 });
  115. expect(run.status).toBe(1);
  116. expect(run.stderr).toContain("over the 1000 B cap");
  117. for (const title of ["(head)", "Skills", "Design systems", "Craft", "Deck — specific need", "Dashboard", "App"]) expect(run.stderr, title).toContain(title);
  118. expect(Object.fromEntries(readdirSync(dir).map((f) => [f, readFileSync(join(dir, f), "utf8")]))).toEqual(before);
  119. writeFileSync(join(dir, "app.md"), readFileSync(join(dir, "app.md"), "utf8").replace(/`mobile-app`/, "`stale`"));
  120. const ok = spawnSync(process.execPath, [script, `--dir=${dir}`], { encoding: "utf8", timeout: 20000 });
  121. expect(ok.status).toBe(0);
  122. for (const f of ["catalog.md", "deck.md", "app.md", "page.md"]) expect(readFileSync(join(dir, f), "utf8"), f).toBe(readFileSync(join(referencesDir, f), "utf8"));
  123. } finally {
  124. rmSync(dir, { force: true, recursive: true });
  125. }
  126. });
  127. });
  128. describe("catalog.md 覆盖与对应", () => {
  129. const { names, paths } = listed(committed);
  130. it("每个骨架、技能、设计系统和 craft 都列出或明确排除;列出的每项都能解析到随包文件", () => {
  131. expect(sorted(names.skeletons)).toEqual(sorted(skeletonNames));
  132. expect(names.skeletons).toHaveLength(skeletonNames.length);
  133. expect(sorted([...names.skills, ...CONFIG.skills.exclude])).toEqual(sorted(skillNames));
  134. expect(names.skills.filter((n) => CONFIG.skills.exclude.includes(n))).toEqual([]);
  135. expect(sorted(names.systems)).toEqual(sorted(systemNames));
  136. expect(sorted(names.craft)).toEqual(sorted(craftNames));
  137. expect(paths.length).toBeGreaterThan(100);
  138. expect(paths.filter((path) => !existsSync(join(skillRoot, ...path.split("/"))))).toEqual([]);
  139. });
  140. it("配置里的每个名称都对应真实资源", () => {
  141. const skeletonRefs = [
  142. ...categories.flatMap((c) => c.members),
  143. ...CONFIG.nameOnly,
  144. ...Object.keys(CONFIG.override),
  145. ...CONFIG.notes.flatMap((n: { names: string[] }) => n.names),
  146. ...CONFIG.missing.flatMap((m: { usedBy: string[] }) => m.usedBy),
  147. ];
  148. expect(skeletonRefs.filter((n) => !skeletonNames.includes(n))).toEqual([]);
  149. expect(excluded.filter((n) => !allSkeletonNames.includes(n))).toEqual([]);
  150. const skillRefs = [...CONFIG.skills.exclude, ...Object.keys(CONFIG.skills.override), ...CONFIG.nameMismatch];
  151. expect(skillRefs.filter((n) => !skillNames.includes(n))).toEqual([]);
  152. const systemRefs = [...Object.keys(CONFIG.systemNotes), ...Object.keys(CONFIG.systemOverride)];
  153. expect(systemRefs.filter((n) => !systemNames.includes(n))).toEqual([]);
  154. const craftRefs = [...CONFIG.craftBaseline, ...CONFIG.craftConditional, ...Object.values(CONFIG.craftAlias as Record<string, string>), ...categories.flatMap((c) => c.craft)];
  155. expect(craftRefs.filter((n) => !craftNames.includes(n))).toEqual([]);
  156. // 未随包的名字一旦随包,丢弃表和别名表就过期了。
  157. expect([...CONFIG.craftDrop, ...Object.keys(CONFIG.craftAlias)].filter((n) => craftNames.includes(n))).toEqual([]);
  158. // 每条注记挂在同一类别下。
  159. for (const note of CONFIG.notes as { names: string[] }[]) {
  160. const keys = new Set(note.names.map((n) => categories.find((c) => c.members.includes(n))?.key));
  161. expect(keys.size, note.names.join(",")).toBe(1);
  162. }
  163. });
  164. it("每个骨架恰好属于一个类别;设计系统的 Category 都在分组表里;craft 目录等于 CONFIG.craft 的键", () => {
  165. const members = categories.flatMap((c) => c.members);
  166. expect(sorted(members)).toEqual(sorted(skeletonNames));
  167. expect(members).toHaveLength(skeletonNames.length);
  168. const unknown = systemNames.filter((n) => !(resources.systems.get(n).category in CONFIG.systemGroups)).map((n) => `${n}: ${resources.systems.get(n).category}`);
  169. expect(unknown).toEqual([]);
  170. expect(sorted(Object.keys(CONFIG.craft))).toEqual(sorted(craftNames));
  171. });
  172. it("骨架声明的 craft 都能解析:在 craft/、别名、丢弃或条件表里", () => {
  173. const unresolved: string[] = [];
  174. for (const [name, { frontmatter }] of resources.skeletons) {
  175. for (const craft of frontmatter.od?.craft?.requires ?? []) {
  176. const target = resolveCraft(craft);
  177. if (target !== null && !craftNames.includes(target)) unresolved.push(`${name}: ${craft}`);
  178. }
  179. }
  180. expect(unresolved).toEqual([]);
  181. });
  182. });
  183. describe("design-resources 输入数据质量", () => {
  184. const files = [
  185. ...skeletonNames.map((n) => ({ dir: n, file: join(resourceRoot, "design-skeletons", n, "SKILL.md") })),
  186. ...skillNames.map((n) => ({ dir: n, file: join(resourceRoot, "skills", n, "SKILL.md") })),
  187. ];
  188. it("每个 SKILL.md 有 frontmatter,name 等于目录名(已知例外除外),description 非空,triggers 是字符串数组", () => {
  189. expect(files.length).toBeGreaterThan(75);
  190. const problems: string[] = [];
  191. for (const { dir, file } of files) {
  192. const raw = splitFrontmatter(readFileSync(file, "utf8"));
  193. if (raw === null) {
  194. problems.push(`${dir}: no frontmatter`);
  195. continue;
  196. }
  197. const fm = parseFrontmatter(raw);
  198. if ((fm.name === dir) === CONFIG.nameMismatch.includes(dir)) problems.push(`${dir}: name ${fm.name}`);
  199. if (typeof fm.description !== "string" || fm.description.trim() === "") problems.push(`${dir}: description`);
  200. if (fm.triggers !== undefined && !(Array.isArray(fm.triggers) && fm.triggers.every((t: unknown) => typeof t === "string"))) {
  201. problems.push(`${dir}: triggers`);
  202. }
  203. }
  204. expect(problems).toEqual([]);
  205. });
  206. it("描述首句被截断(不足 20 字符或以 — / : 结尾,如 YAML 把 ` #` 当注释)时必须有覆盖句", () => {
  207. const suspicious = (description: string) => {
  208. const sentence = firstSentence(description);
  209. return [...sentence].length < 20 || /[—:]$/.test(sentence);
  210. };
  211. const bad = [
  212. ...[...resources.skeletons].filter(([n, { frontmatter }]) => !(n in CONFIG.override) && suspicious(frontmatter.description)),
  213. ...[...resources.skills].filter(([n, { frontmatter }]) => !(n in CONFIG.skills.override) && suspicious(frontmatter.description)),
  214. ].map(([n]) => n);
  215. expect(bad).toEqual([]);
  216. expect(suspicious(resources.skeletons.get("html-ppt-hermes-cyber-terminal").frontmatter.description)).toBe(true);
  217. });
  218. describe("frontmatter 解析器", () => {
  219. it("块标量、折叠标量、跨行流式列表、列表里的映射、行内注释", () => {
  220. const fm = parseFrontmatter(
  221. [
  222. "name: demo",
  223. "description: |",
  224. " First line.",
  225. " Second line.",
  226. "summary: >",
  227. " folded",
  228. " text",
  229. "triggers:",
  230. ' - "quoted, with comma"',
  231. " - bare words",
  232. "od:",
  233. " craft:",
  234. " requires: [typography, color,",
  235. " laws-of-ux]",
  236. " default: 198 # Notion-blue",
  237. " note: dark #0a0c10 canvas",
  238. " inputs:",
  239. " - name: title",
  240. " type: string",
  241. " design_system:",
  242. " requires: false",
  243. ].join("\n"),
  244. );
  245. expect(fm.description).toBe("First line.\nSecond line.");
  246. expect(fm.summary).toBe("folded text");
  247. expect(fm.triggers).toEqual(["quoted, with comma", "bare words"]);
  248. expect(fm.od.craft.requires).toEqual(["typography", "color", "laws-of-ux"]);
  249. expect(fm.od.default).toBe(198);
  250. expect(fm.od.note).toBe("dark");
  251. expect(fm.od.inputs).toEqual([{ name: "title", type: "string" }]);
  252. expect(fm.od.design_system.requires).toBe(false);
  253. });
  254. it("兼容 CRLF 与 BOM", () => {
  255. const text = "\uFEFF---\r\nname: demo\r\ndescription: |\r\n a\r\n b\r\n---\r\nbody\r\n";
  256. const raw = splitFrontmatter(text);
  257. expect(raw).not.toBeNull();
  258. expect(parseFrontmatter(raw)).toEqual({ name: "demo", description: "a\nb" });
  259. expect(splitFrontmatter("# no frontmatter\n")).toBeNull();
  260. });
  261. it("不认识的构造直接抛错,不静默跳过", () => {
  262. 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"]) {
  263. expect(() => parseFrontmatter(source), source).toThrow();
  264. }
  265. });
  266. });
  267. });
  268. describe("catalog.md 内容", () => {
  269. it("hermes 行用覆盖句而不是被 YAML 截断的描述;broadside 行带 editorial", () => {
  270. const hermes = skeletonRow("html-ppt-hermes-cyber-terminal");
  271. expect(hermes).toContain(CONFIG.override["html-ppt-hermes-cyber-terminal"]);
  272. expect(hermes).not.toMatch(/deck —\s*(\[|$)/);
  273. expect(skeletonRow("html-ppt-zhangzara-broadside")).toContain("editorial");
  274. });
  275. it("缺文件警示仍然成立:被点名的文件依旧未随包,写在被引用骨架所在那一档的块里", () => {
  276. for (const { label, paths, usedBy, inline } of CONFIG.missing as Missing[]) {
  277. const track = (categories.find((c) => c.members.includes(usedBy[0] as string)) as Category & { track: string }).track;
  278. // label 走那一档末尾的合并警示句,inline 走骨架自己那一行;两种恰有一种。
  279. expect(Boolean(label) !== Boolean(inline), usedBy.join(",")).toBe(true);
  280. if (label) expect(blockOf(trackText[track] as string), label).toContain(label);
  281. if (inline) for (const name of usedBy) expect(skeletonRow(name), name).toContain(inline);
  282. for (const path of paths) {
  283. expect(existsSync(join(resourceRoot, ...path.split("/"))), `${path} 已随包,更新 CONFIG.missing`).toBe(false);
  284. }
  285. }
  286. });
  287. // ai-assistant-mobile-dashboard 还按 Zwork 原样按分节引用已删除的 OUTPUT_RULES / DESIGN.md、端内 MEDIA: 预览和 审美相关skill/ 路径,
  288. // 并要求读不到就中止。资源层改不了,只能在规则层作废:说明挂在它自己那一行,不让整条 page 路线都付这份上下文。
  289. it("按分节引用已删除规则文件的骨架,作废说明就在自己那一行,且指向随包的文件", () => {
  290. const stale = /OUTPUT_RULES|审美相关skill|MEDIA:|DESIGN(\.md)? §/;
  291. const citing = skeletonNames.filter((n) => stale.test(readFileSync(join(resourceRoot, "design-skeletons", n, "SKILL.md"), "utf8")));
  292. const covered = (CONFIG.missing as Missing[]).filter((m) => m.inline).flatMap((m) => m.usedBy);
  293. expect(citing).toContain("ai-assistant-mobile-dashboard");
  294. expect(sorted(citing), "骨架引用了已删除的规则文件却没有作废说明:补 CONFIG.missing 的 inline").toEqual(sorted(covered));
  295. for (const { inline } of (CONFIG.missing as Missing[]).filter((m) => m.inline)) {
  296. // 说明必须真的作废(不读/不认领)并给出去处,而去处必须是随包的文件。
  297. expect(inline).toMatch(/not shipped/);
  298. expect(inline).toMatch(/never claim/);
  299. const links = [...(inline as string).matchAll(/\[[^\]]+\]\(([^)]+)\)/g)].map((m) => m[1] as string);
  300. expect(links.length).toBeGreaterThan(0);
  301. for (const href of links) expect(existsSync(join(referencesDir, href)), href).toBe(true);
  302. }
  303. });
  304. it("open-design-landing-deck 不承诺缺失的同伴文件;gstack 三个方法型技能不再列出", () => {
  305. const note = skeletonText.split("\n").find((line) => line.startsWith("- Note, `open-design-landing-deck`")) ?? "";
  306. for (const phrase of ["`scripts/compose.ts`", "not shipped", "`schema.ts`", "do not run"]) expect(note, phrase).toContain(phrase);
  307. for (const name of ["design-review", "plan-design-review", "design-consultation"]) {
  308. expect(committed + skeletonText, name).not.toContain(`\`${name}\``);
  309. }
  310. expect(skillNames).toEqual(expect.arrayContaining(["design-review", "plan-design-review", "design-consultation"]));
  311. });
  312. it("依赖 Open Design 运行时的四个骨架不出现在任何生成块里,并写明未列出的目录不能用", () => {
  313. expect(sorted(excluded)).toEqual(sorted(["live-artifact", "live-dashboard", "hyperframes", "video-shortform"]));
  314. for (const name of excluded) expect(skeletonText, name).not.toContain(`\`${name}\``);
  315. for (const track of TRACKS) expect(blockOf(trackText[track] as string), track).toContain("Folders not listed need a runtime this host lacks");
  316. });
  317. it("craft 节把 animation-discipline 和 references/motion.md 配对,并写明冲突时以 motion 为准", () => {
  318. const row = committed.split("\n").find((line) => line.startsWith("- `animation-discipline`")) ?? "";
  319. expect(row).toContain("[references/motion.md](motion.md)");
  320. expect(row).toMatch(/wins where/);
  321. expect(existsSync(join(skillRoot, "references", "motion.md"))).toBe(true);
  322. });
  323. it("设计系统节首行链接 BRAND-DISCLAIMER.md;kami 注明只经 kami-* 骨架选择", () => {
  324. const systems = section(committed, "Design systems");
  325. const first = systems.split("\n")[1] as string;
  326. expect(first).toContain("[BRAND-DISCLAIMER.md](../design-resources/design-systems/BRAND-DISCLAIMER.md)");
  327. expect(existsSync(join(resourceRoot, "design-systems", "BRAND-DISCLAIMER.md"))).toBe(true);
  328. expect(systems).toMatch(/`kami` \(only via kami-\* skeletons\)/);
  329. });
  330. it("no example 标记的集合等于磁盘上没有 example.html 的骨架集合", () => {
  331. const marked = skeletonNames.filter((n) => /\[[^\]]*no example[^\]]*\]$/.test(skeletonRow(n)));
  332. const missing = skeletonNames.filter((n) => !existsSync(join(resourceRoot, "design-skeletons", n, "example.html")));
  333. expect(missing.length).toBeGreaterThan(0);
  334. expect(sorted(marked)).toEqual(sorted(missing));
  335. expect(readdirSync(join(resourceRoot, "design-skeletons")).length).toBe(allSkeletonNames.length);
  336. });
  337. });