guarded-workflow.test.ts 4.3 KB

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