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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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. it.each([
  155. ["all three", { script: "return 1;", saved: { name: "x" }, path: "a.dwf.ts" }],
  156. ["script and path", { script: "return 1;", path: "a.dwf.ts" }],
  157. ["saved and path", { saved: { name: "x" }, path: "a.dwf.ts" }],
  158. ["none", {}],
  159. ])("refuses a %s call before the gate", async (label, input) => {
  160. const outcome = await run({
  161. input,
  162. name: `xor-${label.replace(/\s/gu, "-")}`,
  163. toolName: "CreateWorkflow",
  164. workingDirectory: makeCwd(),
  165. });
  166. expect(outcome.permissionRequested).toHaveLength(0);
  167. expect(outcome.result.success).toBe(false);
  168. expect(outcome.result.error?.message ?? "").toContain("exactly one workflow source");
  169. });
  170. it("refuses `args` without `path`: a saved call has `saved.args`, an inline script has none", async () => {
  171. const outcome = await run({
  172. input: { script: "return 1;", args: { pr: "1" } },
  173. name: "args-without-path",
  174. toolName: "CreateWorkflow",
  175. workingDirectory: makeCwd(),
  176. });
  177. expect(outcome.permissionRequested).toHaveLength(0);
  178. expect(outcome.result.success).toBe(false);
  179. expect(outcome.result.error?.message ?? "").toContain("`args` belongs to the `path` source");
  180. });
  181. });
  182. describe("CreateWorkflow — inline drafts", () => {
  183. it("a non-compiling inline script still lands on disk, and the diagnostics point at that file", async () => {
  184. const cwd = makeCwd();
  185. const { port, submits } = stubRunPort();
  186. const outcome = await run({
  187. input: { name: "triage", script: BROKEN_SCRIPT },
  188. name: "inline-broken",
  189. port,
  190. toolName: "CreateWorkflow",
  191. workingDirectory: cwd,
  192. });
  193. expect(submits).toHaveLength(0);
  194. const output = outcome.result.output as CreateWorkflowOutput;
  195. expect(output.ok).toBe(false);
  196. const draft = draftPath(cwd, "triage.dwf.ts");
  197. expect(readFileSync(draft, "utf8")).toBe(BROKEN_SCRIPT);
  198. // 文案给的是工作区相对写法,行号按文件数(无元数据块,所以与正文行相同)。
  199. const described = join(WORKFLOW_DRAFTS_DIR, "triage.dwf.ts");
  200. expect(output.response).toContain(`${described}:L1:C`);
  201. expect(output.response).toContain(`The script is saved at ${described}.`);
  202. expect(output.response).toContain(`resubmit with \`path: "${described}"\``);
  203. expect(output.response).toContain("do not paste the script inline again");
  204. // display / 输出里的诊断数组仍按**正文行**:转录面画的是正文。
  205. expect(output.diagnostics[0]!.line).toBe(1);
  206. });
  207. it("a launched inline run records the draft and tells the model to edit it next time", async () => {
  208. const cwd = makeCwd();
  209. const script = cleanScript("inline-launch");
  210. const { port, submits } = stubRunPort();
  211. const outcome = await run({
  212. input: { name: "nightly", script },
  213. name: "inline-launch",
  214. port,
  215. toolName: "CreateWorkflow",
  216. workingDirectory: cwd,
  217. });
  218. const draft = draftPath(cwd, "nightly.dwf.ts");
  219. expect(submits[0]!.scriptPath).toBe(draft);
  220. expect(readFileSync(draft, "utf8")).toBe(script);
  221. const output = outcome.result.output as CreateWorkflowOutput;
  222. expect(output.status).toBe("backgrounded");
  223. expect(output.response).toContain(
  224. `The script is saved at ${join(WORKFLOW_DRAFTS_DIR, "nightly.dwf.ts")}; to revise it later, edit that file and pass \`path\` to AmendWorkflow.`,
  225. );
  226. });
  227. it("falls back to the old note, and to no scriptPath, when the draft cannot be written", async () => {
  228. const cwd = makeCwd();
  229. // `.zcode` 是个普通文件 → 草稿目录建不出来。尽力而为:调用照常完成。
  230. writeFileSync(join(cwd, ".zcode"), "not a directory", "utf8");
  231. const { port, submits } = stubRunPort();
  232. const broken = await run({
  233. input: { script: BROKEN_SCRIPT },
  234. name: "draft-write-failed",
  235. port,
  236. toolName: "CreateWorkflow",
  237. workingDirectory: cwd,
  238. });
  239. const brokenOutput = broken.result.output as CreateWorkflowOutput;
  240. expect(brokenOutput.response).toContain(
  241. "NOTE: The workflow was NOT executed — fix the errors above and resubmit.",
  242. );
  243. expect(brokenOutput.response).not.toContain("workflow-drafts");
  244. expect(brokenOutput.response).toContain("L1:C");
  245. const clean = await run({
  246. input: { script: cleanScript("no-draft") },
  247. name: "draft-write-failed-clean",
  248. port,
  249. toolName: "CreateWorkflow",
  250. workingDirectory: cwd,
  251. });
  252. expect(submits).toHaveLength(1);
  253. expect("scriptPath" in submits[0]!).toBe(false);
  254. expect((clean.result.output as CreateWorkflowOutput).response).not.toContain("edit that file");
  255. });
  256. });
  257. describe("CreateWorkflow — the `path` source", () => {
  258. it("accepts a workspace-relative path and runs the file's bytes", async () => {
  259. const cwd = makeCwd();
  260. const script = cleanScript("path-relative");
  261. mkdirSync(join(cwd, "scripts"));
  262. writeFileSync(join(cwd, "scripts", "check.dwf.ts"), script, "utf8");
  263. const { port, submits } = stubRunPort();
  264. const outcome = await run({
  265. input: { path: "scripts/check.dwf.ts" },
  266. name: "path-relative",
  267. port,
  268. toolName: "CreateWorkflow",
  269. workingDirectory: cwd,
  270. });
  271. // 归一化把文件读成 `script`,路径写成绝对形;确认窗看到的就是将要执行的字节。
  272. expect(outcome.permissionRequested[0]!.input).toEqual({
  273. script,
  274. path: join(cwd, "scripts", "check.dwf.ts"),
  275. // 确认窗可调的设置(docs/dynamic-workflow/launch.md「Adjusting the settings in the window」)。
  276. adjustable_settings: { subagent_model: false },
  277. });
  278. expect(submits[0]!.scriptText).toBe(script);
  279. expect(submits[0]!.scriptPath).toBe(join(cwd, "scripts", "check.dwf.ts"));
  280. // `path` 来源的文件不是工具写下的,所以说的是「脚本文件是 …」而不是「已保存到 …」。
  281. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  282. `The script file is ${join("scripts", "check.dwf.ts")};`,
  283. );
  284. // 已经是工作副本了,不再抄一份。
  285. expect(() => readFileSync(draftPath(cwd, "check.dwf.ts"), "utf8")).toThrow();
  286. });
  287. it("accepts an absolute path outside the workspace and reports it absolute", async () => {
  288. const cwd = makeCwd();
  289. const elsewhere = makeCwd();
  290. const script = cleanScript("path-absolute");
  291. const file = join(elsewhere, "outside.dwf.ts");
  292. writeFileSync(file, script, "utf8");
  293. const { port, submits } = stubRunPort();
  294. const outcome = await run({
  295. input: { path: file },
  296. name: "path-absolute",
  297. port,
  298. toolName: "CreateWorkflow",
  299. workingDirectory: cwd,
  300. });
  301. expect(submits[0]!.scriptPath).toBe(file);
  302. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  303. `The script file is ${file};`,
  304. );
  305. });
  306. it("parses a metadata block, validates `args` against it and reports diagnostics in file lines", async () => {
  307. const cwd = makeCwd();
  308. const body =
  309. 'const depth: number = args.depth as number;\nconst bad: number = "x";\nreturn depth;';
  310. const file = join(cwd, "with-meta.dwf.ts");
  311. writeFileSync(
  312. file,
  313. serializeSavedWorkflow(
  314. { description: "declared", args: { depth: { type: "number", default: 2 } } },
  315. body,
  316. ),
  317. "utf8",
  318. );
  319. const { port } = stubRunPort();
  320. const outcome = await run({
  321. input: { path: "with-meta.dwf.ts", args: { depth: 5 } },
  322. name: "path-meta",
  323. port,
  324. toolName: "CreateWorkflow",
  325. workingDirectory: cwd,
  326. });
  327. const output = outcome.result.output as CreateWorkflowOutput;
  328. expect(output.ok).toBe(false);
  329. // 正文第 2 行的诊断 = 文件第 2 + offset 行;offset 由元数据块的行数决定。
  330. const fileLines = readFileSync(file, "utf8").split("\n");
  331. const offset = fileLines.findIndex(
  332. (line) => line === "const depth: number = args.depth as number;",
  333. );
  334. expect(output.diagnostics[0]!.line).toBe(2);
  335. expect(output.response).toContain(`with-meta.dwf.ts:L${2 + offset}:C`);
  336. });
  337. it("runs a declared file with its arguments, defaults filled in", async () => {
  338. const cwd = makeCwd();
  339. writeFileSync(
  340. join(cwd, "declared.dwf.ts"),
  341. serializeSavedWorkflow(
  342. {
  343. description: "declared",
  344. args: {
  345. depth: { type: "number", default: 2 },
  346. target: { type: "string", required: true },
  347. },
  348. },
  349. cleanScript("declared"),
  350. ),
  351. "utf8",
  352. );
  353. const { port, submits } = stubRunPort();
  354. await run({
  355. input: { path: "declared.dwf.ts", args: { target: "pkg" } },
  356. name: "path-args",
  357. port,
  358. toolName: "CreateWorkflow",
  359. workingDirectory: cwd,
  360. });
  361. expect(submits[0]!.args).toEqual({ depth: 2, target: "pkg" });
  362. });
  363. it("rejects `args` for a file with no metadata block, before the gate", async () => {
  364. const cwd = makeCwd();
  365. writeFileSync(join(cwd, "plain.dwf.ts"), cleanScript("plain"), "utf8");
  366. const outcome = await run({
  367. input: { path: "plain.dwf.ts", args: { depth: 1 } },
  368. name: "path-args-undeclared",
  369. toolName: "CreateWorkflow",
  370. workingDirectory: cwd,
  371. });
  372. expect(outcome.permissionRequested).toHaveLength(0);
  373. expect(outcome.result.error?.message ?? "").toContain("declares no arguments");
  374. });
  375. it("names the file when it cannot be read", async () => {
  376. const cwd = makeCwd();
  377. const outcome = await run({
  378. input: { path: "missing.dwf.ts" },
  379. name: "path-missing",
  380. toolName: "CreateWorkflow",
  381. workingDirectory: cwd,
  382. });
  383. expect(outcome.permissionRequested).toHaveLength(0);
  384. expect(outcome.result.error?.message ?? "").toContain("missing.dwf.ts could not be read");
  385. });
  386. });
  387. describe("AmendWorkflow — file sources", () => {
  388. it("refuses a `path` submission whose bytes are the predecessor's script", async () => {
  389. const cwd = makeCwd();
  390. const script = cleanScript("amend-unchanged");
  391. writeFileSync(join(cwd, "run.dwf.ts"), script, "utf8");
  392. const { port, amends, getScriptCalls } = stubRunPort({ runScript: script });
  393. const outcome = await run({
  394. input: { run_id: "dwfrun-prev", path: "run.dwf.ts" },
  395. name: "amend-unchanged",
  396. port,
  397. toolName: "AmendWorkflow",
  398. workingDirectory: cwd,
  399. });
  400. expect(getScriptCalls).toEqual(["dwfrun-prev"]);
  401. expect(amends).toHaveLength(0);
  402. expect(outcome.permissionRequested).toHaveLength(0);
  403. const error = outcome.result.error?.message ?? "";
  404. expect(error).toContain("workflow_script_unchanged");
  405. expect(error).toContain("run.dwf.ts");
  406. expect(error).toContain("Edit the file first");
  407. expect(error).toContain("ResumeWorkflowRun");
  408. expect(error).toContain("Nothing was stopped or created.");
  409. });
  410. it("lets an unchanged script through when the call changes the limit or the model", async () => {
  411. const cwd = makeCwd();
  412. const script = cleanScript("amend-knob");
  413. writeFileSync(join(cwd, "run.dwf.ts"), script, "utf8");
  414. const { port, amends } = stubRunPort({ runScript: script });
  415. await run({
  416. input: { run_id: "dwfrun-prev", path: "run.dwf.ts", max_concurrency: 2 },
  417. name: "amend-knob",
  418. port,
  419. toolName: "AmendWorkflow",
  420. workingDirectory: cwd,
  421. });
  422. expect(amends).toHaveLength(1);
  423. expect(amends[0]!.maxConcurrency).toBe(2);
  424. await run({
  425. input: { run_id: "dwfrun-prev", path: "run.dwf.ts", subagent_model: null },
  426. name: "amend-knob-model",
  427. port,
  428. toolName: "AmendWorkflow",
  429. workingDirectory: cwd,
  430. });
  431. expect(amends).toHaveLength(2);
  432. });
  433. it("skips the check on a port without getScript", async () => {
  434. const cwd = makeCwd();
  435. const script = cleanScript("amend-no-read");
  436. writeFileSync(join(cwd, "run.dwf.ts"), script, "utf8");
  437. const { port, amends } = stubRunPort();
  438. await run({
  439. input: { run_id: "dwfrun-prev", path: "run.dwf.ts" },
  440. name: "amend-no-getrunscript",
  441. port,
  442. toolName: "AmendWorkflow",
  443. workingDirectory: cwd,
  444. });
  445. expect(amends).toHaveLength(1);
  446. expect(amends[0]!.scriptPath).toBe(join(cwd, "run.dwf.ts"));
  447. });
  448. it("never compares an inline script, and writes it to a draft the response names", async () => {
  449. const cwd = makeCwd();
  450. const script = cleanScript("amend-inline");
  451. const { port, amends } = stubRunPort({
  452. runScript: script,
  453. snapshot: { name: "前驱" },
  454. });
  455. const outcome = await run({
  456. input: { run_id: "dwfrun-prev", script },
  457. name: "amend-inline",
  458. port,
  459. toolName: "AmendWorkflow",
  460. workingDirectory: cwd,
  461. });
  462. // 内联提交从不比字节:这道网抓的是「忘了编辑」,而贴一遍脚本不是那个错误。
  463. expect(amends).toHaveLength(1);
  464. // 没有 `name` 时草稿沿用前驱的名字,中文原样进文件名(2026-09-18:ASCII slug 把每份草稿都
  465. // 压成 `workflow-N`,目录里分不出哪个是哪个)。
  466. const draft = draftPath(cwd, "前驱.dwf.ts");
  467. expect(readFileSync(draft, "utf8")).toBe(script);
  468. expect(amends[0]!.scriptPath).toBe(draft);
  469. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  470. `The revision's script is at ${join(WORKFLOW_DRAFTS_DIR, "前驱.dwf.ts")}; edit it there for a further revision.`,
  471. );
  472. });
  473. it("refuses a call that gives both a script and a path", async () => {
  474. const cwd = makeCwd();
  475. const outcome = await run({
  476. input: { run_id: "dwfrun-prev", script: "return 1;", path: "run.dwf.ts" },
  477. name: "amend-both-sources",
  478. toolName: "AmendWorkflow",
  479. workingDirectory: cwd,
  480. });
  481. expect(outcome.result.success).toBe(false);
  482. expect(outcome.result.error?.message ?? "").toContain("at most one revised script");
  483. });
  484. // 两个来源都不给 = 沿用前驱的脚本(docs/dynamic-workflow/launch.md「Keeping the predecessor's
  485. // script」)。沿用的脚本同样要有个家:前驱的脚本文件此刻仍是这份字节就继续记它,否则写新草稿。
  486. describe("neither source: the predecessor's script is kept, and so is its file when it still matches", () => {
  487. it("records the predecessor's script file again when its bytes are still the kept script", async () => {
  488. const cwd = makeCwd();
  489. const script = cleanScript("amend-keep-file");
  490. const file = draftPath(cwd, "kept.dwf.ts");
  491. mkdirSync(join(cwd, WORKFLOW_DRAFTS_DIR), { recursive: true });
  492. writeFileSync(file, script, "utf8");
  493. const { port, amends } = stubRunPort({ runScript: script, snapshot: { scriptPath: file } });
  494. const outcome = await run({
  495. port,
  496. input: { run_id: "dwfrun-prev", max_concurrency: 2 },
  497. name: "amend-keep-file",
  498. toolName: "AmendWorkflow",
  499. workingDirectory: cwd,
  500. });
  501. expect(outcome.result.success).toBe(true);
  502. expect(amends).toHaveLength(1);
  503. expect(amends[0]!.scriptText).toBe(script);
  504. expect(amends[0]!.scriptPath).toBe(file);
  505. // 没有新草稿:目录里仍只有那一个脚本文件(外加 .gitignore 与否都不算脚本)。
  506. expect(
  507. readdirSync(join(cwd, WORKFLOW_DRAFTS_DIR)).filter((entry) => entry.endsWith(".dwf.ts")),
  508. ).toEqual(["kept.dwf.ts"]);
  509. const output = outcome.result.output as CreateWorkflowOutput;
  510. expect(output.response).toContain("started unchanged in the background");
  511. expect(output.response).toContain(`${WORKFLOW_DRAFTS_DIR}/kept.dwf.ts`);
  512. });
  513. it("writes a fresh draft when the predecessor's file has been edited since", async () => {
  514. const cwd = makeCwd();
  515. const script = cleanScript("amend-keep-diverged");
  516. const file = draftPath(cwd, "edited.dwf.ts");
  517. mkdirSync(join(cwd, WORKFLOW_DRAFTS_DIR), { recursive: true });
  518. writeFileSync(file, `${script}\n// edited after the run started\n`, "utf8");
  519. const { port, amends } = stubRunPort({
  520. runScript: script,
  521. snapshot: { scriptPath: file, name: "diverged" },
  522. });
  523. const outcome = await run({
  524. port,
  525. input: { run_id: "dwfrun-prev", max_concurrency: 2 },
  526. name: "amend-keep-diverged",
  527. toolName: "AmendWorkflow",
  528. workingDirectory: cwd,
  529. });
  530. expect(outcome.result.success).toBe(true);
  531. // 跑的是存档的那一份,不是盘上被改过的那一份;记下的文件装的也必须是存档的那一份。
  532. expect(amends[0]!.scriptText).toBe(script);
  533. expect(amends[0]!.scriptPath).toBe(draftPath(cwd, "diverged.dwf.ts"));
  534. expect(readFileSync(amends[0]!.scriptPath!, "utf8")).toBe(script);
  535. // 用户正在改的那个文件一个字节都没动。
  536. expect(readFileSync(file, "utf8")).toContain("// edited after the run started");
  537. });
  538. it("writes a draft when the predecessor never recorded a file", async () => {
  539. const cwd = makeCwd();
  540. const script = cleanScript("amend-keep-no-file");
  541. const { port, amends } = stubRunPort({ runScript: script, snapshot: { name: "nofile" } });
  542. const outcome = await run({
  543. port,
  544. input: { run_id: "dwfrun-prev", subagent_model: null },
  545. name: "amend-keep-no-file",
  546. toolName: "AmendWorkflow",
  547. workingDirectory: cwd,
  548. });
  549. expect(outcome.result.success).toBe(true);
  550. expect(amends[0]!.scriptPath).toBe(draftPath(cwd, "nofile.dwf.ts"));
  551. expect(readFileSync(amends[0]!.scriptPath!, "utf8")).toBe(script);
  552. });
  553. });
  554. });
  555. describe("SaveWorkflow — `script_path`", () => {
  556. it("saves a draft's body and drops the metadata block it carries", async () => {
  557. const cwd = makeCwd();
  558. const body = cleanScript("save-from-draft");
  559. // 从保存定义抄来的草稿带着块;块要被丢掉,元数据以本次调用的字段为准。
  560. saveSavedWorkflow({ cwd, name: "origin", meta: { description: "old words" }, script: body });
  561. const draft = draftPath(cwd, "origin.dwf.ts");
  562. mkdirSync(join(cwd, WORKFLOW_DRAFTS_DIR), { recursive: true });
  563. writeFileSync(draft, readFileSync(join(cwd, ".zcode/workflows/origin.dwf.ts"), "utf8"), "utf8");
  564. const outcome = await run({
  565. input: {
  566. name: "from-draft",
  567. description: "new words",
  568. script_path: join(WORKFLOW_DRAFTS_DIR, "origin.dwf.ts"),
  569. scope: "project",
  570. },
  571. name: "save-script-path",
  572. toolName: "SaveWorkflow",
  573. workingDirectory: cwd,
  574. });
  575. expect(outcome.permissionRequested).toHaveLength(1);
  576. const output = outcome.result.output as SaveWorkflowOutput;
  577. expect(output.ok).toBe(true);
  578. const saved = readFileSync(output.path, "utf8");
  579. expect(saved).toBe(serializeSavedWorkflow({ description: "new words" }, body));
  580. // 块只出现一次:草稿里那一份被丢掉了,而不是被叠在新块后面。
  581. expect(saved.split("/* zcode-workflow")).toHaveLength(2);
  582. });
  583. it("refuses a call that gives both sources, and one that gives neither", async () => {
  584. const cwd = makeCwd();
  585. for (const [label, extra] of [
  586. ["both", { script: "return 1;", script_path: "a.dwf.ts" }],
  587. ["neither", {}],
  588. ] as const) {
  589. const outcome = await run({
  590. input: { name: "x", description: "d", scope: "project", ...extra },
  591. name: `save-xor-${label}`,
  592. toolName: "SaveWorkflow",
  593. workingDirectory: cwd,
  594. });
  595. expect(outcome.result.success).toBe(false);
  596. expect(outcome.result.error?.message ?? "").toContain("exactly one script source");
  597. }
  598. });
  599. });