workflow-script-file-sources.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. import {
  2. mkdirSync,
  3. mkdtempSync,
  4. readFileSync,
  5. readdirSync,
  6. rmSync,
  7. writeFileSync,
  8. } from "node:fs";
  9. import { tmpdir } from "node:os";
  10. import { join } from "node:path";
  11. import { afterEach, describe, expect, it } from "vitest";
  12. import {
  13. SessionEventType,
  14. WORKFLOW_DRAFTS_DIR,
  15. createRootTraceContext,
  16. createSessionId,
  17. createToolCallId,
  18. createTurnId,
  19. type CreateWorkflowOutput,
  20. type DynamicWorkflowRunAmendRequest,
  21. type DynamicWorkflowRunPort,
  22. type DynamicWorkflowRunSnapshot,
  23. type DynamicWorkflowRunSubmitRequest,
  24. type PermissionRequestedPayload,
  25. type SaveWorkflowOutput,
  26. type SessionEvent,
  27. type ToolExecutionResult,
  28. } from "@zcode/contracts";
  29. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  30. import { createToolExecutor } from "../src/tool/executor.js";
  31. import { amendWorkflowToolEntry } from "../src/tool/handlers/amend-workflow.js";
  32. import { createWorkflowToolEntry } from "../src/tool/handlers/create-workflow.js";
  33. import { saveWorkflowToolEntry } from "../src/tool/handlers/save-workflow.js";
  34. import {
  35. saveSavedWorkflow,
  36. serializeSavedWorkflow,
  37. } from "../src/tool/handlers/saved-workflows/index.js";
  38. import { createToolRegistry } from "../src/tool/registry.js";
  39. // docs/dynamic-workflow/launch.md「Script files」:每一段脚本都有个盘上的家,而那个文件就是
  40. // 模型两次提交之间的把手。这里端到端地钉四件事:草稿真的被写下来、诊断按文件行报、`path`
  41. // 回程真的能跑、以及「文件没改过」的修订被挡在任何窗口之前。
  42. const cwds: string[] = [];
  43. function makeCwd(): string {
  44. const dir = mkdtempSync(join(tmpdir(), "dwf-file-sources-"));
  45. cwds.push(dir);
  46. return dir;
  47. }
  48. afterEach(() => {
  49. while (cwds.length > 0) rmSync(cwds.pop()!, { force: true, recursive: true });
  50. });
  51. /** 记忆槽按脚本原文取键,所以每个用例用自己的脚本。 */
  52. function cleanScript(actor: string): string {
  53. return [
  54. "interface R { done: boolean }",
  55. `const r = await agent("${actor}").ask<R>("do");`,
  56. "return r.done;",
  57. ].join("\n");
  58. }
  59. const BROKEN_SCRIPT = 'const broken: number = "not a number";';
  60. function draftPath(cwd: string, fileName: string): string {
  61. return join(cwd, WORKFLOW_DRAFTS_DIR, fileName);
  62. }
  63. interface StubPort {
  64. port: DynamicWorkflowRunPort;
  65. submits: DynamicWorkflowRunSubmitRequest[];
  66. amends: DynamicWorkflowRunAmendRequest[];
  67. getScriptCalls: string[];
  68. }
  69. /** run 端口桩。`runScript` 缺席即端口**没有** `getScript`(老宿主的形状)。 */
  70. function stubRunPort(
  71. options: { runScript?: string; snapshot?: Partial<DynamicWorkflowRunSnapshot> } = {},
  72. ): StubPort {
  73. const submits: DynamicWorkflowRunSubmitRequest[] = [];
  74. const amends: DynamicWorkflowRunAmendRequest[] = [];
  75. const getScriptCalls: string[] = [];
  76. const port = {
  77. async submit(request: DynamicWorkflowRunSubmitRequest) {
  78. submits.push(request);
  79. return { ok: true, runId: "dwfrun-new" };
  80. },
  81. async amend(request: DynamicWorkflowRunAmendRequest) {
  82. amends.push(request);
  83. return { ok: true, runId: "dwfrun-amended" };
  84. },
  85. async getTask(taskId: string) {
  86. return {
  87. runId: taskId,
  88. taskId,
  89. startedAt: new Date(0),
  90. status: "running",
  91. ...options.snapshot,
  92. } as DynamicWorkflowRunSnapshot;
  93. },
  94. ...(options.runScript === undefined
  95. ? {}
  96. : {
  97. async getScript(runId: string) {
  98. getScriptCalls.push(runId);
  99. return options.runScript;
  100. },
  101. }),
  102. } as unknown as DynamicWorkflowRunPort;
  103. return { port, submits, amends, getScriptCalls };
  104. }
  105. interface RunOutcome {
  106. permissionRequested: PermissionRequestedPayload[];
  107. result: ToolExecutionResult;
  108. }
  109. async function run(options: {
  110. input: Record<string, unknown>;
  111. name: string;
  112. port?: DynamicWorkflowRunPort;
  113. toolName: string;
  114. workingDirectory: string;
  115. }): Promise<RunOutcome> {
  116. const sessionId = createSessionId(options.name);
  117. const turnId = createTurnId(options.name);
  118. const traceContext = createRootTraceContext({ sessionId, turnId });
  119. const events: SessionEvent[] = [];
  120. const registry = createToolRegistry();
  121. registry.register(createWorkflowToolEntry);
  122. registry.register(amendWorkflowToolEntry);
  123. registry.register(saveWorkflowToolEntry);
  124. const executor = createToolExecutor({
  125. emitEvent: async (event) => {
  126. events.push(event);
  127. },
  128. ...(options.port ? { dynamicWorkflowRunPort: options.port } : {}),
  129. mode: "build",
  130. permissionBroker: {
  131. async requestPermission() {
  132. return { decision: "allow" as const };
  133. },
  134. },
  135. permissionService: new PermissionService(defaultPermissionConfig),
  136. registry,
  137. sessionId,
  138. turnId,
  139. traceContext,
  140. workingDirectory: options.workingDirectory,
  141. });
  142. const result = await executor.execute(
  143. { id: createToolCallId(options.name), input: options.input, name: options.toolName },
  144. { traceContext },
  145. );
  146. return {
  147. permissionRequested: events
  148. .filter((event) => event.type === SessionEventType.PermissionRequested)
  149. .map((event) => event.payload as PermissionRequestedPayload),
  150. result,
  151. };
  152. }
  153. describe("CreateWorkflow — source XOR and args", () => {
  154. // 「没给」单独成句(参数 JSON 没解析出来时 adapter 恢复成的就是 `{}`),「多给」保持原句。
  155. it.each([
  156. [
  157. "all three",
  158. { script: "return 1;", saved: { name: "x" }, path: "a.dwf.ts" },
  159. "exactly one workflow source",
  160. ],
  161. ["script and path", { script: "return 1;", path: "a.dwf.ts" }, "exactly one workflow source"],
  162. ["saved and path", { saved: { name: "x" }, path: "a.dwf.ts" }, "exactly one workflow source"],
  163. ["none", {}, "No workflow source arrived"],
  164. ])("refuses a %s call before the gate", async (label, input, message) => {
  165. const outcome = await run({
  166. input,
  167. name: `xor-${label.replace(/\s/gu, "-")}`,
  168. toolName: "CreateWorkflow",
  169. workingDirectory: makeCwd(),
  170. });
  171. expect(outcome.permissionRequested).toHaveLength(0);
  172. expect(outcome.result.success).toBe(false);
  173. expect(outcome.result.error?.message ?? "").toContain(message);
  174. });
  175. it("refuses `args` without `path`: a saved call has `saved.args`, an inline script has none", async () => {
  176. const outcome = await run({
  177. input: { script: "return 1;", args: { pr: "1" } },
  178. name: "args-without-path",
  179. toolName: "CreateWorkflow",
  180. workingDirectory: makeCwd(),
  181. });
  182. expect(outcome.permissionRequested).toHaveLength(0);
  183. expect(outcome.result.success).toBe(false);
  184. expect(outcome.result.error?.message ?? "").toContain("`args` belongs to the `path` source");
  185. });
  186. });
  187. describe("CreateWorkflow — inline drafts", () => {
  188. it("a non-compiling inline script still lands on disk, and the diagnostics point at that file", async () => {
  189. const cwd = makeCwd();
  190. const { port, submits } = stubRunPort();
  191. const outcome = await run({
  192. input: { name: "triage", script: BROKEN_SCRIPT },
  193. name: "inline-broken",
  194. port,
  195. toolName: "CreateWorkflow",
  196. workingDirectory: cwd,
  197. });
  198. expect(submits).toHaveLength(0);
  199. const output = outcome.result.output as CreateWorkflowOutput;
  200. expect(output.ok).toBe(false);
  201. const draft = draftPath(cwd, "triage.dwf.ts");
  202. expect(readFileSync(draft, "utf8")).toBe(BROKEN_SCRIPT);
  203. // 文案给的是工作区相对写法,行号按文件数(无元数据块,所以与正文行相同)。
  204. const described = join(WORKFLOW_DRAFTS_DIR, "triage.dwf.ts");
  205. expect(output.response).toContain(`${described}:L1:C`);
  206. expect(output.response).toContain(`The script is saved at ${described}.`);
  207. expect(output.response).toContain(`resubmit with \`path: "${described}"\``);
  208. expect(output.response).toContain("do not paste the script inline again");
  209. // display / 输出里的诊断数组仍按**正文行**:转录面画的是正文。
  210. expect(output.diagnostics[0]!.line).toBe(1);
  211. });
  212. it("a launched inline run records the draft and tells the model to edit it next time", async () => {
  213. const cwd = makeCwd();
  214. const script = cleanScript("inline-launch");
  215. const { port, submits } = stubRunPort();
  216. const outcome = await run({
  217. input: { name: "nightly", script },
  218. name: "inline-launch",
  219. port,
  220. toolName: "CreateWorkflow",
  221. workingDirectory: cwd,
  222. });
  223. const draft = draftPath(cwd, "nightly.dwf.ts");
  224. expect(submits[0]!.scriptPath).toBe(draft);
  225. expect(readFileSync(draft, "utf8")).toBe(script);
  226. const output = outcome.result.output as CreateWorkflowOutput;
  227. expect(output.status).toBe("backgrounded");
  228. expect(output.response).toContain(
  229. `The script is saved at ${join(WORKFLOW_DRAFTS_DIR, "nightly.dwf.ts")}; to revise it later, edit that file and pass \`path\` to AmendWorkflow.`,
  230. );
  231. });
  232. it("falls back to the old note, and to no scriptPath, when the draft cannot be written", async () => {
  233. const cwd = makeCwd();
  234. // `.zcode` 是个普通文件 → 草稿目录建不出来。尽力而为:调用照常完成。
  235. writeFileSync(join(cwd, ".zcode"), "not a directory", "utf8");
  236. const { port, submits } = stubRunPort();
  237. const broken = await run({
  238. input: { script: BROKEN_SCRIPT },
  239. name: "draft-write-failed",
  240. port,
  241. toolName: "CreateWorkflow",
  242. workingDirectory: cwd,
  243. });
  244. const brokenOutput = broken.result.output as CreateWorkflowOutput;
  245. expect(brokenOutput.response).toContain(
  246. "NOTE: The workflow was NOT executed — fix the errors above and resubmit.",
  247. );
  248. expect(brokenOutput.response).not.toContain("workflow-drafts");
  249. expect(brokenOutput.response).toContain("L1:C");
  250. const clean = await run({
  251. input: { script: cleanScript("no-draft") },
  252. name: "draft-write-failed-clean",
  253. port,
  254. toolName: "CreateWorkflow",
  255. workingDirectory: cwd,
  256. });
  257. expect(submits).toHaveLength(1);
  258. expect("scriptPath" in submits[0]!).toBe(false);
  259. expect((clean.result.output as CreateWorkflowOutput).response).not.toContain("edit that file");
  260. });
  261. });
  262. describe("CreateWorkflow — the `path` source", () => {
  263. it("accepts a workspace-relative path and runs the file's bytes", async () => {
  264. const cwd = makeCwd();
  265. const script = cleanScript("path-relative");
  266. mkdirSync(join(cwd, "scripts"));
  267. writeFileSync(join(cwd, "scripts", "check.dwf.ts"), script, "utf8");
  268. const { port, submits } = stubRunPort();
  269. const outcome = await run({
  270. input: { path: "scripts/check.dwf.ts" },
  271. name: "path-relative",
  272. port,
  273. toolName: "CreateWorkflow",
  274. workingDirectory: cwd,
  275. });
  276. // 归一化把文件读成 `script`,路径写成绝对形;确认窗看到的就是将要执行的字节。
  277. expect(outcome.permissionRequested[0]!.input).toEqual({
  278. script,
  279. path: join(cwd, "scripts", "check.dwf.ts"),
  280. // 确认窗可调的设置(docs/dynamic-workflow/launch.md「Adjusting the settings in the window」)。
  281. adjustable_settings: { subagent_model: false },
  282. });
  283. expect(submits[0]!.scriptText).toBe(script);
  284. expect(submits[0]!.scriptPath).toBe(join(cwd, "scripts", "check.dwf.ts"));
  285. // `path` 来源的文件不是工具写下的,所以说的是「脚本文件是 …」而不是「已保存到 …」。
  286. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  287. `The script file is ${join("scripts", "check.dwf.ts")};`,
  288. );
  289. // 已经是工作副本了,不再抄一份。
  290. expect(() => readFileSync(draftPath(cwd, "check.dwf.ts"), "utf8")).toThrow();
  291. });
  292. it("accepts an absolute path outside the workspace and reports it absolute", async () => {
  293. const cwd = makeCwd();
  294. const elsewhere = makeCwd();
  295. const script = cleanScript("path-absolute");
  296. const file = join(elsewhere, "outside.dwf.ts");
  297. writeFileSync(file, script, "utf8");
  298. const { port, submits } = stubRunPort();
  299. const outcome = await run({
  300. input: { path: file },
  301. name: "path-absolute",
  302. port,
  303. toolName: "CreateWorkflow",
  304. workingDirectory: cwd,
  305. });
  306. expect(submits[0]!.scriptPath).toBe(file);
  307. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  308. `The script file is ${file};`,
  309. );
  310. });
  311. it("parses a metadata block, validates `args` against it and reports diagnostics in file lines", async () => {
  312. const cwd = makeCwd();
  313. const body =
  314. 'const depth: number = args.depth as number;\nconst bad: number = "x";\nreturn depth;';
  315. const file = join(cwd, "with-meta.dwf.ts");
  316. writeFileSync(
  317. file,
  318. serializeSavedWorkflow(
  319. { description: "declared", args: { depth: { type: "number", default: 2 } } },
  320. body,
  321. ),
  322. "utf8",
  323. );
  324. const { port } = stubRunPort();
  325. const outcome = await run({
  326. input: { path: "with-meta.dwf.ts", args: { depth: 5 } },
  327. name: "path-meta",
  328. port,
  329. toolName: "CreateWorkflow",
  330. workingDirectory: cwd,
  331. });
  332. const output = outcome.result.output as CreateWorkflowOutput;
  333. expect(output.ok).toBe(false);
  334. // 正文第 2 行的诊断 = 文件第 2 + offset 行;offset 由元数据块的行数决定。
  335. const fileLines = readFileSync(file, "utf8").split("\n");
  336. const offset = fileLines.findIndex(
  337. (line) => line === "const depth: number = args.depth as number;",
  338. );
  339. expect(output.diagnostics[0]!.line).toBe(2);
  340. expect(output.response).toContain(`with-meta.dwf.ts:L${2 + offset}:C`);
  341. });
  342. it("runs a declared file with its arguments, defaults filled in", async () => {
  343. const cwd = makeCwd();
  344. writeFileSync(
  345. join(cwd, "declared.dwf.ts"),
  346. serializeSavedWorkflow(
  347. {
  348. description: "declared",
  349. args: {
  350. depth: { type: "number", default: 2 },
  351. target: { type: "string", required: true },
  352. },
  353. },
  354. cleanScript("declared"),
  355. ),
  356. "utf8",
  357. );
  358. const { port, submits } = stubRunPort();
  359. await run({
  360. input: { path: "declared.dwf.ts", args: { target: "pkg" } },
  361. name: "path-args",
  362. port,
  363. toolName: "CreateWorkflow",
  364. workingDirectory: cwd,
  365. });
  366. expect(submits[0]!.args).toEqual({ depth: 2, target: "pkg" });
  367. });
  368. it("rejects `args` for a file with no metadata block, before the gate", async () => {
  369. const cwd = makeCwd();
  370. writeFileSync(join(cwd, "plain.dwf.ts"), cleanScript("plain"), "utf8");
  371. const outcome = await run({
  372. input: { path: "plain.dwf.ts", args: { depth: 1 } },
  373. name: "path-args-undeclared",
  374. toolName: "CreateWorkflow",
  375. workingDirectory: cwd,
  376. });
  377. expect(outcome.permissionRequested).toHaveLength(0);
  378. expect(outcome.result.error?.message ?? "").toContain("declares no arguments");
  379. });
  380. it("names the file when it cannot be read", async () => {
  381. const cwd = makeCwd();
  382. const outcome = await run({
  383. input: { path: "missing.dwf.ts" },
  384. name: "path-missing",
  385. toolName: "CreateWorkflow",
  386. workingDirectory: cwd,
  387. });
  388. expect(outcome.permissionRequested).toHaveLength(0);
  389. expect(outcome.result.error?.message ?? "").toContain("missing.dwf.ts could not be read");
  390. });
  391. });
  392. describe("AmendWorkflow — file sources", () => {
  393. it("refuses a `path` submission whose bytes are the predecessor's script", async () => {
  394. const cwd = makeCwd();
  395. const script = cleanScript("amend-unchanged");
  396. writeFileSync(join(cwd, "run.dwf.ts"), script, "utf8");
  397. const { port, amends, getScriptCalls } = stubRunPort({ runScript: script });
  398. const outcome = await run({
  399. input: { run_id: "dwfrun-prev", path: "run.dwf.ts" },
  400. name: "amend-unchanged",
  401. port,
  402. toolName: "AmendWorkflow",
  403. workingDirectory: cwd,
  404. });
  405. expect(getScriptCalls).toEqual(["dwfrun-prev"]);
  406. expect(amends).toHaveLength(0);
  407. expect(outcome.permissionRequested).toHaveLength(0);
  408. const error = outcome.result.error?.message ?? "";
  409. expect(error).toContain("workflow_script_unchanged");
  410. expect(error).toContain("run.dwf.ts");
  411. expect(error).toContain("Edit the file first");
  412. expect(error).toContain("ResumeWorkflowRun");
  413. expect(error).toContain("Nothing was stopped or created.");
  414. });
  415. it("lets an unchanged script through when the call changes the limit or the model", async () => {
  416. const cwd = makeCwd();
  417. const script = cleanScript("amend-knob");
  418. writeFileSync(join(cwd, "run.dwf.ts"), script, "utf8");
  419. const { port, amends } = stubRunPort({ runScript: script });
  420. await run({
  421. input: { run_id: "dwfrun-prev", path: "run.dwf.ts", max_concurrency: 2 },
  422. name: "amend-knob",
  423. port,
  424. toolName: "AmendWorkflow",
  425. workingDirectory: cwd,
  426. });
  427. expect(amends).toHaveLength(1);
  428. expect(amends[0]!.maxConcurrency).toBe(2);
  429. await run({
  430. input: { run_id: "dwfrun-prev", path: "run.dwf.ts", subagent_model: null },
  431. name: "amend-knob-model",
  432. port,
  433. toolName: "AmendWorkflow",
  434. workingDirectory: cwd,
  435. });
  436. expect(amends).toHaveLength(2);
  437. });
  438. it("skips the check on a port without getScript", async () => {
  439. const cwd = makeCwd();
  440. const script = cleanScript("amend-no-read");
  441. writeFileSync(join(cwd, "run.dwf.ts"), script, "utf8");
  442. const { port, amends } = stubRunPort();
  443. await run({
  444. input: { run_id: "dwfrun-prev", path: "run.dwf.ts" },
  445. name: "amend-no-getrunscript",
  446. port,
  447. toolName: "AmendWorkflow",
  448. workingDirectory: cwd,
  449. });
  450. expect(amends).toHaveLength(1);
  451. expect(amends[0]!.scriptPath).toBe(join(cwd, "run.dwf.ts"));
  452. });
  453. it("never compares an inline script, and writes it to a draft the response names", async () => {
  454. const cwd = makeCwd();
  455. const script = cleanScript("amend-inline");
  456. const { port, amends } = stubRunPort({
  457. runScript: script,
  458. snapshot: { name: "前驱" },
  459. });
  460. const outcome = await run({
  461. input: { run_id: "dwfrun-prev", script },
  462. name: "amend-inline",
  463. port,
  464. toolName: "AmendWorkflow",
  465. workingDirectory: cwd,
  466. });
  467. // 内联提交从不比字节:这道网抓的是「忘了编辑」,而贴一遍脚本不是那个错误。
  468. expect(amends).toHaveLength(1);
  469. // 没有 `name` 时草稿沿用前驱的名字,中文原样进文件名(2026-09-18:ASCII slug 把每份草稿都
  470. // 压成 `workflow-N`,目录里分不出哪个是哪个)。
  471. const draft = draftPath(cwd, "前驱.dwf.ts");
  472. expect(readFileSync(draft, "utf8")).toBe(script);
  473. expect(amends[0]!.scriptPath).toBe(draft);
  474. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  475. `The revision's script is at ${join(WORKFLOW_DRAFTS_DIR, "前驱.dwf.ts")}; edit it there for a further revision.`,
  476. );
  477. });
  478. it("refuses a call that gives both a script and a path", async () => {
  479. const cwd = makeCwd();
  480. const outcome = await run({
  481. input: { run_id: "dwfrun-prev", script: "return 1;", path: "run.dwf.ts" },
  482. name: "amend-both-sources",
  483. toolName: "AmendWorkflow",
  484. workingDirectory: cwd,
  485. });
  486. expect(outcome.result.success).toBe(false);
  487. expect(outcome.result.error?.message ?? "").toContain("at most one revised script");
  488. });
  489. // 两个来源都不给 = 沿用前驱的脚本(docs/dynamic-workflow/launch.md「Keeping the predecessor's
  490. // script」)。沿用的脚本同样要有个家:前驱的脚本文件此刻仍是这份字节就继续记它,否则写新草稿。
  491. describe("neither source: the predecessor's script is kept, and so is its file when it still matches", () => {
  492. it("records the predecessor's script file again when its bytes are still the kept script", async () => {
  493. const cwd = makeCwd();
  494. const script = cleanScript("amend-keep-file");
  495. const file = draftPath(cwd, "kept.dwf.ts");
  496. mkdirSync(join(cwd, WORKFLOW_DRAFTS_DIR), { recursive: true });
  497. writeFileSync(file, script, "utf8");
  498. const { port, amends } = stubRunPort({ runScript: script, snapshot: { scriptPath: file } });
  499. const outcome = await run({
  500. port,
  501. input: { run_id: "dwfrun-prev", max_concurrency: 2 },
  502. name: "amend-keep-file",
  503. toolName: "AmendWorkflow",
  504. workingDirectory: cwd,
  505. });
  506. expect(outcome.result.success).toBe(true);
  507. expect(amends).toHaveLength(1);
  508. expect(amends[0]!.scriptText).toBe(script);
  509. expect(amends[0]!.scriptPath).toBe(file);
  510. // 没有新草稿:目录里仍只有那一个脚本文件(外加 .gitignore 与否都不算脚本)。
  511. expect(
  512. readdirSync(join(cwd, WORKFLOW_DRAFTS_DIR)).filter((entry) => entry.endsWith(".dwf.ts")),
  513. ).toEqual(["kept.dwf.ts"]);
  514. const output = outcome.result.output as CreateWorkflowOutput;
  515. expect(output.response).toContain("started unchanged in the background");
  516. expect(output.response).toContain(`${WORKFLOW_DRAFTS_DIR}/kept.dwf.ts`);
  517. });
  518. it("writes a fresh draft when the predecessor's file has been edited since", async () => {
  519. const cwd = makeCwd();
  520. const script = cleanScript("amend-keep-diverged");
  521. const file = draftPath(cwd, "edited.dwf.ts");
  522. mkdirSync(join(cwd, WORKFLOW_DRAFTS_DIR), { recursive: true });
  523. writeFileSync(file, `${script}\n// edited after the run started\n`, "utf8");
  524. const { port, amends } = stubRunPort({
  525. runScript: script,
  526. snapshot: { scriptPath: file, name: "diverged" },
  527. });
  528. const outcome = await run({
  529. port,
  530. input: { run_id: "dwfrun-prev", max_concurrency: 2 },
  531. name: "amend-keep-diverged",
  532. toolName: "AmendWorkflow",
  533. workingDirectory: cwd,
  534. });
  535. expect(outcome.result.success).toBe(true);
  536. // 跑的是存档的那一份,不是盘上被改过的那一份;记下的文件装的也必须是存档的那一份。
  537. expect(amends[0]!.scriptText).toBe(script);
  538. expect(amends[0]!.scriptPath).toBe(draftPath(cwd, "diverged.dwf.ts"));
  539. expect(readFileSync(amends[0]!.scriptPath!, "utf8")).toBe(script);
  540. // 用户正在改的那个文件一个字节都没动。
  541. expect(readFileSync(file, "utf8")).toContain("// edited after the run started");
  542. });
  543. it("writes a draft when the predecessor never recorded a file", async () => {
  544. const cwd = makeCwd();
  545. const script = cleanScript("amend-keep-no-file");
  546. const { port, amends } = stubRunPort({ runScript: script, snapshot: { name: "nofile" } });
  547. const outcome = await run({
  548. port,
  549. input: { run_id: "dwfrun-prev", subagent_model: null },
  550. name: "amend-keep-no-file",
  551. toolName: "AmendWorkflow",
  552. workingDirectory: cwd,
  553. });
  554. expect(outcome.result.success).toBe(true);
  555. expect(amends[0]!.scriptPath).toBe(draftPath(cwd, "nofile.dwf.ts"));
  556. expect(readFileSync(amends[0]!.scriptPath!, "utf8")).toBe(script);
  557. });
  558. });
  559. });
  560. describe("SaveWorkflow — `script_path`", () => {
  561. it("saves a draft's body and drops the metadata block it carries", async () => {
  562. const cwd = makeCwd();
  563. const body = cleanScript("save-from-draft");
  564. // 从保存定义抄来的草稿带着块;块要被丢掉,元数据以本次调用的字段为准。
  565. saveSavedWorkflow({ cwd, name: "origin", meta: { description: "old words" }, script: body });
  566. const draft = draftPath(cwd, "origin.dwf.ts");
  567. mkdirSync(join(cwd, WORKFLOW_DRAFTS_DIR), { recursive: true });
  568. writeFileSync(draft, readFileSync(join(cwd, ".zcode/workflows/origin.dwf.ts"), "utf8"), "utf8");
  569. const outcome = await run({
  570. input: {
  571. name: "from-draft",
  572. description: "new words",
  573. script_path: join(WORKFLOW_DRAFTS_DIR, "origin.dwf.ts"),
  574. scope: "project",
  575. },
  576. name: "save-script-path",
  577. toolName: "SaveWorkflow",
  578. workingDirectory: cwd,
  579. });
  580. expect(outcome.permissionRequested).toHaveLength(1);
  581. const output = outcome.result.output as SaveWorkflowOutput;
  582. expect(output.ok).toBe(true);
  583. const saved = readFileSync(output.path, "utf8");
  584. expect(saved).toBe(serializeSavedWorkflow({ description: "new words" }, body));
  585. // 块只出现一次:草稿里那一份被丢掉了,而不是被叠在新块后面。
  586. expect(saved.split("/* zcode-workflow")).toHaveLength(2);
  587. });
  588. it("refuses a call that gives both sources, and one that gives neither", async () => {
  589. const cwd = makeCwd();
  590. for (const [label, extra] of [
  591. ["both", { script: "return 1;", script_path: "a.dwf.ts" }],
  592. ["neither", {}],
  593. ] as const) {
  594. const outcome = await run({
  595. input: { name: "x", description: "d", scope: "project", ...extra },
  596. name: `save-xor-${label}`,
  597. toolName: "SaveWorkflow",
  598. workingDirectory: cwd,
  599. });
  600. expect(outcome.result.success).toBe(false);
  601. expect(outcome.result.error?.message ?? "").toContain("exactly one script source");
  602. }
  603. });
  604. });