guarded-workflow.test.ts 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. import { mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it, vi } from "vitest";
  5. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  6. import type { PermissionBrokerRequest } from "@zcode/contracts";
  7. import {
  8. createRegistryBackedTestApp,
  9. createTestProviderRegistry,
  10. } from "./helpers/registry-backed-test-app.js";
  11. describe("guarded workflow runtime ingress", () => {
  12. // 真实 App、SQLite 与父子工作流有初始化开销;框架预算不改变权限及产品超时。
  13. it.each(["expert", "script"] as const)(
  14. "%s child stays YOLO while its parent remains guarded",
  15. async (kind) => {
  16. const root = await mkdtemp(join(tmpdir(), "guarded-workflow-"));
  17. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  18. const selection = {
  19. providerId: "parent",
  20. modelId: "model",
  21. options: { reasoningLevel: "high" },
  22. };
  23. const requests: PermissionBrokerRequest[] = [];
  24. const modelRequests: string[] = [];
  25. const execute = vi.fn(async () => ({
  26. status: "completed" as const,
  27. stdout: { text: "controlled execution", bytes: 20, truncated: false },
  28. stderr: { text: "", bytes: 0, truncated: false },
  29. exitCode: 0,
  30. durationMs: 1,
  31. timedOut: false,
  32. cancelled: false,
  33. startedAt: new Date(),
  34. completedAt: new Date(),
  35. }));
  36. let sent = false;
  37. const app = await createRegistryBackedTestApp({
  38. env: { ZCODE_HOME: root },
  39. skipUserConfig: true,
  40. sessionStore: store,
  41. providerRegistry: createTestProviderRegistry([selection]),
  42. executionPort: { run: execute },
  43. permissionBroker: {
  44. requestPermission: async (request) => {
  45. requests.push(request);
  46. return { decision: "deny", reason: "guarded fixture denial" };
  47. },
  48. },
  49. runtimeConfig: {
  50. mode: "guarded",
  51. workingDirectory: root,
  52. mcp: { enabled: false },
  53. modelSelection: selection,
  54. },
  55. modelExecutor: {
  56. async generateText(request) {
  57. modelRequests.push(JSON.stringify(request));
  58. const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
  59. if (!sent) {
  60. sent = true;
  61. return {
  62. finishReason: "tool-calls",
  63. text: "",
  64. usage,
  65. toolCalls: [
  66. {
  67. id: "guarded-workflow-rm",
  68. name: "Bash",
  69. input: { command: "rm -rf fixture-only" },
  70. },
  71. ],
  72. };
  73. }
  74. return {
  75. finishReason: "stop",
  76. usage,
  77. text: JSON.stringify({
  78. done: true,
  79. reasoning: "controlled execution completed",
  80. verdict: "pass",
  81. }),
  82. };
  83. },
  84. },
  85. });
  86. try {
  87. if (kind === "script") {
  88. const scriptPath = join(root, "guarded.workflow.js");
  89. await writeFile(
  90. scriptPath,
  91. 'export const meta = { name: "guarded", description: "guarded test", phases: [{ title: "Run" }] }; phase("Run"); return await agent("Run the fixture command.");',
  92. );
  93. await app.runWorkflowScript?.({ scriptPath });
  94. } else {
  95. await app.runExpertWorkflow({ task: "Run the fixture command." });
  96. }
  97. expect(requests).toHaveLength(0);
  98. expect(execute).toHaveBeenCalledTimes(1);
  99. expect(modelRequests.some((request) => request.includes("controlled execution"))).toBe(
  100. true,
  101. );
  102. expect(app.runtime.getMode()).toBe("guarded");
  103. // 子任务的 YOLO 不得污染父任务:随后父任务同一命令仍必须得到拒绝结果。
  104. sent = false;
  105. await app.runtime.executeTurn("Run the fixture command in the parent.");
  106. expect(requests).toHaveLength(1);
  107. expect(requests[0]?.approvalMode).toBe("user-once");
  108. expect(execute).toHaveBeenCalledTimes(1);
  109. expect(modelRequests.some((request) => request.includes("guarded fixture denial"))).toBe(
  110. true,
  111. );
  112. } finally {
  113. await app.close?.();
  114. store.close();
  115. await rm(root, { recursive: true, force: true });
  116. }
  117. },
  118. 30_000,
  119. );
  120. });