workflow-driver-world-run.test.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. /**
  2. * world.run 的 driver 侧执行(docs/dynamic-workflow/authoring.md)。照
  3. * workflow-driver-world-read-args.test.ts 的形状:只碰 driver 端口本身,不经脚本、不经引擎
  4. * ——facade 类型签名与编译期字面量规则在上游拦截,这里防的是编译期之外的接线错误,
  5. * 以及「执行结果 → 值 / 拒绝」的映射契约。
  6. */
  7. import { describe, expect, it } from "vitest";
  8. import type { ExecutionPort, ExecutionResult, FileSystemPort } from "@zcode/contracts";
  9. import { InMemoryJournalStore, type WorkflowReportSink } from "@zcode/dynamic-workflow";
  10. import { createWorkflowEscalationRegistry } from "../src/app/workflow-escalation-registry.js";
  11. import { createAgentRuntimeWorkflowDriver } from "../src/app/workflow-driver.js";
  12. /** 触及即失败的 fs 端口:world.run 不该碰文件系统。 */
  13. function unsupportedFileSystemPort(): FileSystemPort {
  14. return new Proxy({} as FileSystemPort, {
  15. get(_target, name) {
  16. return () => {
  17. throw new Error(`fileSystemPort.${String(name)} 不应被 world.run 触及`);
  18. };
  19. },
  20. });
  21. }
  22. function noopSink(): WorkflowReportSink {
  23. const unexpected = (name: string) => (): never => {
  24. throw new Error(`noopSink.${name} 不应被触及`);
  25. };
  26. return {
  27. askSubmitAttempted: unexpected("askSubmitAttempted"),
  28. askTurnEnded: unexpected("askTurnEnded"),
  29. askProgress: unexpected("askProgress"),
  30. askStats: unexpected("askStats"),
  31. askFailed: unexpected("askFailed"),
  32. };
  33. }
  34. interface RecordedRun {
  35. file: string;
  36. args: string[] | undefined;
  37. cwd: string | undefined;
  38. timeoutMs: number | undefined;
  39. maxInlineBytes: number | undefined;
  40. }
  41. /** 记录请求并回放配置结果的 ExecutionPort 桩。 */
  42. function stubExecutionPort(result: Partial<ExecutionResult>): {
  43. port: ExecutionPort;
  44. calls: RecordedRun[];
  45. } {
  46. const calls: RecordedRun[] = [];
  47. const stream = (text: string) => ({ text, bytes: Buffer.byteLength(text, "utf8"), truncated: false });
  48. const full: ExecutionResult = {
  49. status: "completed",
  50. exitCode: 0,
  51. stdout: stream(""),
  52. stderr: stream(""),
  53. durationMs: 1,
  54. timedOut: false,
  55. cancelled: false,
  56. startedAt: new Date(0),
  57. completedAt: new Date(1),
  58. ...result,
  59. } as ExecutionResult;
  60. return {
  61. calls,
  62. port: {
  63. run: async (request) => {
  64. const command = request.command;
  65. calls.push({
  66. file: command.mode === "argv" ? command.file : `(shell) ${command.command}`,
  67. args: command.mode === "argv" ? command.args : undefined,
  68. cwd: request.cwd,
  69. timeoutMs: request.timeoutMs,
  70. maxInlineBytes: request.outputLimit?.maxInlineBytes,
  71. });
  72. return full;
  73. },
  74. } as ExecutionPort,
  75. };
  76. }
  77. const CAP = 256 * 1024;
  78. function makeDriver(executionPort: ExecutionPort) {
  79. return createAgentRuntimeWorkflowDriver({
  80. journal: new InMemoryJournalStore(),
  81. emit: () => undefined,
  82. fileSystemPort: unsupportedFileSystemPort(),
  83. executionPort,
  84. escalationRegistry: createWorkflowEscalationRegistry(),
  85. cwd: "/workspace/root",
  86. runtimeFactory: () => {
  87. throw new Error("runtimeFactory 不应被 world.run 触及");
  88. },
  89. })(noopSink());
  90. }
  91. describe("workflow driver — world.run", () => {
  92. it("passes argv, cwd, default 300s timeout and cap+1 output limit to the port", async () => {
  93. const { port, calls } = stubExecutionPort({ exitCode: 0, stdout: { text: "ok", bytes: 2, truncated: false } as never });
  94. const driver = makeDriver(port);
  95. const value = await driver.executeWorldRead("run", ["lean", ["--make", "a.lean"]]);
  96. expect(value).toEqual({ exitCode: 0, stdout: "ok", stderr: "" });
  97. expect(calls).toEqual([
  98. {
  99. file: "lean",
  100. args: ["--make", "a.lean"],
  101. cwd: "/workspace/root",
  102. timeoutMs: 300_000,
  103. maxInlineBytes: CAP + 1,
  104. },
  105. ]);
  106. });
  107. it("honours opts.timeoutMs with no upper clamp (long-running tests are in-contract)", async () => {
  108. const { port, calls } = stubExecutionPort({});
  109. const driver = makeDriver(port);
  110. await driver.executeWorldRead("run", ["lake", ["build"], { timeoutMs: 3_600_000 }]);
  111. expect(calls[0]?.timeoutMs).toBe(3_600_000);
  112. });
  113. it("returns a nonzero exit as a value, not a rejection (the gating loop's normal case)", async () => {
  114. const { port } = stubExecutionPort({
  115. status: "failed",
  116. exitCode: 2,
  117. stderr: { text: "proof failed", bytes: 12, truncated: false } as never,
  118. });
  119. const driver = makeDriver(port);
  120. await expect(driver.executeWorldRead("run", ["lean", ["a.lean"]])).resolves.toEqual({
  121. exitCode: 2,
  122. stdout: "",
  123. stderr: "proof failed",
  124. });
  125. });
  126. it("rejects a timeout as a catchable DriverError naming the wall clock", async () => {
  127. const { port } = stubExecutionPort({
  128. status: "timed_out",
  129. timedOut: true,
  130. error: { type: "timeout", message: "Command timed out" },
  131. });
  132. const driver = makeDriver(port);
  133. await expect(driver.executeWorldRead("run", ["lake", ["build"]])).rejects.toMatchObject({
  134. code: "DriverError",
  135. message: expect.stringContaining("300000ms"),
  136. });
  137. });
  138. it("rejects spawn errors as DriverError (the observation never ran)", async () => {
  139. const { port } = stubExecutionPort({
  140. status: "spawn_error",
  141. error: { type: "spawn_error", message: "ENOENT: lean not found" },
  142. });
  143. const driver = makeDriver(port);
  144. await expect(driver.executeWorldRead("run", ["lean", []])).rejects.toMatchObject({
  145. code: "DriverError",
  146. message: expect.stringContaining("ENOENT"),
  147. });
  148. });
  149. it("runs whatever command the compiled script hands it: there is no runtime allowlist", async () => {
  150. // 授权只在编译期(9003 字面量 + 确认窗)。driver 曾另持一份 launch 时收集的命令集复验,
  151. // 补全函数体里新出现的命令因此被误拒(workflow-world-read.ts 文件头第 2 条);这里钉住
  152. // "driver 不再有第二份名单":一条 launch 时不存在的命令照样执行。
  153. const { port, calls } = stubExecutionPort({});
  154. const driver = makeDriver(port);
  155. await expect(driver.executeWorldRead("run", ["echo", ["hi"]])).resolves.toMatchObject({
  156. exitCode: 0,
  157. });
  158. expect(calls.map((call) => call.file)).toEqual(["echo"]);
  159. });
  160. it("rejects stdout over the 256KB cap with actionable guidance (cap+1 probe)", async () => {
  161. const big = "x".repeat(CAP + 1);
  162. const { port } = stubExecutionPort({
  163. stdout: { text: big, bytes: CAP + 1, truncated: false } as never,
  164. });
  165. const driver = makeDriver(port);
  166. await expect(driver.executeWorldRead("run", ["node", ["-e", "spam"]])).rejects.toMatchObject({
  167. code: "WorldReadCapExceeded",
  168. message: expect.stringContaining("stdout"),
  169. });
  170. });
  171. it("rejects stderr over the cap the same way", async () => {
  172. const { port } = stubExecutionPort({
  173. stderr: { text: "y", bytes: 1, truncated: true } as never,
  174. });
  175. const driver = makeDriver(port);
  176. await expect(driver.executeWorldRead("run", ["node", []])).rejects.toMatchObject({
  177. code: "WorldReadCapExceeded",
  178. message: expect.stringContaining("stderr"),
  179. });
  180. });
  181. it("validates argument shapes loudly, never coercing", async () => {
  182. const { port, calls } = stubExecutionPort({});
  183. const driver = makeDriver(port);
  184. const reject = (args: unknown[]) =>
  185. expect(driver.executeWorldRead("run", args)).rejects.toMatchObject({ code: "DriverError" });
  186. await reject([]);
  187. await reject([42]);
  188. await reject(["lean", "not-an-array"]);
  189. await reject(["lean", [1]]);
  190. await reject(["lean", [], "not-opts"]);
  191. await reject(["lean", [], { timeoutMs: 0 }]);
  192. await reject(["lean", [], { timeoutMs: 1.5 }]);
  193. await reject(["lean", [], {}, "extra"]);
  194. expect(calls).toEqual([]);
  195. });
  196. });