saved-workflow-tools.test.ts 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  5. import {
  6. CREATE_WORKFLOW_SOURCE_CONFLICT_ERROR,
  7. CREATE_WORKFLOW_SOURCE_MISSING_ERROR,
  8. WORKFLOW_SOURCE_MISSING_HINT,
  9. CreateWorkflowInputSchema,
  10. HookEventName,
  11. SAVE_WORKFLOW_SENTINEL_IN_SCRIPT_ERROR,
  12. SessionEventType,
  13. WORKFLOW_DRAFTS_DIR,
  14. createRootTraceContext,
  15. createSessionId,
  16. createToolCallId,
  17. createTurnId,
  18. type CreateWorkflowOutput,
  19. type DynamicWorkflowRunPort,
  20. type DynamicWorkflowRunSubmitRequest,
  21. type ListSavedWorkflowsOutput,
  22. type PermissionBrokerPort,
  23. type PermissionRequestedPayload,
  24. type SaveWorkflowOutput,
  25. type SessionEvent,
  26. type ToolExecutionResult,
  27. } from "@zcode/contracts";
  28. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  29. import { createToolExecutor } from "../src/tool/executor.js";
  30. import { createWorkflowToolEntry } from "../src/tool/handlers/create-workflow.js";
  31. import { saveWorkflowToolEntry } from "../src/tool/handlers/save-workflow.js";
  32. import { listSavedWorkflowsToolEntry } from "../src/tool/handlers/list-saved-workflows.js";
  33. import { builtInTools } from "../src/tool/handlers/index.js";
  34. import { saveSavedWorkflow } from "../src/tool/handlers/saved-workflows/index.js";
  35. import { createToolRegistry } from "../src/tool/registry.js";
  36. import type { HookRunner } from "../src/hooks/index.js";
  37. const cwds: string[] = [];
  38. function makeCwd(): string {
  39. const dir = mkdtempSync(join(tmpdir(), "dwf-tools-"));
  40. cwds.push(dir);
  41. return dir;
  42. }
  43. /** 一个隔离的家目录,供全局档用例注入。 */
  44. function makeHome(): string {
  45. const dir = mkdtempSync(join(tmpdir(), "dwf-tools-home-"));
  46. cwds.push(dir);
  47. return dir;
  48. }
  49. // 生产的全局根取 os.homedir()(POSIX 上认 $HOME)。handler 不接收 homeDir,所以把 HOME
  50. // 指到一个空临时目录,让全局档落点与「哪都没有」的错误文案在测试里可控、可复现。
  51. let originalHome: string | undefined;
  52. let originalUserProfile: string | undefined;
  53. let testHome: string;
  54. beforeEach(() => {
  55. originalHome = process.env.HOME;
  56. originalUserProfile = process.env.USERPROFILE;
  57. testHome = makeHome();
  58. process.env.HOME = testHome;
  59. process.env.USERPROFILE = testHome;
  60. });
  61. afterEach(() => {
  62. if (originalHome === undefined) delete process.env.HOME;
  63. else process.env.HOME = originalHome;
  64. if (originalUserProfile === undefined) delete process.env.USERPROFILE;
  65. else process.env.USERPROFILE = originalUserProfile;
  66. while (cwds.length > 0) rmSync(cwds.pop()!, { force: true, recursive: true });
  67. });
  68. /** 全局档落点(HOME 已被 beforeEach 指到 testHome)。 */
  69. function globalSavedPath(name: string): string {
  70. return join(testHome, ".zcode/workflows", `${name}.dwf.ts`);
  71. }
  72. // 记忆槽是单槽、按脚本原文取键,所以每个用例用自己的脚本;否则上一个用例存下的分析
  73. // 会直接满足下一个用例的断言。
  74. function cleanScript(actor: string): string {
  75. return [
  76. "interface R { done: boolean }",
  77. `const r = await agent("${actor}").ask<R>("do");`,
  78. "return r.done;",
  79. ].join("\n");
  80. }
  81. interface RunOptions {
  82. broker?: PermissionBrokerPort;
  83. dynamicWorkflowRunPort?: DynamicWorkflowRunPort;
  84. hookRunner?: HookRunner;
  85. input: Record<string, unknown>;
  86. name: string;
  87. toolName: string;
  88. workingDirectory: string;
  89. }
  90. interface RunOutcome {
  91. events: SessionEvent[];
  92. permissionRequested: PermissionRequestedPayload[];
  93. result: ToolExecutionResult;
  94. }
  95. function stubRunPort(runId: string): {
  96. port: DynamicWorkflowRunPort;
  97. submits: DynamicWorkflowRunSubmitRequest[];
  98. } {
  99. const submits: DynamicWorkflowRunSubmitRequest[] = [];
  100. return {
  101. port: {
  102. async submit(request) {
  103. submits.push(request);
  104. // submit 的结果是判别联合(amend-resume 的三道门可以拒绝一次提交);桩恒接受。
  105. return { ok: true, runId };
  106. },
  107. } as unknown as DynamicWorkflowRunPort,
  108. submits,
  109. };
  110. }
  111. async function run(options: RunOptions): Promise<RunOutcome> {
  112. const sessionId = createSessionId(options.name);
  113. const turnId = createTurnId(options.name);
  114. const traceContext = createRootTraceContext({ sessionId, turnId });
  115. const events: SessionEvent[] = [];
  116. const registry = createToolRegistry();
  117. registry.register(createWorkflowToolEntry);
  118. registry.register(saveWorkflowToolEntry);
  119. registry.register(listSavedWorkflowsToolEntry);
  120. const executor = createToolExecutor({
  121. emitEvent: async (event) => {
  122. events.push(event);
  123. },
  124. ...(options.dynamicWorkflowRunPort
  125. ? { dynamicWorkflowRunPort: options.dynamicWorkflowRunPort }
  126. : {}),
  127. ...(options.hookRunner ? { hookRunner: options.hookRunner } : {}),
  128. mode: "build",
  129. permissionBroker: options.broker ?? {
  130. async requestPermission() {
  131. return { decision: "allow" as const };
  132. },
  133. },
  134. permissionService: new PermissionService(defaultPermissionConfig),
  135. registry,
  136. sessionId,
  137. turnId,
  138. traceContext,
  139. workingDirectory: options.workingDirectory,
  140. });
  141. const result = await executor.execute(
  142. { id: createToolCallId(options.name), input: options.input, name: options.toolName },
  143. { traceContext },
  144. );
  145. return {
  146. events,
  147. permissionRequested: events
  148. .filter((event) => event.type === SessionEventType.PermissionRequested)
  149. .map((event) => event.payload as PermissionRequestedPayload),
  150. result,
  151. };
  152. }
  153. const DENY: PermissionBrokerPort = {
  154. async requestPermission() {
  155. return { decision: "deny", reason: "User declined" };
  156. },
  157. };
  158. function savedPath(cwd: string, name: string): string {
  159. return join(cwd, ".zcode/workflows", `${name}.dwf.ts`);
  160. }
  161. describe("SaveWorkflow", () => {
  162. it("writes the file after the confirmation, with the metadata block ahead of the script", async () => {
  163. const cwd = makeCwd();
  164. const script = cleanScript("save-clean");
  165. const outcome = await run({
  166. input: {
  167. name: "pr-review",
  168. description: "Review a pull request",
  169. whenToUse: "When the user asks for a PR review",
  170. args: { pr: { type: "string", required: true, description: "PR number" } },
  171. script,
  172. scope: "project",
  173. },
  174. name: "save-clean",
  175. toolName: "SaveWorkflow",
  176. workingDirectory: cwd,
  177. });
  178. expect(outcome.permissionRequested).toHaveLength(1);
  179. expect(outcome.result.success).toBe(true);
  180. const output = outcome.result.output as SaveWorkflowOutput;
  181. expect(output.ok).toBe(true);
  182. expect(output.overwritten).toBe(false);
  183. expect(output.scope).toBe("project");
  184. expect(output.path).toBe(savedPath(cwd, "pr-review"));
  185. // 逐字节:脚本本体是 run 的 script_hash 的基准,序列化不许顺手规范化它。
  186. expect(readFileSync(output.path, "utf8")).toBe(
  187. [
  188. "/* zcode-workflow",
  189. "description: Review a pull request",
  190. "whenToUse: When the user asks for a PR review",
  191. "args:",
  192. " pr:",
  193. " type: string",
  194. " description: PR number",
  195. " required: true",
  196. "*/",
  197. script,
  198. ].join("\n"),
  199. );
  200. });
  201. // 归一化 (c):确认窗要展示的一切都在**入参**里,display 一个字段都不加。入参通道对每个
  202. // 客户端版本都是无 schema 的透传,所以旧桌面与 legacy v3 也拿得到完整内容。
  203. it("asks with no display, carrying path/overwrite/scope and the full script in the input", async () => {
  204. const cwd = makeCwd();
  205. const script = cleanScript("save-preview");
  206. const outcome = await run({
  207. input: { name: "preview", description: "shows up in the window", script, scope: "project" },
  208. name: "save-preview",
  209. toolName: "SaveWorkflow",
  210. workingDirectory: cwd,
  211. });
  212. const payload = outcome.permissionRequested[0]!;
  213. expect(payload.display).toBeUndefined();
  214. // 持久项目规则记不住"这一次的决定",只会把这道确认永久关掉。
  215. expect(payload.optionsPolicy).toBe("no-always-allow");
  216. expect(payload.input).toEqual({
  217. name: "preview",
  218. description: "shows up in the window",
  219. script,
  220. scope: "project",
  221. path: savedPath(cwd, "preview"),
  222. overwrite: false,
  223. });
  224. });
  225. // 「覆盖」与「新建」必须是窗口上两句不同的话:批准一次覆盖就是同意丢掉磁盘上那一份。
  226. it("flags an overwrite in the gate input when the name is already taken", async () => {
  227. const cwd = makeCwd();
  228. saveSavedWorkflow({ cwd, name: "taken", meta: { description: "old" }, script: "return 1;" });
  229. const outcome = await run({
  230. input: {
  231. name: "taken",
  232. description: "new",
  233. script: cleanScript("save-overwrite"),
  234. scope: "project",
  235. },
  236. name: "save-overwrite",
  237. toolName: "SaveWorkflow",
  238. workingDirectory: cwd,
  239. });
  240. expect((outcome.permissionRequested[0]!.input as { overwrite: boolean }).overwrite).toBe(true);
  241. const output = outcome.result.output as SaveWorkflowOutput;
  242. expect(output.overwritten).toBe(true);
  243. expect(readFileSync(output.path, "utf8")).toContain("description: new");
  244. });
  245. // 让用户批准一段编不过的代码,只会用一个不产生任何效果的决策打断改错回路。
  246. it("returns diagnostics for a broken script without asking and without writing", async () => {
  247. const cwd = makeCwd();
  248. const outcome = await run({
  249. input: {
  250. name: "broken",
  251. description: "will not compile",
  252. script: 'const x: number = "s";',
  253. scope: "project",
  254. },
  255. name: "save-broken",
  256. toolName: "SaveWorkflow",
  257. workingDirectory: cwd,
  258. });
  259. expect(outcome.permissionRequested).toHaveLength(0);
  260. expect(outcome.result.success).toBe(true);
  261. const output = outcome.result.output as SaveWorkflowOutput;
  262. expect(output.ok).toBe(false);
  263. expect(output.diagnostics.length).toBeGreaterThan(0);
  264. expect(output.overwritten).toBeUndefined();
  265. expect(existsSync(savedPath(cwd, "broken"))).toBe(false);
  266. });
  267. it("rejects an unusable name before the gate and without touching the disk", async () => {
  268. const cwd = makeCwd();
  269. const outcome = await run({
  270. input: {
  271. name: "../evil",
  272. description: "traversal",
  273. script: cleanScript("save-traversal"),
  274. scope: "project",
  275. },
  276. name: "save-traversal",
  277. toolName: "SaveWorkflow",
  278. workingDirectory: cwd,
  279. });
  280. expect(outcome.permissionRequested).toHaveLength(0);
  281. expect(outcome.result.success).toBe(false);
  282. expect(outcome.result.error?.message).toContain("not a usable workflow name");
  283. expect(existsSync(join(cwd, ".zcode"))).toBe(false);
  284. });
  285. // encode 的幂等性(文件里永远只有一个 frontmatter 块)靠这条守:不做「检测到就替换」的
  286. // 聪明合并,否则模型无从分辨自己传的元数据和文件里那个哪一个生效。
  287. it("rejects a script that already carries a metadata block", async () => {
  288. const cwd = makeCwd();
  289. const outcome = await run({
  290. input: {
  291. name: "double",
  292. description: "already has frontmatter",
  293. script: `/* zcode-workflow\ndescription: smuggled\n*/\n${cleanScript("save-sentinel")}`,
  294. scope: "project",
  295. },
  296. name: "save-sentinel",
  297. toolName: "SaveWorkflow",
  298. workingDirectory: cwd,
  299. });
  300. expect(outcome.permissionRequested).toHaveLength(0);
  301. expect(outcome.result.success).toBe(false);
  302. expect(outcome.result.error?.message).toBe(SAVE_WORKFLOW_SENTINEL_IN_SCRIPT_ERROR);
  303. expect(existsSync(savedPath(cwd, "double"))).toBe(false);
  304. });
  305. it("writes nothing when the confirmation is denied", async () => {
  306. const cwd = makeCwd();
  307. const outcome = await run({
  308. broker: DENY,
  309. input: {
  310. name: "denied",
  311. description: "not this time",
  312. script: cleanScript("save-deny"),
  313. scope: "project",
  314. },
  315. name: "save-deny",
  316. toolName: "SaveWorkflow",
  317. workingDirectory: cwd,
  318. });
  319. expect(outcome.permissionRequested).toHaveLength(1);
  320. expect(outcome.result.success).toBe(false);
  321. expect(outcome.result.error?.type).toBe("permission_denied");
  322. expect(existsSync(savedPath(cwd, "denied"))).toBe(false);
  323. });
  324. // 作用域是模型必填:没有默认值,schema 直接拒。
  325. it("fails schema validation when scope is omitted", async () => {
  326. const cwd = makeCwd();
  327. const outcome = await run({
  328. input: {
  329. name: "no-scope",
  330. description: "missing scope",
  331. script: cleanScript("save-no-scope"),
  332. },
  333. name: "save-no-scope",
  334. toolName: "SaveWorkflow",
  335. workingDirectory: cwd,
  336. });
  337. expect(outcome.permissionRequested).toHaveLength(0);
  338. expect(outcome.result.success).toBe(false);
  339. expect(existsSync(savedPath(cwd, "no-scope"))).toBe(false);
  340. });
  341. // 全局档:落点在注入的 HOME 下,resolveInput 按 scope 选根算出它。
  342. it("backfills the global path and writes under the home dir for scope global", async () => {
  343. const cwd = makeCwd();
  344. const script = cleanScript("save-global");
  345. const outcome = await run({
  346. input: { name: "research", description: "deep research", script, scope: "global" },
  347. name: "save-global",
  348. toolName: "SaveWorkflow",
  349. workingDirectory: cwd,
  350. });
  351. expect(outcome.permissionRequested).toHaveLength(1);
  352. expect(outcome.permissionRequested[0]!.input).toEqual({
  353. name: "research",
  354. description: "deep research",
  355. script,
  356. scope: "global",
  357. path: globalSavedPath("research"),
  358. overwrite: false,
  359. });
  360. const output = outcome.result.output as SaveWorkflowOutput;
  361. expect(output.scope).toBe("global");
  362. expect(output.path).toBe(globalSavedPath("research"));
  363. expect(output.response).toContain("Saved global workflow 'research'");
  364. // 项目目录一个字节都没被建出来。
  365. expect(existsSync(join(cwd, ".zcode"))).toBe(false);
  366. expect(existsSync(globalSavedPath("research"))).toBe(true);
  367. });
  368. // shadowing 回填 hides_global:保存项目档而全局档已有同名。
  369. it("backfills shadowing=hides_global when a global copy already exists", async () => {
  370. const cwd = makeCwd();
  371. saveSavedWorkflow({
  372. cwd,
  373. name: "dup",
  374. meta: { description: "global one" },
  375. script: "return 1;",
  376. scope: "global",
  377. });
  378. const outcome = await run({
  379. input: {
  380. name: "dup",
  381. description: "project one",
  382. script: cleanScript("save-shadow-p"),
  383. scope: "project",
  384. },
  385. name: "save-shadow-project",
  386. toolName: "SaveWorkflow",
  387. workingDirectory: cwd,
  388. });
  389. expect((outcome.permissionRequested[0]!.input as { shadowing?: string }).shadowing).toBe(
  390. "hides_global",
  391. );
  392. });
  393. // shadowing 回填 hidden_by_project:保存全局档而项目档已有同名。
  394. it("backfills shadowing=hidden_by_project when a project copy already exists", async () => {
  395. const cwd = makeCwd();
  396. saveSavedWorkflow({
  397. cwd,
  398. name: "dup",
  399. meta: { description: "project one" },
  400. script: "return 1;",
  401. });
  402. const outcome = await run({
  403. input: {
  404. name: "dup",
  405. description: "global one",
  406. script: cleanScript("save-shadow-g"),
  407. scope: "global",
  408. },
  409. name: "save-shadow-global",
  410. toolName: "SaveWorkflow",
  411. workingDirectory: cwd,
  412. });
  413. expect((outcome.permissionRequested[0]!.input as { shadowing?: string }).shadowing).toBe(
  414. "hidden_by_project",
  415. );
  416. });
  417. });
  418. describe("ListSavedWorkflows", () => {
  419. it("lists definitions with their arguments and never the script body", async () => {
  420. const cwd = makeCwd();
  421. saveSavedWorkflow({
  422. cwd,
  423. name: "triage",
  424. meta: {
  425. description: "Triage the inbox",
  426. whenToUse: "Every morning",
  427. args: { limit: { type: "number", default: 10 } },
  428. },
  429. script: cleanScript("list-triage"),
  430. });
  431. const outcome = await run({
  432. input: {},
  433. name: "list-saved",
  434. toolName: "ListSavedWorkflows",
  435. workingDirectory: cwd,
  436. });
  437. expect(outcome.permissionRequested).toHaveLength(0);
  438. const output = outcome.result.output as ListSavedWorkflowsOutput;
  439. expect(output.workflows).toHaveLength(1);
  440. expect(output.workflows[0]!.name).toBe("triage");
  441. expect(output.invalid).toBeUndefined();
  442. const modelContent = String(outcome.result.modelContent ?? "");
  443. expect(modelContent).toContain('name="triage"');
  444. expect(modelContent).toContain("Triage the inbox");
  445. expect(modelContent).toContain("arg limit (number, default 10)");
  446. expect(modelContent).not.toContain("agent(");
  447. });
  448. it("says so in a sentence when the project has no saved workflows", async () => {
  449. const outcome = await run({
  450. input: {},
  451. name: "list-saved-empty",
  452. toolName: "ListSavedWorkflows",
  453. workingDirectory: makeCwd(),
  454. });
  455. expect((outcome.result.output as ListSavedWorkflowsOutput).workflows).toEqual([]);
  456. expect(String(outcome.result.modelContent ?? "")).toContain("No workflows are saved");
  457. });
  458. // 与 ListWorkflowRuns 同一条收敛:工具恒查会话工作目录,模型无权跨项目扫盘。
  459. it("rejects a cwd input outright", async () => {
  460. const outcome = await run({
  461. input: { cwd: "/etc" },
  462. name: "list-saved-cwd",
  463. toolName: "ListSavedWorkflows",
  464. workingDirectory: makeCwd(),
  465. });
  466. expect(outcome.result.success).toBe(false);
  467. });
  468. });
  469. describe("CreateWorkflow saved source", () => {
  470. it("normalizes the gate input to the resolved script, the saved name and the checked args", async () => {
  471. const cwd = makeCwd();
  472. const script = cleanScript("saved-happy");
  473. saveSavedWorkflow({
  474. cwd,
  475. name: "nightly",
  476. meta: { description: "nightly triage", args: { depth: { type: "number", default: 3 } } },
  477. script,
  478. });
  479. const { port, submits } = stubRunPort("dwfrun-saved");
  480. const outcome = await run({
  481. dynamicWorkflowRunPort: port,
  482. input: { saved: { name: "nightly" } },
  483. name: "create-saved-happy",
  484. toolName: "CreateWorkflow",
  485. workingDirectory: cwd,
  486. });
  487. expect(outcome.permissionRequested).toHaveLength(1);
  488. // 归一化 (b) 的核心:旧桌面的 readWorkflowScript(raw.script) / readWorkflowName(raw.name)
  489. // 就是读这两个键——它们命中是**构造上**成立的,不是兼容处理。
  490. expect(outcome.permissionRequested[0]!.input).toEqual({
  491. name: "nightly",
  492. script,
  493. saved: {
  494. name: "nightly",
  495. args: { depth: 3 },
  496. path: savedPath(cwd, "nightly"),
  497. scope: "project",
  498. // 工作副本在 resolveInput 里随这次读一起写下(docs/dynamic-workflow/launch.md
  499. // 「Script files」):模型要改的是这份拷贝,保存的定义一个字都不动。
  500. draft: join(cwd, WORKFLOW_DRAFTS_DIR, "nightly.dwf.ts"),
  501. },
  502. // 拷贝带着元数据块,所以诊断的文件行要跳过块的那几行。
  503. script_line_offset: expect.any(Number),
  504. // 确认窗可调的设置(docs/dynamic-workflow/launch.md「Adjusting the settings in the window」):
  505. // 桩 run port 没有模型目录、也报不出天花板,所以只能调上界、没有上限。
  506. adjustable_settings: { subagent_model: false },
  507. });
  508. // 拷贝逐字节等于定义文件本身。
  509. expect(readFileSync(join(cwd, WORKFLOW_DRAFTS_DIR, "nightly.dwf.ts"), "utf8")).toBe(
  510. readFileSync(savedPath(cwd, "nightly"), "utf8"),
  511. );
  512. expect(outcome.result.success).toBe(true);
  513. const output = outcome.result.output as CreateWorkflowOutput;
  514. expect(output.status).toBe("backgrounded");
  515. expect(submits).toHaveLength(1);
  516. expect(submits[0]!.scriptText).toBe(script);
  517. expect(submits[0]!.name).toBe("nightly");
  518. // 实参走 name / scriptText 同一条元数据路,落 dwf_run.args_json 并注入沙箱。
  519. expect(submits[0]!.args).toEqual({ depth: 3 });
  520. });
  521. // 不变式 8 的钉子:saved 与内联产出的 display 必须逐字节相同,本特性一个字段都不加。
  522. it("produces a display byte-identical to the same script run inline", async () => {
  523. const cwd = makeCwd();
  524. const script = cleanScript("saved-parity");
  525. saveSavedWorkflow({ cwd, name: "parity", meta: { description: "parity" }, script });
  526. const { port } = stubRunPort("dwfrun-parity");
  527. const viaSaved = await run({
  528. dynamicWorkflowRunPort: port,
  529. input: { saved: { name: "parity" } },
  530. name: "create-parity-saved",
  531. toolName: "CreateWorkflow",
  532. workingDirectory: cwd,
  533. });
  534. const viaInline = await run({
  535. dynamicWorkflowRunPort: port,
  536. input: { script },
  537. name: "create-parity-inline",
  538. toolName: "CreateWorkflow",
  539. workingDirectory: cwd,
  540. });
  541. const savedDisplay = viaSaved.permissionRequested[0]!.display;
  542. expect(savedDisplay).toEqual(viaInline.permissionRequested[0]!.display);
  543. expect(Object.keys(savedDisplay as object).sort()).toEqual([
  544. "causalityGraph",
  545. "diagnostics",
  546. "errorCount",
  547. "kind",
  548. "ok",
  549. ]);
  550. });
  551. // 归一化 (e):策略不被保存绕开。一条扫描脚本的 PreToolUse hook 在 saved run 上必须
  552. // 看到真正的脚本——否则保存就成了一条策略盲区。
  553. it("gives PreToolUse hooks the resolved script, not just the saved name", async () => {
  554. const cwd = makeCwd();
  555. const script = cleanScript("saved-hook");
  556. saveSavedWorkflow({ cwd, name: "policed", meta: { description: "policed" }, script });
  557. const seen: unknown[] = [];
  558. const hookRunner: HookRunner = {
  559. async run(input) {
  560. if (input.hookEventName === HookEventName.PreToolUse) {
  561. seen.push((input as unknown as { toolInput?: unknown }).toolInput);
  562. }
  563. return { additionalContexts: [] };
  564. },
  565. };
  566. await run({
  567. dynamicWorkflowRunPort: stubRunPort("dwfrun-hook").port,
  568. hookRunner,
  569. input: { saved: { name: "policed" } },
  570. name: "create-saved-hook",
  571. toolName: "CreateWorkflow",
  572. workingDirectory: cwd,
  573. });
  574. expect(seen).toHaveLength(1);
  575. expect((seen[0] as { script?: string }).script).toBe(script);
  576. });
  577. // 不变式 5:确认与执行同字节。解析只发生一次,批准之后不再读盘。
  578. it("runs the bytes shown at the gate even if the file changes after resolution", async () => {
  579. const cwd = makeCwd();
  580. const approved = cleanScript("saved-toctou");
  581. saveSavedWorkflow({ cwd, name: "swapped", meta: { description: "swapped" }, script: approved });
  582. const { port, submits } = stubRunPort("dwfrun-toctou");
  583. const outcome = await run({
  584. broker: {
  585. async requestPermission() {
  586. // 用户思考的这段时间里,磁盘上的文件被换掉了。
  587. saveSavedWorkflow({
  588. cwd,
  589. name: "swapped",
  590. meta: { description: "swapped" },
  591. script: cleanScript("saved-toctou-evil"),
  592. });
  593. return { decision: "allow" };
  594. },
  595. },
  596. dynamicWorkflowRunPort: port,
  597. input: { saved: { name: "swapped" } },
  598. name: "create-saved-toctou",
  599. toolName: "CreateWorkflow",
  600. workingDirectory: cwd,
  601. });
  602. expect(outcome.result.success).toBe(true);
  603. expect(submits[0]!.scriptText).toBe(approved);
  604. });
  605. it("lets an explicit name override the saved name as the run label", async () => {
  606. const cwd = makeCwd();
  607. saveSavedWorkflow({
  608. cwd,
  609. name: "generic",
  610. meta: { description: "generic" },
  611. script: cleanScript("saved-label"),
  612. });
  613. const { port, submits } = stubRunPort("dwfrun-label");
  614. await run({
  615. dynamicWorkflowRunPort: port,
  616. input: { name: "tuesday run", saved: { name: "generic" } },
  617. name: "create-saved-label",
  618. toolName: "CreateWorkflow",
  619. workingDirectory: cwd,
  620. });
  621. expect(submits[0]!.name).toBe("tuesday run");
  622. });
  623. // 参数传错没有任何值得用户裁决的东西:弹一个注定失败的窗只是打断模型的改错回路。
  624. it("rejects bad arguments before the gate, naming the declaration", async () => {
  625. const cwd = makeCwd();
  626. saveSavedWorkflow({
  627. cwd,
  628. name: "strict-args",
  629. meta: {
  630. description: "takes args",
  631. args: { pr: { type: "string", required: true, description: "PR number" } },
  632. },
  633. script: cleanScript("saved-bad-args"),
  634. });
  635. const { port, submits } = stubRunPort("dwfrun-bad-args");
  636. const outcome = await run({
  637. dynamicWorkflowRunPort: port,
  638. input: { saved: { name: "strict-args", args: { pull: "42" } } },
  639. name: "create-saved-bad-args",
  640. toolName: "CreateWorkflow",
  641. workingDirectory: cwd,
  642. });
  643. expect(outcome.permissionRequested).toHaveLength(0);
  644. expect(submits).toHaveLength(0);
  645. expect(outcome.result.success).toBe(false);
  646. const message = outcome.result.error?.message ?? "";
  647. expect(message).toContain("unknown argument 'pull'");
  648. expect(message).toContain("missing required argument 'pr'");
  649. // 声明复述让模型一次改对,而不是再猜一轮。
  650. expect(message).toContain("PR number");
  651. });
  652. // 猜错名字之后最有用的下一步信息就是正确的那一批。
  653. it("names the available workflows when the requested one does not exist", async () => {
  654. const cwd = makeCwd();
  655. saveSavedWorkflow({
  656. cwd,
  657. name: "actual",
  658. meta: { description: "the real one" },
  659. script: cleanScript("saved-missing"),
  660. });
  661. const { port, submits } = stubRunPort("dwfrun-missing");
  662. const outcome = await run({
  663. dynamicWorkflowRunPort: port,
  664. input: { saved: { name: "typo" } },
  665. name: "create-saved-missing",
  666. toolName: "CreateWorkflow",
  667. workingDirectory: cwd,
  668. });
  669. expect(outcome.permissionRequested).toHaveLength(0);
  670. expect(submits).toHaveLength(0);
  671. expect(outcome.result.success).toBe(false);
  672. const message = outcome.result.error?.message ?? "";
  673. expect(message).toContain("No saved workflow named 'typo'");
  674. expect(message).toContain("Available saved workflows: actual");
  675. });
  676. it("points at SaveWorkflow when the project has no saved workflows at all", async () => {
  677. const outcome = await run({
  678. input: { saved: { name: "anything" } },
  679. name: "create-saved-none",
  680. toolName: "CreateWorkflow",
  681. workingDirectory: makeCwd(),
  682. });
  683. expect(outcome.result.error?.message ?? "").toContain("no saved workflows yet");
  684. });
  685. // saved.scope 定向:同名两档时指定 global 跳过遮蔽,跑的是全局那份。
  686. it("takes the global copy when saved.scope is global despite a project shadow", async () => {
  687. const cwd = makeCwd();
  688. const projectScript = cleanScript("saved-scope-project");
  689. const globalScript = cleanScript("saved-scope-global");
  690. saveSavedWorkflow({
  691. cwd,
  692. name: "dup",
  693. meta: { description: "project" },
  694. script: projectScript,
  695. });
  696. saveSavedWorkflow({
  697. cwd,
  698. name: "dup",
  699. meta: { description: "global" },
  700. script: globalScript,
  701. scope: "global",
  702. });
  703. const { port, submits } = stubRunPort("dwfrun-scope-global");
  704. const outcome = await run({
  705. dynamicWorkflowRunPort: port,
  706. input: { saved: { name: "dup", scope: "global" } },
  707. name: "create-saved-scope-global",
  708. toolName: "CreateWorkflow",
  709. workingDirectory: cwd,
  710. });
  711. expect(outcome.permissionRequested).toHaveLength(1);
  712. const gateSaved = (
  713. outcome.permissionRequested[0]!.input as { saved: { scope: string; path: string } }
  714. ).saved;
  715. expect(gateSaved.scope).toBe("global");
  716. expect(gateSaved.path).toBe(globalSavedPath("dup"));
  717. expect(submits[0]!.scriptText).toBe(globalScript);
  718. });
  719. // 缺省走 first-wins:同名两档时项目档遮蔽全局档,跑的是项目那份。
  720. it("takes the project copy by default when both scopes carry the name", async () => {
  721. const cwd = makeCwd();
  722. const projectScript = cleanScript("saved-default-project");
  723. saveSavedWorkflow({
  724. cwd,
  725. name: "dup",
  726. meta: { description: "project" },
  727. script: projectScript,
  728. });
  729. saveSavedWorkflow({
  730. cwd,
  731. name: "dup",
  732. meta: { description: "global" },
  733. script: cleanScript("saved-default-global"),
  734. scope: "global",
  735. });
  736. const { port, submits } = stubRunPort("dwfrun-scope-default");
  737. const outcome = await run({
  738. dynamicWorkflowRunPort: port,
  739. input: { saved: { name: "dup" } },
  740. name: "create-saved-scope-default",
  741. toolName: "CreateWorkflow",
  742. workingDirectory: cwd,
  743. });
  744. const gateSaved = (outcome.permissionRequested[0]!.input as { saved: { scope: string } }).saved;
  745. expect(gateSaved.scope).toBe("project");
  746. expect(submits[0]!.scriptText).toBe(projectScript);
  747. });
  748. // 定向找不到:文案说「该作用域下没有」,并列出两档可用名字(带标签)。
  749. it("names the scope and lists both archives when a directed lookup misses", async () => {
  750. const cwd = makeCwd();
  751. saveSavedWorkflow({
  752. cwd,
  753. name: "in-project",
  754. meta: { description: "p" },
  755. script: cleanScript("saved-directed-p"),
  756. });
  757. saveSavedWorkflow({
  758. cwd,
  759. name: "in-global",
  760. meta: { description: "g" },
  761. script: cleanScript("saved-directed-g"),
  762. scope: "global",
  763. });
  764. const outcome = await run({
  765. input: { saved: { name: "ghost", scope: "global" } },
  766. name: "create-saved-directed-miss",
  767. toolName: "CreateWorkflow",
  768. workingDirectory: cwd,
  769. });
  770. expect(outcome.result.success).toBe(false);
  771. const message = outcome.result.error?.message ?? "";
  772. expect(message).toContain("No global workflow named 'ghost'");
  773. expect(message).toContain("in-project (project)");
  774. expect(message).toContain("in-global (global)");
  775. });
  776. it("surfaces a hand-broken metadata block as a fixable file, not a missing workflow", async () => {
  777. const cwd = makeCwd();
  778. saveSavedWorkflow({
  779. cwd,
  780. name: "mangled",
  781. meta: { description: "fine" },
  782. script: cleanScript("saved-mangled"),
  783. });
  784. writeFileSync(savedPath(cwd, "mangled"), "return 1;\n", "utf8");
  785. const outcome = await run({
  786. input: { saved: { name: "mangled" } },
  787. name: "create-saved-mangled",
  788. toolName: "CreateWorkflow",
  789. workingDirectory: cwd,
  790. });
  791. const message = outcome.result.error?.message ?? "";
  792. expect(message).toContain("could not be read");
  793. expect(message).toContain("hand-edited");
  794. });
  795. // 保存的定义编不过是**它的**问题;不点名文件的话模型会以为是自己写错了然后原样重试。
  796. it("blames the saved file when the stored script no longer compiles", async () => {
  797. const cwd = makeCwd();
  798. saveSavedWorkflow({
  799. cwd,
  800. name: "rotten",
  801. meta: { description: "was fine once" },
  802. script: 'const rotten: number = "not a number";',
  803. });
  804. const { port, submits } = stubRunPort("dwfrun-rotten");
  805. const outcome = await run({
  806. dynamicWorkflowRunPort: port,
  807. input: { saved: { name: "rotten" } },
  808. name: "create-saved-rotten",
  809. toolName: "CreateWorkflow",
  810. workingDirectory: cwd,
  811. });
  812. expect(outcome.permissionRequested).toHaveLength(0);
  813. expect(submits).toHaveLength(0);
  814. expect(outcome.result.success).toBe(true);
  815. const output = outcome.result.output as CreateWorkflowOutput;
  816. expect(output.ok).toBe(false);
  817. expect(output.response).toContain("The saved workflow 'rotten'");
  818. expect(output.response).toContain(savedPath(cwd, "rotten"));
  819. // 改动之后这条路径也有文件可改了:拷贝的落点被点名,诊断按**拷贝的文件行**报,
  820. // 而改定义本身仍要走 SaveWorkflow(docs/dynamic-workflow/launch.md「Script files」)。
  821. const draft = join(WORKFLOW_DRAFTS_DIR, "rotten.dwf.ts");
  822. expect(output.response).toContain(`A working copy of the saved workflow 'rotten'`);
  823. expect(output.response).toContain(`was written to ${draft}`);
  824. expect(output.response).toContain("use SaveWorkflow");
  825. // 正文第 1 行的诊断 = 文件第 4 行(起始标记 + description + 终止行)。
  826. expect(output.diagnostics[0]!.line).toBe(1);
  827. expect(output.response).toContain(`${draft}:L4:C7`);
  828. });
  829. // 内联路径零回归:模型写的字段一个字节不变(resolveInput 只补确认窗可调设置这条解析事实),且一次盘操作都不做。
  830. it("leaves the inline path byte-for-byte untouched", async () => {
  831. const cwd = makeCwd();
  832. const script = cleanScript("inline-regression");
  833. const { port, submits } = stubRunPort("dwfrun-inline");
  834. const outcome = await run({
  835. dynamicWorkflowRunPort: port,
  836. input: { script },
  837. name: "create-inline",
  838. toolName: "CreateWorkflow",
  839. workingDirectory: cwd,
  840. });
  841. expect(outcome.permissionRequested[0]!.input).toEqual({
  842. script,
  843. adjustable_settings: { subagent_model: false },
  844. });
  845. expect(submits[0]!.scriptText).toBe(script);
  846. expect("name" in submits[0]!).toBe(false);
  847. expect("args" in submits[0]!).toBe(false);
  848. // 归一化仍是恒等函数——确认窗看到的入参逐字节就是模型发出的那一份(上面那条断言)。
  849. // 盘上唯一多出来的是 handler 写的那份草稿:脚本的家,模型下一次据它走 `path`
  850. // (docs/dynamic-workflow/launch.md「Script files」)。
  851. const draft = join(cwd, WORKFLOW_DRAFTS_DIR, "workflow.dwf.ts");
  852. expect(readFileSync(draft, "utf8")).toBe(script);
  853. expect(submits[0]!.scriptPath).toBe(draft);
  854. expect(existsSync(join(cwd, ".zcode", "workflows"))).toBe(false);
  855. });
  856. // 「没给」与「多给」分开报:`{}` 也是参数 JSON 解析失败后 adapter 恢复出的形状,那句话要说出
  857. // 这个原因;「多给」只是选择要撤回,不该扯上 JSON。
  858. it.each([
  859. ["neither", {}, CREATE_WORKFLOW_SOURCE_MISSING_ERROR],
  860. ["only-settings", { max_concurrency: 2 }, CREATE_WORKFLOW_SOURCE_MISSING_ERROR],
  861. ["both", { script: "return 1;", saved: { name: "x" } }, CREATE_WORKFLOW_SOURCE_CONFLICT_ERROR],
  862. [
  863. "all-three",
  864. { script: "return 1;", saved: { name: "x" }, path: "a.dwf.ts" },
  865. CREATE_WORKFLOW_SOURCE_CONFLICT_ERROR,
  866. ],
  867. ])(
  868. "ends a %s-source call before the gate with its own actionable message",
  869. async (label, input, message) => {
  870. const outcome = await run({
  871. input,
  872. name: `create-source-${label}`,
  873. toolName: "CreateWorkflow",
  874. workingDirectory: makeCwd(),
  875. });
  876. expect(outcome.permissionRequested).toHaveLength(0);
  877. expect(outcome.result.success).toBe(false);
  878. expect(outcome.result.error?.message).toContain(message);
  879. },
  880. );
  881. it("names the unparsed-arguments cause only when no source arrived", () => {
  882. expect(CREATE_WORKFLOW_SOURCE_MISSING_ERROR).toContain(WORKFLOW_SOURCE_MISSING_HINT);
  883. expect(CREATE_WORKFLOW_SOURCE_CONFLICT_ERROR).not.toContain(WORKFLOW_SOURCE_MISSING_HINT);
  884. });
  885. });
  886. describe("CreateWorkflow input schema", () => {
  887. // XOR 刻意**不**在 schema 上:归一化输入同时带 script 与 saved,是合法执行态。
  888. // 一条 superRefine 会在 handler 的 parse 与 hook 改写后的二次校验上把它炸掉。
  889. it("accepts the normalized shape carrying both script and saved", () => {
  890. const parsed = CreateWorkflowInputSchema.safeParse({
  891. name: "nightly",
  892. script: "return 1;",
  893. saved: {
  894. name: "nightly",
  895. args: { a: 1 },
  896. path: "/p/.zcode/workflows/nightly.dwf.ts",
  897. scope: "project",
  898. },
  899. });
  900. expect(parsed.success).toBe(true);
  901. });
  902. it("still rejects unknown top-level keys", () => {
  903. expect(CreateWorkflowInputSchema.safeParse({ script: "return 1;", cwd: "/tmp" }).success).toBe(
  904. false,
  905. );
  906. });
  907. });
  908. describe("built-in tool registry", () => {
  909. it("registers the two new saved-workflow tools", () => {
  910. const names = builtInTools.map((entry) => entry.metadata.name);
  911. expect(names).toContain("SaveWorkflow");
  912. expect(names).toContain("ListSavedWorkflows");
  913. });
  914. // SaveWorkflow 写用户的仓库:与 CreateWorkflow 同档,任何权限模式都要先问。
  915. it("gates SaveWorkflow in every permission mode, without an always-allow option", () => {
  916. expect(saveWorkflowToolEntry.permission?.alwaysAsk).toBe(true);
  917. expect(saveWorkflowToolEntry.permission?.askOptions?.allowAlways).toBe(false);
  918. // CreateWorkflow 当年的 "none" 是占位期遗留,不该被抄:这个工具真的往工作区写文件。
  919. expect(saveWorkflowToolEntry.metadata.sideEffectScope).toBe("workspace");
  920. expect(saveWorkflowToolEntry.permission?.sideEffectScope).toBe("workspace");
  921. });
  922. // 读清单不写不跑:那两道 gate 的理由(写仓库 / 执行代码)都不适用。
  923. it("leaves ListSavedWorkflows ungated and read-only", () => {
  924. expect(listSavedWorkflowsToolEntry.metadata.readOnly).toBe(true);
  925. expect(listSavedWorkflowsToolEntry.metadata.needsApproval).toBe(false);
  926. expect(listSavedWorkflowsToolEntry.permission?.alwaysAsk).toBeUndefined();
  927. });
  928. // 引导文案的存在性(钉关键词,不钉逐字)。
  929. it("tells the model to ask before saving, and to consider saved workflows first", () => {
  930. expect(saveWorkflowToolEntry.metadata.description).toContain(
  931. "NEVER call this tool unsolicited",
  932. );
  933. expect(saveWorkflowToolEntry.metadata.description).toContain(
  934. "suggest saving it in one sentence and wait",
  935. );
  936. expect(createWorkflowToolEntry.metadata.description).toContain("ListSavedWorkflows");
  937. expect(createWorkflowToolEntry.metadata.description).toContain("exactly one source");
  938. });
  939. });