dynamic-workflow-skill.test.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. // ============================================================
  2. // bundled-skills: builtin /workflow command + dynamic-workflows skill tripwire
  3. // ============================================================
  4. // 契约见 docs/dynamic-workflow/authoring.md「The `/workflow` command and the skill」。
  5. //
  6. // 这套断言守的是一件事:**技能正文与 facade 同步,且 facade 只出现一次**。2026-09-21 起 facade 的
  7. // .d.ts 不再随 CreateWorkflow 的描述每次请求重发(那是约 4.4k token),而是逐字嵌在 SKILL.md
  8. // §16.2 的标记块里,由 resolveInput 上的技能门保证模型写脚本之前读过。标记块之外的正文不得再抄
  9. // 任何一段签名——第二份必然漂移。因此这里(1)钉住标记块与 FACADE_DTS 逐字相等,(2)从
  10. // FACADE_DTS 派生正文允许的成员集合——facade 一改,本文件就红,而不是让正文默默烂掉。
  11. //
  12. // 另有一条负向断言:另一套常见的 Workflow 工具 API(pipeline/parallel/
  13. // budget.total…)与本 facade 形近而实不同。它的词汇一旦漏进正文,模型会写出编译不过的脚本,且诊断信息
  14. // 指向的是"不存在的标识符"而非"你用错了 API",极难自查。`phase` 是这份名单里唯一被撤下的:
  15. // dwf 自己有了 `phase("名字")` 阶段标注(docs/dynamic-workflow/presentation.md),黑名单
  16. // 因此变成假阳性,改由「marker 形态」正向断言接管。
  17. //
  18. // 2026-09-21 起命令与技能都不再随 zcode-guide 插件发布:命令编进 CLI(builtin-workflow-command.ts),
  19. // 技能进 packages/bundled-skills(bundled-skills.ts)。插件一被卸载/停用,入口就整体消失的事故形态
  20. // 由此关闭;本文件同时钉住两件资产的新住址。
  21. import { readFile } from "node:fs/promises";
  22. import { tmpdir } from "node:os";
  23. import { join } from "node:path";
  24. import { fileURLToPath } from "node:url";
  25. import { createNodeSkillAdapter } from "@zcode/adapters/skills";
  26. import type { SkillRoot } from "@zcode/contracts";
  27. import { analyzeWorkflowScript, compileWorkflowScript, FACADE_DTS } from "@zcode/dynamic-workflow";
  28. import { describe, expect, it } from "vitest";
  29. import {
  30. BUNDLED_SKILL_PACK_REQUIRED_PATHS,
  31. DYNAMIC_WORKFLOW_SKILL_NAME,
  32. resolveBundledSkillRoots,
  33. } from "../src/app/bundled-skills.js";
  34. import { collectDynamicWorkflowDisabledSkillPaths } from "../src/app/dynamic-workflow-gate.js";
  35. import {
  36. resolveZCodeBuiltinPromptCommand,
  37. resolveZCodeBuiltinPromptCommandInvocation,
  38. } from "../src/builtin-prompt-command.js";
  39. import {
  40. BUILTIN_WORKFLOW_COMMAND,
  41. BUILTIN_WORKFLOW_COMMAND_NAME,
  42. expandBuiltinWorkflowCommandPrompt,
  43. } from "../src/builtin-workflow-command.js";
  44. const PACKAGES_ROOT = fileURLToPath(new URL("../../", import.meta.url));
  45. const PACK_ROOT = join(PACKAGES_ROOT, "bundled-skills");
  46. const SKILL_NAME = DYNAMIC_WORKFLOW_SKILL_NAME;
  47. const SKILL_DIR = join(PACK_ROOT, "skills", SKILL_NAME);
  48. /** zcode-guide 仍是一个普通插件技能根:用来证明灰度门不会连坐技能包之外的技能。 */
  49. const GUIDE_PLUGIN_SKILLS_ROOT = join(PACKAGES_ROOT, "zcode-guide-plugin", "skills");
  50. /** 技能正文三件套:SKILL.md 常驻,另两份由模型按需 Read。 */
  51. const SKILL_FILES = ["SKILL.md", "patterns.md", "examples.md"] as const;
  52. /** adapters/src/skills/index.ts:20 —— 超长直接丢弃技能,不是警告。 */
  53. const MAX_DESCRIPTION_LENGTH = 1024;
  54. /** core/src/context/sections/skills.ts:10 —— 会话清单里每条描述只露出这么多字符。 */
  55. const LISTING_DESCRIPTION_CHARS = 250;
  56. /**
  57. * core/src/tool/handlers/skill.ts 的 WORKFLOW_SKILL_MAX_BYTES —— 这份技能专有的上限(其余技能是
  58. * 100 000)。超出即截断,而截掉的会是 §16 的契约。
  59. */
  60. const SKILL_TOOL_MAX_BYTES = 200_000;
  61. /** SKILL.md §16.2 里逐字嵌入 FACADE_DTS 的标记块。 */
  62. const FACADE_BLOCK_START = "<!-- facade-dts:start -->";
  63. const FACADE_BLOCK_END = "<!-- facade-dts:end -->";
  64. const FACADE_BLOCK_PATTERN = /<!-- facade-dts:start -->[\s\S]*?<!-- facade-dts:end -->/g;
  65. /** 负向断言(declare / phase 形态 / 外来词汇)看的是正文,不看那一块 ambient 声明。 */
  66. function stripFacadeBlock(text: string): string {
  67. return text.replace(FACADE_BLOCK_PATTERN, "");
  68. }
  69. async function readSkillFile(name: string): Promise<string> {
  70. return readFile(join(SKILL_DIR, name), "utf8");
  71. }
  72. async function readAllContent(): Promise<{ name: string; text: string }[]> {
  73. const skills = await Promise.all(
  74. SKILL_FILES.map(async (name) => ({ name, text: stripFacadeBlock(await readSkillFile(name)) })),
  75. );
  76. return [...skills, { name: "builtin /workflow", text: BUILTIN_WORKFLOW_COMMAND.content }];
  77. }
  78. /** 抽 `---` 包裹的 flat frontmatter;解析规则对齐 adapters 的 parseFlatYaml(只认顶层标量)。 */
  79. function parseFlatFrontmatter(text: string): Record<string, string> {
  80. const lines = text.split(/\r?\n/);
  81. if (lines[0] !== "---") return {};
  82. const end = lines.indexOf("---", 1);
  83. if (end === -1) return {};
  84. const entries: Record<string, string> = {};
  85. for (const line of lines.slice(1, end)) {
  86. if (/^\s/.test(line)) continue;
  87. const separator = line.indexOf(":");
  88. if (separator === -1) continue;
  89. const key = line.slice(0, separator).trim();
  90. const raw = line.slice(separator + 1).trim();
  91. entries[key] = raw.replace(/^"(.*)"$/s, "$1").replace(/^'(.*)'$/s, "$1");
  92. }
  93. return entries;
  94. }
  95. describe("builtin /workflow command", () => {
  96. it("declares the skill it depends on and passes the user's request through", () => {
  97. // skills: 会让 contracts 的 formatCommandSkillInstructions 生成 "先调 Skill 工具" 前置指令。
  98. // 名字写错不会报错,只会静默失去技能加载——所以钉住它等于技能目录名。
  99. expect(BUILTIN_WORKFLOW_COMMAND.metadata.name).toBe(BUILTIN_WORKFLOW_COMMAND_NAME);
  100. expect(BUILTIN_WORKFLOW_COMMAND.metadata.skills).toEqual([SKILL_NAME]);
  101. expect(BUILTIN_WORKFLOW_COMMAND.metadata.description).toBeTruthy();
  102. expect(BUILTIN_WORKFLOW_COMMAND.metadata.argumentHint).toBeTruthy();
  103. // 没有 $ARGUMENTS 时 expandCustomCommandTemplate 会把参数追加成 "User arguments:" 尾块,
  104. // 位置不受控;命令的正文要自己决定用户请求落在哪。
  105. expect(BUILTIN_WORKFLOW_COMMAND.content).toContain("$ARGUMENTS");
  106. const prompt = expandBuiltinWorkflowCommandPrompt("ship the release");
  107. expect(prompt).toContain(`Required skills: \`${SKILL_NAME}\`.`);
  108. expect(prompt).toContain(`call the Skill tool for \`${SKILL_NAME}\``);
  109. expect(prompt).toContain("ship the release");
  110. expect(prompt).toContain("`CreateWorkflow`");
  111. expect(prompt).not.toContain("$ARGUMENTS");
  112. });
  113. it("expands through the builtin prompt resolver, and not while the gray gate is off", () => {
  114. // DWG-03:目录侧剔除了它,但用户仍可手打命令名,两条路径必须给出同一个结论。
  115. expect(resolveZCodeBuiltinPromptCommand("/workflow ship it")).toContain("ship it");
  116. expect(
  117. resolveZCodeBuiltinPromptCommand("/workflow ship it", { dynamicWorkflowEnabled: true }),
  118. ).toContain("ship it");
  119. expect(
  120. resolveZCodeBuiltinPromptCommand("/workflow ship it", { dynamicWorkflowEnabled: false }),
  121. ).toBe(undefined);
  122. // 无参数也展开:模型会按技能自行向用户要任务,而不是把 "/workflow" 当普通文本。
  123. expect(resolveZCodeBuiltinPromptCommand("/workflow")).toContain("Required skills");
  124. expect(resolveZCodeBuiltinPromptCommand("please /workflow now")).toBe(undefined);
  125. });
  126. // launch.md「On demand: activation」:装配层要知道展开的是哪个命令,才能在 `/workflow` 上挂激活。
  127. it("invocation 形态带命令名", () => {
  128. expect(resolveZCodeBuiltinPromptCommandInvocation("/workflow ship it")).toMatchObject({
  129. name: BUILTIN_WORKFLOW_COMMAND_NAME,
  130. });
  131. expect(resolveZCodeBuiltinPromptCommandInvocation("/WORKFLOW ship it")?.name).toBe(
  132. BUILTIN_WORKFLOW_COMMAND_NAME,
  133. );
  134. expect(resolveZCodeBuiltinPromptCommandInvocation("/init")?.name).toBe("init");
  135. expect(
  136. resolveZCodeBuiltinPromptCommandInvocation("/workflow x", { dynamicWorkflowEnabled: false }),
  137. ).toBeUndefined();
  138. expect(resolveZCodeBuiltinPromptCommandInvocation("/unknown")).toBeUndefined();
  139. });
  140. });
  141. describe("bundled dynamic-workflows skill", () => {
  142. it("loads: name matches the directory, description fits the loader's cap", async () => {
  143. const frontmatter = parseFlatFrontmatter(await readSkillFile("SKILL.md"));
  144. expect(frontmatter.name).toBe(SKILL_NAME);
  145. expect(frontmatter.description).toBeTruthy();
  146. expect(frontmatter.description.length).toBeLessThan(MAX_DESCRIPTION_LENGTH);
  147. // 自动触发只看得见前 250 字符,所以触发词必须前置——而且必须是 CreateWorkflow 这个专名,
  148. // 不能是泛泛的 "multi-agent":后者会在 Agent 工具才是正解的场合把模型拽向 workflow。
  149. expect(frontmatter.description.slice(0, LISTING_DESCRIPTION_CHARS)).toContain("CreateWorkflow");
  150. });
  151. it("ships every file the pack contract pins, and the pack pins every file shipped", async () => {
  152. const contents = await Promise.all(SKILL_FILES.map((name) => readSkillFile(name)));
  153. for (const text of contents) expect(text.length).toBeGreaterThan(0);
  154. // 双向对齐:技能目录里的每个文件都是必需资产(bundled-skills.ts 缺一拒绝整包),
  155. // 契约里也不得残留已不存在的文件(否则 stage/SEA 构建永远失败)。
  156. const pinned = new Set(BUNDLED_SKILL_PACK_REQUIRED_PATHS);
  157. for (const name of SKILL_FILES) expect(pinned).toContain(`skills/${SKILL_NAME}/${name}`);
  158. expect(pinned.size).toBe(SKILL_FILES.length);
  159. });
  160. it("embeds the facade verbatim, once, and stays under the Skill tool's byte cap", async () => {
  161. const skill = await readSkillFile("SKILL.md");
  162. // docs/dynamic-workflow/authoring.md「The authoring surface」:标记块里是编译器吃的同一个常量,
  163. // 逐字相等——模型读到的契约不可能漂离能编译过的东西。
  164. const block = `${FACADE_BLOCK_START}\n\`\`\`ts\n${FACADE_DTS.trim()}\n\`\`\`\n${FACADE_BLOCK_END}`;
  165. expect(skill.split(block)).toHaveLength(2);
  166. expect(skill.match(FACADE_BLOCK_PATTERN)).toHaveLength(1);
  167. // 技能是 Skill 工具一次性返回的正文;超过上限会被从尾部截掉,而 §16 正在尾部。
  168. expect(Buffer.byteLength(skill, "utf8")).toBeLessThan(SKILL_TOOL_MAX_BYTES);
  169. });
  170. it("carries the contract the tool descriptions used to carry", async () => {
  171. // 描述收短后,这些句子只活在这里(core/tests/workflow-routing-hints.test.ts 钉的是描述那一侧)。
  172. const skill = await readSkillFile("SKILL.md");
  173. expect(skill).toContain("## 16. Tool reference");
  174. expect(skill).toContain("refuses\nto run until this skill has been loaded");
  175. expect(skill).toContain("**Three sources; pass exactly one.**");
  176. expect(skill).toContain(
  177. "Running a saved workflow\n is the one call that does not need this skill loaded",
  178. );
  179. expect(skill).toContain("`max_concurrency`");
  180. expect(skill).toContain("`subagent_model`");
  181. expect(skill).toContain("do not imitate it");
  182. expect(skill).toContain("Never use the `declare` modifier");
  183. expect(skill).toContain("`noUncheckedIndexedAccess` off");
  184. expect(skill).toContain("needs no guard");
  185. expect(skill).toContain("No `export` statements");
  186. expect(skill).toContain("No `import` statements");
  187. expect(skill).toContain("compile-time string\n literal");
  188. expect(skill).toContain("standalone\n statement");
  189. expect(skill).toContain("Two markers\n with the same name are one phase");
  190. expect(skill).toContain("unique within the\n run");
  191. expect(skill).toContain("Model-side errors never reach the script");
  192. expect(skill).toContain("`ContextLimit`");
  193. expect(skill).toContain("Never put the same content in both");
  194. expect(skill).toContain("never\n paste the script a second time");
  195. expect(skill).toContain("### 16.4 `AmendWorkflow`");
  196. expect(skill).toContain("`script_unchanged`");
  197. // 沿用规则按固定顺序:脚本先(两个来源字段都不给)、并发、子代理模型;就地调并发那一句紧贴并发
  198. // 字段(docs/dynamic-workflow/launch.md「What the model is told」,2026-09-21 起由技能承载)。
  199. const amend = skill.slice(skill.indexOf("### 16.4 `AmendWorkflow`"), skill.indexOf("### 16.5"));
  200. const keptScript = amend.indexOf("Omit both to keep the predecessor's script");
  201. const limit = amend.indexOf("- `max_concurrency`: omit to keep the predecessor's limit");
  202. const inPlace = amend.indexOf("retunes that run in place");
  203. const model = amend.indexOf("- `subagent_model`: omit to keep the predecessor's choice");
  204. expect(keptScript).toBeGreaterThan(-1);
  205. expect(keptScript).toBeLessThan(limit);
  206. expect(limit).toBeLessThan(inPlace);
  207. expect(inPlace).toBeLessThan(model);
  208. expect(amend).toContain("`path` or `script`, never both. `path` is the usual form");
  209. expect(skill).toContain("picks that\nask up where it left off");
  210. // 缓存的精确规则(docs/dynamic-workflow/launch.md「What the model is told」):首次写工作区之后,只有
  211. // 读过/跑过的子代理的 ask 转为实跑,只作答的 ask 继续命中。§13 曾把它说成「之后一切都实跑」,与
  212. // 描述矛盾;描述收短后技能是唯一出处,两处必须同一个说法。
  213. expect(skill).toContain("**How the cache works.**");
  214. expect(skill).toContain("Asks that only\nanswered keep settling from the cache");
  215. expect(skill).not.toContain(
  216. "every ask to any subagent runs live even if its text is unchanged",
  217. );
  218. expect(skill).toContain("### 16.5 `SaveWorkflow`");
  219. expect(skill).toContain("Never unsolicited");
  220. expect(skill).toContain("`script_path`");
  221. expect(skill).toContain("### 16.6 `EvalWorkflowSnippet`");
  222. expect(skill).toContain("do not exist here and\n fail typechecking");
  223. });
  224. it("never restates the facade outside its marked block", async () => {
  225. for (const { name, text } of await readAllContent()) {
  226. // 标记块(§16.2)是唯一的 ambient 声明来源。正文里再出现 `declare ` 意味着抄了一份签名进来,
  227. // 也意味着模型会看到两份、且其中一份会漂移。
  228. expect(text, name).not.toMatch(/\bdeclare\s/);
  229. // RULES 已经禁掉这三样;示例里出现就是在示范违规。
  230. expect(text, name).not.toMatch(/^\s*import\s/m);
  231. expect(text, name).not.toMatch(/^\s*export\s/m);
  232. }
  233. });
  234. it("mentions only facade members that actually exist", async () => {
  235. for (const { name, text } of await readAllContent()) {
  236. for (const [, container, member] of text.matchAll(
  237. // artifact 加入扫描面:产物成员名(file/markdown/chart/table/metrics/board)里有四个
  238. // 是普通英文词,正文写错一个字母不会像 `glob` 那样显眼。`artifact.*` 这种散文写法
  239. // 匹配不到(`*` 不是标识符首字符),所以只有真调用会被查。
  240. /\b(artifact|files|git|world)\.([A-Za-z_$][\w$]*)/g,
  241. )) {
  242. expect(FACADE_DTS, `${name}: ${container}.${member}`).toContain(`${member}(`);
  243. }
  244. }
  245. });
  246. it("teaches world.run and the EvalWorkflowSnippet pre-flight (amendment 1)", async () => {
  247. // docs/dynamic-workflow/authoring.md「The skill」:确定性门控归 world.run、片段预检归
  248. // EvalWorkflowSnippet。正文丢了任何一个,指导面就静默塌回「一切效应都外包给 actor」。
  249. const skill = await readSkillFile("SKILL.md");
  250. expect(skill).toContain("world.run");
  251. expect(skill).toContain("EvalWorkflowSnippet");
  252. const patterns = await readSkillFile("patterns.md");
  253. expect(patterns).toContain("world.run");
  254. });
  255. // docs/dynamic-workflow/authoring.md「The guidance」。产物是 run 交给用户的唯一通道,而
  256. // facade 只给签名:不写进 §9,模型会继续把子代理产出的 pdf 留在工作区,或者把同一段
  257. // markdown 同时塞进 return 和产物。三条正向断言分别钉住三种成员的判断依据。
  258. it("teaches artifact delivery: file, markdown and the report-fed dashboard (amendment 6)", async () => {
  259. const skill = await readSkillFile("SKILL.md");
  260. expect(skill).toContain("**Deliver artifacts.**");
  261. expect(skill).toContain('report(item, "perf")');
  262. expect(skill).toContain("compile-time string literals");
  263. // 拒绝是可接的,而且拒绝那一刻正是把缺口交回子代理的时机——产物族里唯一的控制流教学点。
  264. expect(skill).toContain("reject catchably");
  265. });
  266. it("teaches no persona knob: neither a tool profile nor a model tier (amendments 7–8)", async () => {
  267. // docs/dynamic-workflow/authoring.md:`tools` 与模型档位都已退场。技能正文里再出现任何一个,
  268. // 就是在教一个编译不过的成员;「只读」的说法也一并禁掉——每个子代理都有完整工作工具集,
  269. // 不改文件是 ask 说的,不是档位保证的。2026-09-26 起 persona 可以点名一个**具体**模型
  270. // (「Choosing a model per subagent」),所以 `model:` 本身合法,被禁的只是档位词。
  271. for (const { name, text } of await readAllContent()) {
  272. expect(text, `${name}: persona tools`).not.toMatch(/\btools:\s*"/);
  273. expect(text, `${name}: persona model tier`).not.toMatch(
  274. /\bmodel:\s*"(lite|main|fast|strong)"/,
  275. );
  276. // `"none"` 不在表里:`let feedback = "none"` 这类普通字符串是合法示例。
  277. expect(text, `${name}: tool profile vocabulary`).not.toMatch(
  278. /ToolProfile|"readonly"|read-only subagent/,
  279. );
  280. }
  281. });
  282. // docs/dynamic-workflow/authoring.md「The skill」:流水线是默认姿态——每个条目一做完就进下一阶段,
  283. // 只有下一步需要全部条目的地方才等齐。2026-09-30 之前 §7 以「只在数据需要全体时 join」立题,
  284. // 读起来像「少设屏障」,而不是「默认流水线」;模型写出的脚本于是一阶段一屏障。
  285. it("teaches pipelining as the default and a join as the exception", async () => {
  286. const skill = await readSkillFile("SKILL.md");
  287. expect(skill).toContain(
  288. "## 7. Pipeline by default; join only where the next step needs every item",
  289. );
  290. expect(skill).toContain("each item moves on the moment it is ready");
  291. expect(skill).toContain("**Decide, at every hand-off, how an item leaves its stage:**");
  292. expect(skill).toContain("a join, with a comment saying what needs every item");
  293. // §2 把它列为拓扑决策之一,§3 把它列入提交前自查。
  294. expect(skill).toContain("**Where each item goes next.**");
  295. expect(skill).toContain("at every `Promise.all`\nask whether the next step needs every item");
  296. const patterns = await readSkillFile("patterns.md");
  297. expect(patterns).toContain("**Start with the pipeline shapes.**");
  298. expect(patterns).toContain("## 6. Staged handoff with typed results");
  299. // 路由模式(#13)曾是两道屏障:先全部分诊,再全部作答。分诊与作答一对一,所以按条串起来。
  300. expect(patterns).not.toContain('phase("Decide which model each question needs")');
  301. expect(patterns).toContain(
  302. 'phase("Route each question to the model it needs and answer it there")',
  303. );
  304. });
  305. // docs/dynamic-workflow/authoring.md「Choosing a model per subagent」:两种写法、一个路由模式,
  306. // 技能正文与 patterns.md 各钉一处;路由脚本本身带 `<!-- compile -->`,由下面的编译守卫验。
  307. it("teaches the per-subagent model: a literal, a model() table, and routing by a typed key", async () => {
  308. const skill = await readSkillFile("SKILL.md");
  309. expect(skill).toContain("**Per-subagent model**");
  310. expect(skill).toContain('agent("judge", { model: "GLM-5.3-Flash" })');
  311. expect(skill).toContain("`ListModels`");
  312. expect(skill).toContain("(`patterns.md` #13)");
  313. const patterns = await readSkillFile("patterns.md");
  314. expect(patterns).toContain("## 13. Model routing");
  315. expect(patterns).toContain("model: MODELS[route.tier]");
  316. });
  317. it("does not leak the other Workflow API's vocabulary", async () => {
  318. // 这些标识符属于另一套 Workflow 工具 API,不属于本 facade。漏进来的后果是脚本编译不过,
  319. // 而诊断只会说"找不到 pipeline",读起来像 facade 缺功能,而不像"你记错了是哪套 API"。
  320. const foreign = [
  321. /\bpipeline\(/,
  322. /\bparallel\(/,
  323. // 已删除的 run 级 `budget` 全局(remainingTokens / remainingNodes)与另一套 API 的同名读法不该
  324. // 出现。persona 的 `budget: { webSearch }`(authoring.md「A subagent's search budget」)是合法
  325. // 写法,所以只禁这些读法,不再禁整个词。
  326. /\bbudget\s*\(/,
  327. /\bbudget\.remaining/,
  328. /\bremaining(Tokens|Nodes)\b/,
  329. /\bdeclare const budget\b/,
  330. /\bagentType\b/,
  331. /\bisolation:/,
  332. /\beffort:/,
  333. /\bschema:/,
  334. ];
  335. for (const { name, text } of await readAllContent()) {
  336. for (const pattern of foreign) {
  337. expect(text, `${name}: ${String(pattern)}`).not.toMatch(pattern);
  338. }
  339. }
  340. });
  341. it("uses phase() in the dwf marker form, never the other Workflow API's", async () => {
  342. // `phase(` 曾在上面的 foreign 名单里(两套 API 都有 phase),dwf 补上阶段标注后它成了
  343. // 真 facade 成员,黑名单变成假阳性,把唯一的分组教学面挡在门外。改成正向断言:出现即
  344. // 必须是 marker 形态 `phase("字面量")`。两套 API 的调用形状几乎同形,所以真正的判别力
  345. // 在别处——同组 foreign 项(pipeline/parallel/schema:…)仍在,且下面的编译守卫会让
  346. // 任何非 dwf 的 phase 用法在真编译器上炸掉。
  347. for (const { name, text } of await readAllContent()) {
  348. for (const [call] of text.matchAll(/\bphase\([^)]*\)/g)) {
  349. expect(call, `${name}: ${call}`).toMatch(/^phase\("[^"]+"\)$/);
  350. }
  351. }
  352. });
  353. // docs/dynamic-workflow/authoring.md「The skill」:门要与任务的验收标准同尺度——先盘点仓库的
  354. // 检查面,快的一层驱动循环,最强的一层决定出口;示例本身不能再是弱门(§8 只门 cargo test、
  355. // examples #4 把 `lake env lean` 当 real checker)。
  356. it("teaches gate adequacy: survey the repository's checks, strongest tier decides the exit", async () => {
  357. const skill = await readSkillFile("SKILL.md");
  358. expect(skill).toContain("**Choose the gate before you write it.**");
  359. expect(skill).toContain("**Gate at the task's scale.**");
  360. expect(skill).toContain("Run the end-to-end suite once before handing over");
  361. // §8 的优化循环:单测驱动轮次,bench 决定 winner,而不是量完基线就再也不测。
  362. expect(skill).toContain('phase("Measure whether it is actually faster")');
  363. expect(skill).not.toContain('phase("Verify it actually works")');
  364. const patterns = await readSkillFile("patterns.md");
  365. expect(patterns).toContain('!check.stderr.includes("sorry")');
  366. expect(patterns).toContain("Build the whole project once before handing over");
  367. const examples = await readSkillFile("examples.md");
  368. expect(examples).toContain("Run the whole test suite once over the migrated tree");
  369. expect(examples).toContain("Build the whole project with the new proof");
  370. expect(examples).toContain("Run the property tests for real");
  371. });
  372. // docs/dynamic-workflow/authoring.md「The skill」:显式 workflow 请求默认取厚、发现必经独立确认
  373. // 且未确认者保留标注、最终返回值取报告形态。三条都是文字守卫,防止再平衡被下一次润色抹掉。
  374. it("teaches verify-before-report, the unconfirmed label, and the report shape", async () => {
  375. const skill = await readSkillFile("SKILL.md");
  376. expect(skill).toContain("## The bar: first-class, expert-level work");
  377. expect(skill).toContain("## 3. Fresh eyes");
  378. expect(skill).toContain("Ask for failures, not approval.");
  379. expect(skill).toContain("An explicit workflow request is a request for depth");
  380. expect(skill).toContain(
  381. "**Verify before you report, in proportion to what a wrong claim costs.**",
  382. );
  383. expect(skill).toContain("`unconfirmed`");
  384. expect(skill).toContain("interface WorkflowReport");
  385. expect(skill).toContain("notCovered");
  386. expect(skill).not.toContain("not to your ambition");
  387. const patterns = await readSkillFile("patterns.md");
  388. expect(patterns).toContain("confirmer-");
  389. const examples = await readSkillFile("examples.md");
  390. expect(examples).toContain("conclusion:");
  391. expect(examples).toContain("notCovered:");
  392. });
  393. // docs/dynamic-workflow/authoring.md「The skill」:验证与代价成比例、阶段间按条流水
  394. // 而不是一律 Promise.all 屏障、发现脚本有错时停下当场修订。三条都曾是 skill 自己教出来的行为
  395. //(本机 72 个 run:0 份脚本按条流水、37 份在验证阶段前设全屏障、0 次 cancelled 前驱的修订),
  396. // 所以既钉住新说法,也钉住旧示例(先审全部文件、再确认全部发现)不再回来。
  397. it("teaches proportional verification, per-item streaming, and mid-run repair (amendment 10)", async () => {
  398. const skill = await readSkillFile("SKILL.md");
  399. // 2026-09-30 起 §7 以「默认流水线」立题(见上一条用例);按条串接的规则住在 **Chaining.** 段。
  400. expect(skill).toContain("**Chaining.** When two stages map one to one");
  401. expect(skill).toContain("**Not inside a concurrent fan-out callback.**");
  402. expect(skill).toContain("Three things that look like verification and are waste.");
  403. expect(skill).toContain("**Repair a run while it is still going.**");
  404. expect(skill).toContain("`Promise.allSettled`");
  405. // 完整示例(2026-09-21 起在 examples.md §5)按条流水:确认者链在各自文件的评审之后,名字带路径
  406. // 与序号;旧的屏障式阶段名不再出现。SKILL.md §11 只留指路。
  407. expect(skill).toContain("## 11. A complete example");
  408. expect(skill).toContain("`${ZCODE_SKILL_DIR}/examples.md` §5");
  409. const movedExample = await readSkillFile("examples.md");
  410. expect(movedExample).toContain("## 5. Changed-file review with confirmation as reviews land");
  411. expect(movedExample).toContain("confirmer-${p}-${index}");
  412. expect(movedExample).not.toContain(
  413. 'phase("Confirm each kept finding independently and report it")',
  414. );
  415. // 过时的缓存关门说法(工具档位 2026-09-12 已退场)不得回来。
  416. for (const { name, text } of await readAllContent()) {
  417. expect(text, name).not.toMatch(/first subagent with tools/i);
  418. }
  419. const patterns = await readSkillFile("patterns.md");
  420. expect(patterns).toContain("## 10. Per-item pipeline");
  421. expect(patterns).toContain("A queue is not a barrier");
  422. const examples = await readSkillFile("examples.md");
  423. expect(examples).toContain(
  424. 'phase("Judge each candidate and confirm the real ones as they are judged")',
  425. );
  426. expect(examples).not.toContain('phase("Confirm each survivor by reproducing it")');
  427. });
  428. // 脚本文件(docs/dynamic-workflow/launch.md「Script files」):每次提交的脚本都有一个磁盘文件,
  429. // 内联脚本由工具写进 `.zcode/workflow-drafts/<slug>.dwf.ts`,诊断按文件行号给出,之后的每一次
  430. // 修订都是「改那个文件 + 用 `path` 重新提交」。这三句是承重话,必须逐字在 skill 里:模型一旦回到
  431. // 整段重贴,就同时踩中两个实测代价——约两万 token 的脚本重新流式输出会被部分 provider 卡死,
  432. // 而 run 真正出错时脚本正文往往已被 compaction 丢出上下文,只有文件还在。
  433. it("teaches the script-file loop: edit the file, resubmit by path", async () => {
  434. const skill = await readSkillFile("SKILL.md");
  435. expect(skill).toContain(".zcode/workflow-drafts/");
  436. expect(skill).toContain("{path}:L{line}:C{column} {message}");
  437. expect(skill).toContain(
  438. "**Edit that file and resubmit with `path`. Do not paste the script inline again**",
  439. );
  440. // 出错的 run 同样按文件修订:通知与 GetWorkflowRun 给出 scriptPath,AmendWorkflow 收 path。
  441. expect(skill).toContain("edit the run's script file, which the notification names,");
  442. expect(skill).toContain("**Every run remembers its script file, so a revision is an `Edit`.**");
  443. expect(skill).toContain("`scriptPath`");
  444. // 草稿目录免审批,否则模型会以为改文件也要等用户点确认,于是又回去贴脚本。
  445. expect(skill).toContain("**Editing a draft asks nothing.**");
  446. // EvalWorkflowSnippet 的第二个来源。
  447. expect(skill).toContain("or as `path` to a file holding it");
  448. // 旧的「整段重来」说法不得回流。
  449. for (const { name, text } of await readAllContent()) {
  450. expect(text, name).not.toMatch(/call\s+`CreateWorkflow` again/);
  451. expect(text, name).not.toMatch(/resubmit with `AmendWorkflow`\./);
  452. }
  453. });
  454. // 2026-09-07 用户裁决(docs/dynamic-workflow/authoring.md「The skill」):用户可见文本按
  455. // 「像告诉同事那样说」的一条原则 + 英中成对例子教,不列禁用词。同时钉住一处更正:分析器没有
  456. // 「同一子代理上无序 ask」的告警(诊断集 9001/9003/9004/9005/9006),skill 不得再声称编译器会警告。
  457. // 2026-09-08 用户实测:模型把 skill 里的 "cold read" / "fresh eyes" 逐字译成「冷读」「冷眼」并写进
  458. // 阶段名与子代理名。正文改称 independent read,§9 表格加成对例子,示例子代理不再叫 cold-reviewer。
  459. it("teaches writing for the user, and does not claim an analyzer warning", async () => {
  460. const skill = await readSkillFile("SKILL.md");
  461. expect(skill).toMatch(/^## \d+\. Write for the user$/m);
  462. expect(skill).toContain("文件评审阶段");
  463. expect(skill).toContain("The language travels through your asks");
  464. expect(skill).toContain("独立评审员");
  465. expect(skill).toContain("冷读方案");
  466. for (const { name, text } of await readAllContent()) {
  467. expect(text, name).not.toMatch(/compiler warns/i);
  468. // 表格的 Not 列故意保留这两个词作反例,只查表格之外的正文。
  469. expect(text.replace(/^\| .*$/gm, ""), name).not.toMatch(/cold[- ]read|cold-reviewer/i);
  470. }
  471. });
  472. it("names CreateWorkflow explicitly wherever it routes", async () => {
  473. // legacy 的 script/expert `Workflow` 工具仍在(core/src/tool/handlers/workflow.ts),
  474. // 与 dwf 共用 "workflow" 这个词。所以正文必须指名 CreateWorkflow,不能说"the workflow tool"。
  475. for (const { name, text } of await readAllContent()) {
  476. expect(text, name).toContain("CreateWorkflow");
  477. expect(text, name).not.toMatch(/\bthe workflow tool\b/i);
  478. }
  479. });
  480. // 最强的一条守卫:示例脚本过真编译器。标识符匹配只能证明"名字存在",编译能证明"这段脚本真能跑"。
  481. // 只查显式标注 `<!-- compile -->` 的块——patterns.md 的片段刻意省略接口声明,不是完整脚本;
  482. // 用启发式("含 return 就编译")区分两者,迟早会把某个真错误当成片段放过去。
  483. it("compiles every script block marked as complete", async () => {
  484. const marked: { file: string; index: number; source: string }[] = [];
  485. for (const { name, text } of await readAllContent()) {
  486. const blocks = [...text.matchAll(/<!-- compile -->\n```ts\n([\s\S]*?)```/g)];
  487. blocks.forEach((match, index) => {
  488. marked.push({ file: name, index, source: match[1] });
  489. });
  490. }
  491. // SKILL.md 的完整示例 + §9 的报告形状 + §9 的产物发布例 + examples.md 的四个脚本。
  492. // 掉到 6 以下意味着标记被误删——那会让这条守卫静默退化成空断言。
  493. // 下限沿革:4(初版)→ 5(Amendment 1 的 world.run 例)→ 6(Amendment 6 的产物例)。
  494. expect(marked.length).toBeGreaterThanOrEqual(6);
  495. for (const { file, index, source } of marked) {
  496. const result = compileWorkflowScript(source);
  497. expect(result.diagnostics, `${file} block #${index}`).toEqual([]);
  498. expect(result.ok, `${file} block #${index}`).toBe(true);
  499. // 编译只跑 typecheck,看不见 authoring 诊断(world.run 字面量、phase 标记形态、actor
  500. // 重名 / fan-out 静态名)。而 CreateWorkflow / SaveWorkflow 的 handler 先过
  501. // analyzeScript,`!ok` 即拒绝提交——所以「示例能编译」曾经不等于「模型照抄能提交」。
  502. // 2026-08-31 amend-resume 把 actor 名变成唯一身份键后这条缝真的漏了东西:技能里每一个
  503. // fan-out 都写着 `agent("reviewer")`,全是 9006。补上这一趟,守卫才对齐真实的提交门。
  504. const analyzed = analyzeWorkflowScript(source);
  505. expect(analyzed.diagnostics, `${file} block #${index} (analyze)`).toEqual([]);
  506. expect(analyzed.ok, `${file} block #${index} (analyze)`).toBe(true);
  507. }
  508. });
  509. });
  510. /**
  511. * 灰度门(docs/dynamic-workflow/launch.md「Gray release」)按**目录名**定位技能资产,而技能包里改名
  512. * 不会让任何类型报错,门会静默失效。这里把名字钉死在真实文件上。
  513. */
  514. describe("gray release gate names stay pinned to the real bundled assets", () => {
  515. function bundledRoots(): SkillRoot[] {
  516. return resolveBundledSkillRoots({ cliStorageRoot: join(tmpdir(), "zcode-unused-cli-storage") });
  517. }
  518. it("内置技能包解析到真实的 skills 目录,且剔除路径正好落在 dynamic-workflows SKILL.md 上", () => {
  519. const roots = bundledRoots();
  520. expect(roots).toEqual([
  521. {
  522. path: join(PACK_ROOT, "skills"),
  523. priority: expect.any(Number),
  524. scope: "system",
  525. source: "bundled",
  526. },
  527. ]);
  528. expect(collectDynamicWorkflowDisabledSkillPaths(roots)).toEqual([join(SKILL_DIR, "SKILL.md")]);
  529. });
  530. /**
  531. * 端到端地跑一遍真实的 NodeSkillAdapter,把 create-app 的装配复现出来:内置技能根与插件技能根并列,
  532. * adapter 在发现阶段按 SKILL.md 的绝对路径比对 disabledPaths。任一假设不成立,这条用例立刻红,
  533. * 而不是灰度门静默失效。
  534. */
  535. describe("real NodeSkillAdapter discovery", () => {
  536. const guidePluginRoot: SkillRoot = {
  537. path: GUIDE_PLUGIN_SKILLS_ROOT,
  538. priority: 0,
  539. scope: "system",
  540. source: "plugin",
  541. };
  542. async function discoveredSkills(
  543. disabledPaths: string[],
  544. ): Promise<Array<{ name: string; source: string }>> {
  545. const adapter = createNodeSkillAdapter({ disabledPaths });
  546. const outcome = await adapter.discoverSkills({
  547. workingDirectory: PACK_ROOT,
  548. roots: [guidePluginRoot, ...bundledRoots()],
  549. });
  550. return outcome.skills.map((skill) => ({ name: skill.name, source: skill.source }));
  551. }
  552. it("灰度开启(无门禁路径)时目录里有 dynamic-workflows,且来源是 bundled", async () => {
  553. await expect(discoveredSkills([])).resolves.toContainEqual({
  554. name: SKILL_NAME,
  555. source: "bundled",
  556. });
  557. });
  558. it("灰度关闭时 dynamic-workflows 消失,插件技能仍在", async () => {
  559. const skills = await discoveredSkills(
  560. collectDynamicWorkflowDisabledSkillPaths(bundledRoots()),
  561. );
  562. const names = skills.map((skill) => skill.name);
  563. expect(names).not.toContain(SKILL_NAME);
  564. // 反向断言:门只剔一个 SKILL.md,其他根没有被连坐。
  565. expect(names).toContain("zcode-configuration-guide");
  566. expect(names.length).toBeGreaterThan(1);
  567. });
  568. });
  569. });