saved-workflow-tools.test.ts 36 KB

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