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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. tailBytes: number | undefined;
  41. }
  42. /** 记录请求并回放配置结果的 ExecutionPort 桩。 */
  43. function stubExecutionPort(result: Partial<ExecutionResult>): {
  44. port: ExecutionPort;
  45. calls: RecordedRun[];
  46. } {
  47. const calls: RecordedRun[] = [];
  48. const stream = (text: string) => ({ text, bytes: Buffer.byteLength(text, "utf8"), truncated: false });
  49. const full: ExecutionResult = {
  50. status: "completed",
  51. exitCode: 0,
  52. stdout: stream(""),
  53. stderr: stream(""),
  54. durationMs: 1,
  55. timedOut: false,
  56. cancelled: false,
  57. startedAt: new Date(0),
  58. completedAt: new Date(1),
  59. ...result,
  60. } as ExecutionResult;
  61. return {
  62. calls,
  63. port: {
  64. run: async (request) => {
  65. const command = request.command;
  66. calls.push({
  67. file: command.mode === "argv" ? command.file : `(shell) ${command.command}`,
  68. args: command.mode === "argv" ? command.args : undefined,
  69. cwd: request.cwd,
  70. timeoutMs: request.timeoutMs,
  71. maxInlineBytes: request.outputLimit?.maxInlineBytes,
  72. tailBytes: request.outputLimit?.tailBytes,
  73. });
  74. return full;
  75. },
  76. } as ExecutionPort,
  77. };
  78. }
  79. const CAP = 16 * 1024 * 1024;
  80. function makeDriver(executionPort: ExecutionPort) {
  81. return createAgentRuntimeWorkflowDriver({
  82. journal: new InMemoryJournalStore(),
  83. emit: () => undefined,
  84. fileSystemPort: unsupportedFileSystemPort(),
  85. executionPort,
  86. escalationRegistry: createWorkflowEscalationRegistry(),
  87. cwd: "/workspace/root",
  88. runtimeFactory: () => {
  89. throw new Error("runtimeFactory 不应被 world.run 触及");
  90. },
  91. })(noopSink());
  92. }
  93. describe("workflow driver — world.run", () => {
  94. it("passes argv, cwd, default 300s timeout and cap+1 output limit to the port", async () => {
  95. const { port, calls } = stubExecutionPort({ exitCode: 0, stdout: { text: "ok", bytes: 2, truncated: false } as never });
  96. const driver = makeDriver(port);
  97. const value = await driver.executeWorldRead("run", ["lean", ["--make", "a.lean"]]);
  98. expect(value).toEqual({ exitCode: 0, stdout: "ok", stderr: "" });
  99. expect(calls).toEqual([
  100. {
  101. file: "lean",
  102. args: ["--make", "a.lean"],
  103. cwd: "/workspace/root",
  104. timeoutMs: 300_000,
  105. maxInlineBytes: CAP + 1,
  106. tailBytes: undefined,
  107. },
  108. ]);
  109. });
  110. it("honours opts.timeoutMs with no upper clamp (long-running tests are in-contract)", async () => {
  111. const { port, calls } = stubExecutionPort({});
  112. const driver = makeDriver(port);
  113. await driver.executeWorldRead("run", ["lake", ["build"], { timeoutMs: 3_600_000 }]);
  114. expect(calls[0]?.timeoutMs).toBe(3_600_000);
  115. });
  116. it("returns a nonzero exit as a value, not a rejection (the gating loop's normal case)", async () => {
  117. const { port } = stubExecutionPort({
  118. status: "failed",
  119. exitCode: 2,
  120. stderr: { text: "proof failed", bytes: 12, truncated: false } as never,
  121. });
  122. const driver = makeDriver(port);
  123. await expect(driver.executeWorldRead("run", ["lean", ["a.lean"]])).resolves.toEqual({
  124. exitCode: 2,
  125. stdout: "",
  126. stderr: "proof failed",
  127. });
  128. });
  129. it("rejects a timeout as a catchable DriverError naming the wall clock", async () => {
  130. const { port } = stubExecutionPort({
  131. status: "timed_out",
  132. timedOut: true,
  133. error: { type: "timeout", message: "Command timed out" },
  134. });
  135. const driver = makeDriver(port);
  136. await expect(driver.executeWorldRead("run", ["lake", ["build"]])).rejects.toMatchObject({
  137. code: "DriverError",
  138. message: expect.stringContaining("300000ms"),
  139. });
  140. });
  141. it("rejects spawn errors as DriverError (the observation never ran)", async () => {
  142. const { port } = stubExecutionPort({
  143. status: "spawn_error",
  144. error: { type: "spawn_error", message: "ENOENT: lean not found" },
  145. });
  146. const driver = makeDriver(port);
  147. await expect(driver.executeWorldRead("run", ["lean", []])).rejects.toMatchObject({
  148. code: "DriverError",
  149. message: expect.stringContaining("ENOENT"),
  150. });
  151. });
  152. it("runs whatever command the compiled script hands it: there is no runtime allowlist", async () => {
  153. // 授权只在编译期(9003 字面量 + 确认窗)。driver 曾另持一份 launch 时收集的命令集复验,
  154. // 补全函数体里新出现的命令因此被误拒(workflow-world-read.ts 文件头第 2 条);这里钉住
  155. // "driver 不再有第二份名单":一条 launch 时不存在的命令照样执行。
  156. const { port, calls } = stubExecutionPort({});
  157. const driver = makeDriver(port);
  158. await expect(driver.executeWorldRead("run", ["echo", ["hi"]])).resolves.toMatchObject({
  159. exitCode: 0,
  160. });
  161. expect(calls.map((call) => call.file)).toEqual(["echo"]);
  162. });
  163. it("accepts exactly cap bytes in full mode (the +1 probe tells 'exactly' from 'over')", async () => {
  164. // 文本内容与本断言无关,只看 bytes / truncated;不真造 16 MiB 字符串。
  165. const { port } = stubExecutionPort({
  166. stdout: { text: "x", bytes: CAP, truncated: false } as never,
  167. });
  168. const driver = makeDriver(port);
  169. await expect(driver.executeWorldRead("run", ["node", []])).resolves.toMatchObject({
  170. stdout: "x",
  171. });
  172. });
  173. it("rejects stdout over the 16 MiB cap with actionable guidance (cap+1 probe)", async () => {
  174. const { port } = stubExecutionPort({
  175. stdout: { text: "x", bytes: CAP + 1, truncated: false } as never,
  176. });
  177. const driver = makeDriver(port);
  178. await expect(driver.executeWorldRead("run", ["node", ["-e", "spam"]])).rejects.toMatchObject({
  179. code: "WorldReadCapExceeded",
  180. message: expect.stringMatching(/stdout[\s\S]*output: \{ tail: n \}/u),
  181. });
  182. });
  183. it("rejects stderr over the cap the same way", async () => {
  184. const { port } = stubExecutionPort({
  185. stderr: { text: "y", bytes: 1, truncated: true } as never,
  186. });
  187. const driver = makeDriver(port);
  188. await expect(driver.executeWorldRead("run", ["node", []])).rejects.toMatchObject({
  189. code: "WorldReadCapExceeded",
  190. message: expect.stringContaining("stderr"),
  191. });
  192. });
  193. it("validates argument shapes loudly, never coercing", async () => {
  194. const { port, calls } = stubExecutionPort({});
  195. const driver = makeDriver(port);
  196. const reject = (args: unknown[]) =>
  197. expect(driver.executeWorldRead("run", args)).rejects.toMatchObject({ code: "DriverError" });
  198. await reject([]);
  199. await reject([42]);
  200. await reject(["lean", "not-an-array"]);
  201. await reject(["lean", [1]]);
  202. await reject(["lean", [], "not-opts"]);
  203. await reject(["lean", [], { timeoutMs: 0 }]);
  204. await reject(["lean", [], { timeoutMs: 1.5 }]);
  205. await reject(["lean", [], {}, "extra"]);
  206. expect(calls).toEqual([]);
  207. });
  208. });
  209. describe("workflow driver — world.run output modes", () => {
  210. const huge = (tail?: string) =>
  211. ({ text: "", bytes: 10 * CAP, truncated: true, ...(tail === undefined ? {} : { tail }) }) as never;
  212. it("explicit output 'full' sends the same request as the default", async () => {
  213. const { port, calls } = stubExecutionPort({});
  214. const driver = makeDriver(port);
  215. await driver.executeWorldRead("run", ["lean", [], { output: "full" }]);
  216. expect(calls[0]).toMatchObject({ maxInlineBytes: CAP + 1, tailBytes: undefined });
  217. });
  218. it("discard asks for no inline bytes and returns empty streams whatever the process printed", async () => {
  219. const { port, calls } = stubExecutionPort({ stdout: huge(), stderr: huge() });
  220. const driver = makeDriver(port);
  221. await expect(
  222. driver.executeWorldRead("run", ["pnpm", ["test"], { output: "discard" }]),
  223. ).resolves.toEqual({ exitCode: 0, stdout: "", stderr: "" });
  224. expect(calls[0]).toMatchObject({ maxInlineBytes: 0, tailBytes: undefined });
  225. });
  226. it("discard still returns a nonzero exit as a value", async () => {
  227. const { port } = stubExecutionPort({ status: "failed", exitCode: 1, stdout: huge(), stderr: huge() });
  228. const driver = makeDriver(port);
  229. await expect(
  230. driver.executeWorldRead("run", ["pnpm", ["test"], { output: "discard" }]),
  231. ).resolves.toEqual({ exitCode: 1, stdout: "", stderr: "" });
  232. });
  233. it("tail asks the port for the last n bytes and returns them per stream", async () => {
  234. const { port, calls } = stubExecutionPort({
  235. status: "failed",
  236. exitCode: 2,
  237. stdout: huge("last out"),
  238. stderr: huge("last err"),
  239. });
  240. const driver = makeDriver(port);
  241. await expect(
  242. driver.executeWorldRead("run", ["pnpm", ["test"], { output: { tail: 4096 } }]),
  243. ).resolves.toEqual({ exitCode: 2, stdout: "last out", stderr: "last err" });
  244. expect(calls[0]).toMatchObject({ maxInlineBytes: 0, tailBytes: 4096 });
  245. });
  246. it("tail accepts n at both bounds (1 and the cap)", async () => {
  247. const { port, calls } = stubExecutionPort({ stdout: huge("x"), stderr: huge("") });
  248. const driver = makeDriver(port);
  249. await driver.executeWorldRead("run", ["node", [], { output: { tail: 1 } }]);
  250. await driver.executeWorldRead("run", ["node", [], { output: { tail: CAP } }]);
  251. expect(calls.map((call) => call.tailBytes)).toEqual([1, CAP]);
  252. });
  253. it("tail fails loudly when the port returns no tail (wiring error, not an empty stream)", async () => {
  254. const { port } = stubExecutionPort({ stdout: huge(), stderr: huge() });
  255. const driver = makeDriver(port);
  256. await expect(
  257. driver.executeWorldRead("run", ["node", [], { output: { tail: 8 } }]),
  258. ).rejects.toMatchObject({ code: "DriverError", message: expect.stringContaining("tail") });
  259. });
  260. it("rejects bad output shapes with an actionable DriverError before running anything", async () => {
  261. const { port, calls } = stubExecutionPort({});
  262. const driver = makeDriver(port);
  263. const reject = (output: unknown) =>
  264. expect(driver.executeWorldRead("run", ["lean", [], { output }])).rejects.toMatchObject({
  265. code: "DriverError",
  266. message: expect.stringContaining("opts.output"),
  267. });
  268. await reject("quiet");
  269. await reject(null);
  270. await reject([]);
  271. await reject({});
  272. await reject({ tail: 0 });
  273. await reject({ tail: -1 });
  274. await reject({ tail: 1.5 });
  275. await reject({ tail: "64" });
  276. await reject({ tail: CAP + 1 });
  277. await reject({ tail: 64, head: 64 });
  278. expect(calls).toEqual([]);
  279. });
  280. });