saved-workflow-tools.test.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. // 无同名时 shadowing 键缺席(不挂噪音字段)。
  416. it("omits the shadowing key when no other scope has the name", async () => {
  417. const cwd = makeCwd();
  418. const outcome = await run({
  419. input: {
  420. name: "solo",
  421. description: "unique",
  422. script: cleanScript("save-solo"),
  423. scope: "project",
  424. },
  425. name: "save-solo",
  426. toolName: "SaveWorkflow",
  427. workingDirectory: cwd,
  428. });
  429. expect("shadowing" in (outcome.permissionRequested[0]!.input as object)).toBe(false);
  430. });
  431. });
  432. describe("ListSavedWorkflows", () => {
  433. it("lists definitions with their arguments and never the script body", async () => {
  434. const cwd = makeCwd();
  435. saveSavedWorkflow({
  436. cwd,
  437. name: "triage",
  438. meta: {
  439. description: "Triage the inbox",
  440. whenToUse: "Every morning",
  441. args: { limit: { type: "number", default: 10 } },
  442. },
  443. script: cleanScript("list-triage"),
  444. });
  445. const outcome = await run({
  446. input: {},
  447. name: "list-saved",
  448. toolName: "ListSavedWorkflows",
  449. workingDirectory: cwd,
  450. });
  451. expect(outcome.permissionRequested).toHaveLength(0);
  452. const output = outcome.result.output as ListSavedWorkflowsOutput;
  453. expect(output.workflows).toHaveLength(1);
  454. expect(output.workflows[0]!.name).toBe("triage");
  455. expect(output.invalid).toBeUndefined();
  456. const modelContent = String(outcome.result.modelContent ?? "");
  457. expect(modelContent).toContain('name="triage"');
  458. expect(modelContent).toContain("Triage the inbox");
  459. expect(modelContent).toContain("arg limit (number, default 10)");
  460. expect(modelContent).not.toContain("agent(");
  461. });
  462. it("says so in a sentence when the project has no saved workflows", async () => {
  463. const outcome = await run({
  464. input: {},
  465. name: "list-saved-empty",
  466. toolName: "ListSavedWorkflows",
  467. workingDirectory: makeCwd(),
  468. });
  469. expect((outcome.result.output as ListSavedWorkflowsOutput).workflows).toEqual([]);
  470. expect(String(outcome.result.modelContent ?? "")).toContain("No workflows are saved");
  471. });
  472. // 与 ListWorkflowRuns 同一条收敛:工具恒查会话工作目录,模型无权跨项目扫盘。
  473. it("rejects a cwd input outright", async () => {
  474. const outcome = await run({
  475. input: { cwd: "/etc" },
  476. name: "list-saved-cwd",
  477. toolName: "ListSavedWorkflows",
  478. workingDirectory: makeCwd(),
  479. });
  480. expect(outcome.result.success).toBe(false);
  481. });
  482. });
  483. describe("CreateWorkflow saved source", () => {
  484. it("normalizes the gate input to the resolved script, the saved name and the checked args", async () => {
  485. const cwd = makeCwd();
  486. const script = cleanScript("saved-happy");
  487. saveSavedWorkflow({
  488. cwd,
  489. name: "nightly",
  490. meta: { description: "nightly triage", args: { depth: { type: "number", default: 3 } } },
  491. script,
  492. });
  493. const { port, submits } = stubRunPort("dwfrun-saved");
  494. const outcome = await run({
  495. dynamicWorkflowRunPort: port,
  496. input: { saved: { name: "nightly" } },
  497. name: "create-saved-happy",
  498. toolName: "CreateWorkflow",
  499. workingDirectory: cwd,
  500. });
  501. expect(outcome.permissionRequested).toHaveLength(1);
  502. // 归一化 (b) 的核心:旧桌面的 readWorkflowScript(raw.script) / readWorkflowName(raw.name)
  503. // 就是读这两个键——它们命中是**构造上**成立的,不是兼容处理。
  504. expect(outcome.permissionRequested[0]!.input).toEqual({
  505. name: "nightly",
  506. script,
  507. saved: {
  508. name: "nightly",
  509. args: { depth: 3 },
  510. path: savedPath(cwd, "nightly"),
  511. scope: "project",
  512. // 工作副本在 resolveInput 里随这次读一起写下(docs/dynamic-workflow/launch.md
  513. // 「Script files」):模型要改的是这份拷贝,保存的定义一个字都不动。
  514. draft: join(cwd, WORKFLOW_DRAFTS_DIR, "nightly.dwf.ts"),
  515. },
  516. // 拷贝带着元数据块,所以诊断的文件行要跳过块的那几行。
  517. script_line_offset: expect.any(Number),
  518. // 确认窗可调的设置(docs/dynamic-workflow/launch.md「Adjusting the settings in the window」):
  519. // 桩 run port 没有模型目录、也报不出天花板,所以只能调上界、没有上限。
  520. adjustable_settings: { subagent_model: false },
  521. });
  522. // 拷贝逐字节等于定义文件本身。
  523. expect(readFileSync(join(cwd, WORKFLOW_DRAFTS_DIR, "nightly.dwf.ts"), "utf8")).toBe(
  524. readFileSync(savedPath(cwd, "nightly"), "utf8"),
  525. );
  526. expect(outcome.result.success).toBe(true);
  527. const output = outcome.result.output as CreateWorkflowOutput;
  528. expect(output.status).toBe("backgrounded");
  529. expect(submits).toHaveLength(1);
  530. expect(submits[0]!.scriptText).toBe(script);
  531. expect(submits[0]!.name).toBe("nightly");
  532. // 实参走 name / scriptText 同一条元数据路,落 dwf_run.args_json 并注入沙箱。
  533. expect(submits[0]!.args).toEqual({ depth: 3 });
  534. });
  535. // 不变式 8 的钉子:saved 与内联产出的 display 必须逐字节相同,本特性一个字段都不加。
  536. it("produces a display byte-identical to the same script run inline", async () => {
  537. const cwd = makeCwd();
  538. const script = cleanScript("saved-parity");
  539. saveSavedWorkflow({ cwd, name: "parity", meta: { description: "parity" }, script });
  540. const { port } = stubRunPort("dwfrun-parity");
  541. const viaSaved = await run({
  542. dynamicWorkflowRunPort: port,
  543. input: { saved: { name: "parity" } },
  544. name: "create-parity-saved",
  545. toolName: "CreateWorkflow",
  546. workingDirectory: cwd,
  547. });
  548. const viaInline = await run({
  549. dynamicWorkflowRunPort: port,
  550. input: { script },
  551. name: "create-parity-inline",
  552. toolName: "CreateWorkflow",
  553. workingDirectory: cwd,
  554. });
  555. const savedDisplay = viaSaved.permissionRequested[0]!.display;
  556. expect(savedDisplay).toEqual(viaInline.permissionRequested[0]!.display);
  557. expect(Object.keys(savedDisplay as object).sort()).toEqual([
  558. "causalityGraph",
  559. "diagnostics",
  560. "errorCount",
  561. "kind",
  562. "ok",
  563. ]);
  564. });
  565. // 归一化 (e):策略不被保存绕开。一条扫描脚本的 PreToolUse hook 在 saved run 上必须
  566. // 看到真正的脚本——否则保存就成了一条策略盲区。
  567. it("gives PreToolUse hooks the resolved script, not just the saved name", async () => {
  568. const cwd = makeCwd();
  569. const script = cleanScript("saved-hook");
  570. saveSavedWorkflow({ cwd, name: "policed", meta: { description: "policed" }, script });
  571. const seen: unknown[] = [];
  572. const hookRunner: HookRunner = {
  573. async run(input) {
  574. if (input.hookEventName === HookEventName.PreToolUse) {
  575. seen.push((input as unknown as { toolInput?: unknown }).toolInput);
  576. }
  577. return { additionalContexts: [] };
  578. },
  579. };
  580. await run({
  581. dynamicWorkflowRunPort: stubRunPort("dwfrun-hook").port,
  582. hookRunner,
  583. input: { saved: { name: "policed" } },
  584. name: "create-saved-hook",
  585. toolName: "CreateWorkflow",
  586. workingDirectory: cwd,
  587. });
  588. expect(seen).toHaveLength(1);
  589. expect((seen[0] as { script?: string }).script).toBe(script);
  590. });
  591. // 不变式 5:确认与执行同字节。解析只发生一次,批准之后不再读盘。
  592. it("runs the bytes shown at the gate even if the file changes after resolution", async () => {
  593. const cwd = makeCwd();
  594. const approved = cleanScript("saved-toctou");
  595. saveSavedWorkflow({ cwd, name: "swapped", meta: { description: "swapped" }, script: approved });
  596. const { port, submits } = stubRunPort("dwfrun-toctou");
  597. const outcome = await run({
  598. broker: {
  599. async requestPermission() {
  600. // 用户思考的这段时间里,磁盘上的文件被换掉了。
  601. saveSavedWorkflow({
  602. cwd,
  603. name: "swapped",
  604. meta: { description: "swapped" },
  605. script: cleanScript("saved-toctou-evil"),
  606. });
  607. return { decision: "allow" };
  608. },
  609. },
  610. dynamicWorkflowRunPort: port,
  611. input: { saved: { name: "swapped" } },
  612. name: "create-saved-toctou",
  613. toolName: "CreateWorkflow",
  614. workingDirectory: cwd,
  615. });
  616. expect(outcome.result.success).toBe(true);
  617. expect(submits[0]!.scriptText).toBe(approved);
  618. expect(submits[0]!.scriptText).not.toContain("saved-toctou-evil");
  619. });
  620. it("lets an explicit name override the saved name as the run label", async () => {
  621. const cwd = makeCwd();
  622. saveSavedWorkflow({
  623. cwd,
  624. name: "generic",
  625. meta: { description: "generic" },
  626. script: cleanScript("saved-label"),
  627. });
  628. const { port, submits } = stubRunPort("dwfrun-label");
  629. await run({
  630. dynamicWorkflowRunPort: port,
  631. input: { name: "tuesday run", saved: { name: "generic" } },
  632. name: "create-saved-label",
  633. toolName: "CreateWorkflow",
  634. workingDirectory: cwd,
  635. });
  636. expect(submits[0]!.name).toBe("tuesday run");
  637. });
  638. // 参数传错没有任何值得用户裁决的东西:弹一个注定失败的窗只是打断模型的改错回路。
  639. it("rejects bad arguments before the gate, naming the declaration", async () => {
  640. const cwd = makeCwd();
  641. saveSavedWorkflow({
  642. cwd,
  643. name: "strict-args",
  644. meta: {
  645. description: "takes args",
  646. args: { pr: { type: "string", required: true, description: "PR number" } },
  647. },
  648. script: cleanScript("saved-bad-args"),
  649. });
  650. const { port, submits } = stubRunPort("dwfrun-bad-args");
  651. const outcome = await run({
  652. dynamicWorkflowRunPort: port,
  653. input: { saved: { name: "strict-args", args: { pull: "42" } } },
  654. name: "create-saved-bad-args",
  655. toolName: "CreateWorkflow",
  656. workingDirectory: cwd,
  657. });
  658. expect(outcome.permissionRequested).toHaveLength(0);
  659. expect(submits).toHaveLength(0);
  660. expect(outcome.result.success).toBe(false);
  661. const message = outcome.result.error?.message ?? "";
  662. expect(message).toContain("unknown argument 'pull'");
  663. expect(message).toContain("missing required argument 'pr'");
  664. // 声明复述让模型一次改对,而不是再猜一轮。
  665. expect(message).toContain("PR number");
  666. });
  667. // 猜错名字之后最有用的下一步信息就是正确的那一批。
  668. it("names the available workflows when the requested one does not exist", async () => {
  669. const cwd = makeCwd();
  670. saveSavedWorkflow({
  671. cwd,
  672. name: "actual",
  673. meta: { description: "the real one" },
  674. script: cleanScript("saved-missing"),
  675. });
  676. const { port, submits } = stubRunPort("dwfrun-missing");
  677. const outcome = await run({
  678. dynamicWorkflowRunPort: port,
  679. input: { saved: { name: "typo" } },
  680. name: "create-saved-missing",
  681. toolName: "CreateWorkflow",
  682. workingDirectory: cwd,
  683. });
  684. expect(outcome.permissionRequested).toHaveLength(0);
  685. expect(submits).toHaveLength(0);
  686. expect(outcome.result.success).toBe(false);
  687. const message = outcome.result.error?.message ?? "";
  688. expect(message).toContain("No saved workflow named 'typo'");
  689. expect(message).toContain("Available saved workflows: actual");
  690. });
  691. it("points at SaveWorkflow when the project has no saved workflows at all", async () => {
  692. const outcome = await run({
  693. input: { saved: { name: "anything" } },
  694. name: "create-saved-none",
  695. toolName: "CreateWorkflow",
  696. workingDirectory: makeCwd(),
  697. });
  698. expect(outcome.result.error?.message ?? "").toContain("no saved workflows yet");
  699. });
  700. // saved.scope 定向:同名两档时指定 global 跳过遮蔽,跑的是全局那份。
  701. it("takes the global copy when saved.scope is global despite a project shadow", async () => {
  702. const cwd = makeCwd();
  703. const projectScript = cleanScript("saved-scope-project");
  704. const globalScript = cleanScript("saved-scope-global");
  705. saveSavedWorkflow({
  706. cwd,
  707. name: "dup",
  708. meta: { description: "project" },
  709. script: projectScript,
  710. });
  711. saveSavedWorkflow({
  712. cwd,
  713. name: "dup",
  714. meta: { description: "global" },
  715. script: globalScript,
  716. scope: "global",
  717. });
  718. const { port, submits } = stubRunPort("dwfrun-scope-global");
  719. const outcome = await run({
  720. dynamicWorkflowRunPort: port,
  721. input: { saved: { name: "dup", scope: "global" } },
  722. name: "create-saved-scope-global",
  723. toolName: "CreateWorkflow",
  724. workingDirectory: cwd,
  725. });
  726. expect(outcome.permissionRequested).toHaveLength(1);
  727. const gateSaved = (
  728. outcome.permissionRequested[0]!.input as { saved: { scope: string; path: string } }
  729. ).saved;
  730. expect(gateSaved.scope).toBe("global");
  731. expect(gateSaved.path).toBe(globalSavedPath("dup"));
  732. expect(submits[0]!.scriptText).toBe(globalScript);
  733. });
  734. // 缺省走 first-wins:同名两档时项目档遮蔽全局档,跑的是项目那份。
  735. it("takes the project copy by default when both scopes carry the name", async () => {
  736. const cwd = makeCwd();
  737. const projectScript = cleanScript("saved-default-project");
  738. saveSavedWorkflow({
  739. cwd,
  740. name: "dup",
  741. meta: { description: "project" },
  742. script: projectScript,
  743. });
  744. saveSavedWorkflow({
  745. cwd,
  746. name: "dup",
  747. meta: { description: "global" },
  748. script: cleanScript("saved-default-global"),
  749. scope: "global",
  750. });
  751. const { port, submits } = stubRunPort("dwfrun-scope-default");
  752. const outcome = await run({
  753. dynamicWorkflowRunPort: port,
  754. input: { saved: { name: "dup" } },
  755. name: "create-saved-scope-default",
  756. toolName: "CreateWorkflow",
  757. workingDirectory: cwd,
  758. });
  759. const gateSaved = (outcome.permissionRequested[0]!.input as { saved: { scope: string } }).saved;
  760. expect(gateSaved.scope).toBe("project");
  761. expect(submits[0]!.scriptText).toBe(projectScript);
  762. });
  763. // 定向找不到:文案说「该作用域下没有」,并列出两档可用名字(带标签)。
  764. it("names the scope and lists both archives when a directed lookup misses", async () => {
  765. const cwd = makeCwd();
  766. saveSavedWorkflow({
  767. cwd,
  768. name: "in-project",
  769. meta: { description: "p" },
  770. script: cleanScript("saved-directed-p"),
  771. });
  772. saveSavedWorkflow({
  773. cwd,
  774. name: "in-global",
  775. meta: { description: "g" },
  776. script: cleanScript("saved-directed-g"),
  777. scope: "global",
  778. });
  779. const outcome = await run({
  780. input: { saved: { name: "ghost", scope: "global" } },
  781. name: "create-saved-directed-miss",
  782. toolName: "CreateWorkflow",
  783. workingDirectory: cwd,
  784. });
  785. expect(outcome.result.success).toBe(false);
  786. const message = outcome.result.error?.message ?? "";
  787. expect(message).toContain("No global workflow named 'ghost'");
  788. expect(message).toContain("in-project (project)");
  789. expect(message).toContain("in-global (global)");
  790. });
  791. it("surfaces a hand-broken metadata block as a fixable file, not a missing workflow", async () => {
  792. const cwd = makeCwd();
  793. saveSavedWorkflow({
  794. cwd,
  795. name: "mangled",
  796. meta: { description: "fine" },
  797. script: cleanScript("saved-mangled"),
  798. });
  799. writeFileSync(savedPath(cwd, "mangled"), "return 1;\n", "utf8");
  800. const outcome = await run({
  801. input: { saved: { name: "mangled" } },
  802. name: "create-saved-mangled",
  803. toolName: "CreateWorkflow",
  804. workingDirectory: cwd,
  805. });
  806. const message = outcome.result.error?.message ?? "";
  807. expect(message).toContain("could not be read");
  808. expect(message).toContain("hand-edited");
  809. });
  810. // 保存的定义编不过是**它的**问题;不点名文件的话模型会以为是自己写错了然后原样重试。
  811. it("blames the saved file when the stored script no longer compiles", async () => {
  812. const cwd = makeCwd();
  813. saveSavedWorkflow({
  814. cwd,
  815. name: "rotten",
  816. meta: { description: "was fine once" },
  817. script: 'const rotten: number = "not a number";',
  818. });
  819. const { port, submits } = stubRunPort("dwfrun-rotten");
  820. const outcome = await run({
  821. dynamicWorkflowRunPort: port,
  822. input: { saved: { name: "rotten" } },
  823. name: "create-saved-rotten",
  824. toolName: "CreateWorkflow",
  825. workingDirectory: cwd,
  826. });
  827. expect(outcome.permissionRequested).toHaveLength(0);
  828. expect(submits).toHaveLength(0);
  829. expect(outcome.result.success).toBe(true);
  830. const output = outcome.result.output as CreateWorkflowOutput;
  831. expect(output.ok).toBe(false);
  832. expect(output.response).toContain("The saved workflow 'rotten'");
  833. expect(output.response).toContain(savedPath(cwd, "rotten"));
  834. // 改动之后这条路径也有文件可改了:拷贝的落点被点名,诊断按**拷贝的文件行**报,
  835. // 而改定义本身仍要走 SaveWorkflow(docs/dynamic-workflow/launch.md「Script files」)。
  836. const draft = join(WORKFLOW_DRAFTS_DIR, "rotten.dwf.ts");
  837. expect(output.response).toContain(`A working copy of the saved workflow 'rotten'`);
  838. expect(output.response).toContain(`was written to ${draft}`);
  839. expect(output.response).toContain("use SaveWorkflow");
  840. // 正文第 1 行的诊断 = 文件第 4 行(起始标记 + description + 终止行)。
  841. expect(output.diagnostics[0]!.line).toBe(1);
  842. expect(output.response).toContain(`${draft}:L4:C7`);
  843. });
  844. // 内联路径零回归:模型写的字段一个字节不变(resolveInput 只补确认窗可调设置这条解析事实),且一次盘操作都不做。
  845. it("leaves the inline path byte-for-byte untouched", async () => {
  846. const cwd = makeCwd();
  847. const script = cleanScript("inline-regression");
  848. const { port, submits } = stubRunPort("dwfrun-inline");
  849. const outcome = await run({
  850. dynamicWorkflowRunPort: port,
  851. input: { script },
  852. name: "create-inline",
  853. toolName: "CreateWorkflow",
  854. workingDirectory: cwd,
  855. });
  856. expect(outcome.permissionRequested[0]!.input).toEqual({
  857. script,
  858. adjustable_settings: { subagent_model: false },
  859. });
  860. expect(submits[0]!.scriptText).toBe(script);
  861. expect("name" in submits[0]!).toBe(false);
  862. expect("args" in submits[0]!).toBe(false);
  863. // 归一化仍是恒等函数——确认窗看到的入参逐字节就是模型发出的那一份(上面那条断言)。
  864. // 盘上唯一多出来的是 handler 写的那份草稿:脚本的家,模型下一次据它走 `path`
  865. // (docs/dynamic-workflow/launch.md「Script files」)。
  866. const draft = join(cwd, WORKFLOW_DRAFTS_DIR, "workflow.dwf.ts");
  867. expect(readFileSync(draft, "utf8")).toBe(script);
  868. expect(submits[0]!.scriptPath).toBe(draft);
  869. expect(existsSync(join(cwd, ".zcode", "workflows"))).toBe(false);
  870. });
  871. it.each([
  872. ["neither", {}],
  873. ["both", { script: "return 1;", saved: { name: "x" } }],
  874. ])("ends a %s-source call before the gate with one actionable message", async (label, input) => {
  875. const outcome = await run({
  876. input,
  877. name: `create-source-${label}`,
  878. toolName: "CreateWorkflow",
  879. workingDirectory: makeCwd(),
  880. });
  881. expect(outcome.permissionRequested).toHaveLength(0);
  882. expect(outcome.result.success).toBe(false);
  883. expect(outcome.result.error?.message).toContain(CREATE_WORKFLOW_SOURCE_ERROR);
  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. });