repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/plugins/chef/test/executor.test.ts

Raw
import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";

import {
  AgentError,
  AgentTimeoutError,
  ChefError,
  Executor,
  GateFailureError,
  MaxIterationsError,
} from "../executor";
import { Store } from "../store";
import { z } from "zod";

let store: Store;
let tempDir: string;
let mockClient: any;

beforeEach(() => {
  tempDir = mkdtempSync(join(tmpdir(), "chef-exec-test-"));
  store = new Store(tempDir);

  mockClient = {
    session: {
      create: mock(() => Promise.resolve({ id: "session-1" })),
      prompt: mock(() =>
        Promise.resolve({
          data: { info: { structured_output: { result: "ok" } } },
        })
      ),
      delete: mock(() => Promise.resolve()),
    },
    app: {
      log: mock(() => Promise.resolve()),
      agents: mock(() => Promise.resolve([])),
    },
  };
});

afterEach(() => {
  store.close();
  rmSync(tempDir, { recursive: true, force: true });
});

// Helper to create a basic pipeline definition
function createDefinition(phases: any[]) {
  return { name: "test-pipeline", phases };
}

function createExecutor(
  definition: any,
  options?: { maxLoopIterations?: number },
) {
  return new Executor(
    store,
    mockClient as any,
    definition,
    options,
  );
}

describe("Executor - Basic step execution", () => {
  test("executes a single step pipeline", async () => {
    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do thing",
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("completed");
    expect(result.context.step1).toEqual({ result: "ok" });
  });

  test("creates session with correct agent", async () => {
    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "my-special-agent",
        prompt: "do thing",
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    await executor.execute(instance.id, {});

    expect(mockClient.session.create).toHaveBeenCalled();
    const createCall = (mockClient.session.create as any).mock.calls[0][0];
    expect(createCall.body.agent).toBe("my-special-agent");
  });

  test("injects context before prompting", async () => {
    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do thing",
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", { existing: "data" });
    const executor = createExecutor(definition);
    await executor.execute(instance.id, {});

    // Two prompt calls: context injection (noReply: true) and execution
    expect(mockClient.session.prompt).toHaveBeenCalledTimes(2);

    // First call is context injection
    const contextCall = (mockClient.session.prompt as any).mock.calls[0][0];
    expect(contextCall.body.noReply).toBe(true);

    // Second call is execution
    const execCall = (mockClient.session.prompt as any).mock.calls[1][0];
    expect(execCall.body.noReply).toBeUndefined();
    expect(execCall.body.format).toBeDefined();
  });

  test("uses string prompt directly", async () => {
    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do the thing now",
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    await executor.execute(instance.id, {});

    const execCall = (mockClient.session.prompt as any).mock.calls[1][0];
    expect(execCall.body.parts[0].text).toBe("do the thing now");
  });

  test("evaluates function prompt with context", async () => {
    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: (ctx: any) => `dynamic prompt based on ${ctx.inputValue}`,
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {
      inputValue: "test-input",
    });
    const executor = createExecutor(definition);
    await executor.execute(instance.id, { inputValue: "test-input" });

    const execCall = (mockClient.session.prompt as any).mock.calls[1][0];
    expect(execCall.body.parts[0].text).toBe(
      "dynamic prompt based on test-input",
    );
  });
});

describe("Executor - Context flow", () => {
  test("context flows between steps", async () => {
    let capturedContext: any;
    let callCount = 0;

    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "first step",
        output: z.object({ findings: z.string() }),
      },
      {
        name: "step2",
        type: "step",
        agent: "test-agent",
        prompt: (ctx: any) => {
          capturedContext = ctx;
          return "second step";
        },
        output: z.object({ result: z.string() }),
      },
    ]);

    // Replace mock with one that returns different values based on call count
    mockClient.session.prompt = mock(() => {
      callCount++;
      // Odd calls are context injection (1, 3), even calls are execution (2, 4)
      if (callCount % 2 === 0) {
        // Execution call - return step1's output on second execution
        return Promise.resolve({
          data: { info: { structured_output: { findings: "important-data" } } },
        });
      }
      // Context injection
      return Promise.resolve({});
    });

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    await executor.execute(instance.id, {});

    // The second step's prompt function should have received context with step1's output
    expect(capturedContext.step1).toEqual({ findings: "important-data" });
  });
});

describe("Executor - Retry logic", () => {
  test("retries on failure and succeeds", async () => {
    let attemptCount = 0;
    mockClient.session.prompt = mock(() => {
      attemptCount++;
      // Even calls (0, 2) are context injection, odd calls (1, 3) are execution
      if (attemptCount % 2 === 0) {
        // Execution prompt
        if (attemptCount < 4) {
          // First execution fails
          return Promise.reject(new AgentError("step1", "Temporary failure"));
        }
        return Promise.resolve({
          data: { info: { structured_output: { result: "ok" } } },
        });
      }
      // Context injection succeeds
      return Promise.resolve({});
    });

    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do thing",
        retry: { maxAttempts: 3, backoffMs: 1, retryOn: undefined },
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("completed");
    expect(result.context.step1).toEqual({ result: "ok" });
  });

  test("gives up after maxAttempts", async () => {
    let attemptCount = 0;
    mockClient.session.prompt = mock(() => {
      attemptCount++;
      if (attemptCount % 2 === 0) {
        // Execution - always fails
        return Promise.reject(new AgentError("step1", "Permanent failure"));
      }
      return Promise.resolve({});
    });

    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do thing",
        retry: { maxAttempts: 2, backoffMs: 1, retryOn: undefined },
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("failed");
    expect(result.error).toContain("Permanent failure");
  });

  test("only retries on matching error types", async () => {
    let attemptCount = 0;
    mockClient.session.prompt = mock(() => {
      attemptCount++;
      if (attemptCount % 2 === 0) {
        // Execution - throws agent_error (not agent_timeout)
        return Promise.reject(new AgentError("step1", "Wrong error type"));
      }
      return Promise.resolve({});
    });

    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do thing",
        retry: { maxAttempts: 3, backoffMs: 1, retryOn: ["agent_timeout"] },
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    // Should fail immediately because agent_error doesn't match retryOn
    expect(result.status).toBe("failed");
    expect(result.error).toContain("Wrong error type");
    // Only one attempt made (context injection + 1 execution)
    expect(attemptCount).toBe(2);
  });

  test("retries on 'all' error type", async () => {
    let attemptCount = 0;
    mockClient.session.prompt = mock(() => {
      attemptCount++;
      if (attemptCount % 2 === 0) {
        if (attemptCount < 4) {
          return Promise.reject(new AgentError("step1", "Some error"));
        }
        return Promise.resolve({
          data: { info: { structured_output: { result: "ok" } } },
        });
      }
      return Promise.resolve({});
    });

    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do thing",
        retry: { maxAttempts: 3, backoffMs: 1, retryOn: ["all"] },
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("completed");
    expect(result.context.step1).toEqual({ result: "ok" });
  });
});

describe("Executor - Timeout", () => {
  test("step that takes too long throws AgentTimeoutError", async () => {
    let callCount = 0;
    mockClient.session.prompt = mock(() => {
      callCount++;
      // First call is context injection - resolve immediately
      if (callCount === 1) {
        return Promise.resolve({});
      }
      // Second call (execution) - never resolves (will timeout)
      return new Promise(() => {});
    });

    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do thing",
        timeout: 10, // very short timeout
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("failed");
    expect(result.error).toContain("timed out");
  });
});

describe("Executor - Session cleanup", () => {
  test("cleans up session on success", async () => {
    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do thing",
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    await executor.execute(instance.id, {});

    expect(mockClient.session.delete).toHaveBeenCalled();
    const deleteCall = (mockClient.session.delete as any).mock.calls[0][0];
    expect(deleteCall.path.id).toBe("session-1");
  });

  test("cleans up session on failure", async () => {
    let attemptCount = 0;
    mockClient.session.prompt = mock(() => {
      attemptCount++;
      if (attemptCount % 2 === 0) {
        return Promise.reject(new AgentError("step1", "Failure"));
      }
      return Promise.resolve({});
    });

    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do thing",
        retry: { maxAttempts: 1, backoffMs: 1, retryOn: undefined },
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    await executor.execute(instance.id, {});

    expect(mockClient.session.delete).toHaveBeenCalled();
  });

  test("tracks leaked sessions when cleanup fails", async () => {
    mockClient.session.delete = mock(() =>
      Promise.reject(new Error("Delete failed"))
    );

    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do thing",
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("completed");
    // The cleanup failed but pipeline still completed
    expect(mockClient.app.log).toHaveBeenCalled();
  });

  test("redacts session IDs in leaked session logs", async () => {
    const longSessionId = "abcdefghijklmnop-1234-5678-9abc-def012345678";
    mockClient.session.create = mock(() =>
      Promise.resolve({ id: longSessionId })
    );
    mockClient.session.delete = mock(() =>
      Promise.reject(new Error("Delete failed"))
    );

    // Capture console.warn output
    const warnSpy: string[] = [];
    const origWarn = console.warn;
    console.warn = (...args: any[]) => warnSpy.push(args.join(" "));

    try {
      const definition = createDefinition([
        {
          name: "step1",
          type: "step",
          agent: "test-agent",
          prompt: "do thing",
          output: z.object({ result: z.string() }),
        },
      ]);
      const instance = store.createPipeline("test-pipe", {});
      const executor = createExecutor(definition);
      await executor.execute(instance.id, {});

      // Check that the warn output contains truncated ID, not full ID
      const leakedWarn = warnSpy.find((w) => w.includes("leaked session"));
      expect(leakedWarn).toBeDefined();
      expect(leakedWarn!).toContain("abcdefgh…");
      expect(leakedWarn!).not.toContain(
        "abcdefghijklmnop-1234-5678-9abc-def012345678",
      );
    } finally {
      console.warn = origWarn;
    }
  });

  test("redactId handles short and long IDs correctly", () => {
    // Access the private static method via (Executor as any)
    const redact = (Executor as any).redactId;
    expect(redact).toBeDefined();

    // Long IDs are truncated to first 8 chars + ellipsis
    expect(redact("abcdefghijklmnop")).toBe("abcdefgh…");
    expect(redact("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee")).toBe("aaaaaaaa…");

    // Short IDs (<= 8 chars) are returned unchanged
    expect(redact("short")).toBe("short");
    expect(redact("12345678")).toBe("12345678");
  });
});

describe("Executor - Gate execution", () => {
  test("gate with agent succeeds", async () => {
    const definition = createDefinition([
      {
        name: "gate1",
        type: "gate",
        agent: "test-agent",
        expect: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("completed");
    expect(result.context.gate1).toEqual({ result: "ok" });
  });

  test("gate without agent validates context directly", async () => {
    const definition = createDefinition([
      {
        name: "gate1",
        type: "gate",
        expect: z.object({ research: z.object({ findings: z.string() }) }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {
      research: { findings: "valid-data" },
    });
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {
      research: { findings: "valid-data" },
    });

    expect(result.status).toBe("completed");
    expect(result.context.gate1).toEqual({
      research: { findings: "valid-data" },
    });
  });

  test("gate failure with onFail loops back", async () => {
    let promptCallCount = 0;

    mockClient.session.prompt = mock((opts: any) => {
      promptCallCount++;
      // Flow:
      // Call 1: step1 context injection
      // Call 2: step1 execution
      // Call 3: gate1 context injection
      // Call 4: gate1 first evaluation (FAIL - loops back to step1)
      // Call 5: step1 retry context injection
      // Call 6: step1 retry execution
      // Call 7: gate1 second context injection
      // Call 8: gate1 second evaluation (SUCCEED)
      if (promptCallCount === 4) {
        // First gate evaluation - fail
        return Promise.reject(
          new GateFailureError("gate1", "Validation failed"),
        );
      }
      if (promptCallCount === 8) {
        // Second gate evaluation - succeed
        return Promise.resolve({
          data: { info: { structured_output: { result: "gate-ok" } } },
        });
      }
      // All other calls succeed
      return Promise.resolve({
        data: { info: { structured_output: { result: "ok" } } },
      });
    });

    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do step1",
        output: z.object({ result: z.string() }),
      },
      {
        name: "gate1",
        type: "gate",
        agent: "test-agent",
        expect: z.object({ result: z.string() }),
        onFail: "step1",
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    // Gate fails, loops back to step1, then gate succeeds
    expect(result.status).toBe("completed");
    expect(result.context.gate1).toEqual({ result: "gate-ok" });
  });

  test("gate failure without onFail fails pipeline", async () => {
    mockClient.session.prompt = mock(() =>
      Promise.reject(new GateFailureError("gate1", "Validation failed"))
    );

    const definition = createDefinition([
      {
        name: "gate1",
        type: "gate",
        agent: "test-agent",
        expect: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("failed");
    expect(result.error).toContain("Validation failed");
  });
});

describe("Executor - Parallel execution", () => {
  test("executes all parallel steps", async () => {
    let sessionCreateCount = 0;
    const sessionStepMap = new Map<string, number>();
    const outputs = ["result-a", "result-b"];

    // Mock session.create to return unique IDs and track which step
    const originalCreate = mockClient.session.create;
    mockClient.session.create = mock(() => {
      sessionCreateCount++;
      const sessionId = `session-${sessionCreateCount}`;
      sessionStepMap.set(sessionId, sessionCreateCount - 1); // step index
      return Promise.resolve({ id: sessionId });
    });

    // Reset prompt mock to use the session mapping
    mockClient.session.prompt = mock((opts: any) => {
      const stepIndex = sessionStepMap.get(opts?.path?.id) ?? 0;
      // Context injection: noReply is true
      if (opts?.body?.noReply) {
        return Promise.resolve({});
      }
      // Execution
      return Promise.resolve({
        data: { info: { structured_output: { value: outputs[stepIndex] } } },
      });
    });

    const definition = createDefinition([
      {
        name: "parallel_0",
        type: "parallel",
        steps: [
          {
            name: "step1",
            agent: "test-agent",
            prompt: "do thing A",
            output: z.object({ value: z.string() }),
          },
          {
            name: "step2",
            agent: "test-agent",
            prompt: "do thing B",
            output: z.object({ value: z.string() }),
          },
        ],
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("completed");
    expect(result.context.parallel_0.step1).toEqual({ value: "result-a" });
    expect(result.context.parallel_0.step2).toEqual({ value: "result-b" });
  });

  test("parallel fails if any step fails", async () => {
    let callCount = 0;
    mockClient.session.prompt = mock(() => {
      callCount++;
      // Context injection: odd calls - succeed with empty structured output
      // Execution: even calls - fail with AgentError
      if (callCount % 2 === 0) {
        return Promise.reject(new AgentError("step1", "One step failed"));
      }
      // Return a proper response structure for context injection
      return Promise.resolve({
        data: { info: { structured_output: {} } },
      });
    });

    const definition = createDefinition([
      {
        name: "parallel_0",
        type: "parallel",
        steps: [
          {
            name: "step1",
            agent: "test-agent",
            prompt: "do thing",
            output: z.object({ value: z.string() }),
          },
          {
            name: "step2",
            agent: "test-agent",
            prompt: "do thing",
            output: z.object({ value: z.string() }),
          },
        ],
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("failed");
    expect(result.error).toContain("One step failed");
  });
});

describe("Executor - When/Loop", () => {
  test("when condition met causes loop", async () => {
    let whenCallCount = 0;

    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do thing",
        output: z.object({ result: z.string() }),
      },
      {
        name: "when_0",
        type: "when",
        condition: (ctx: any) => {
          whenCallCount++;
          return whenCallCount < 2; // Loop once, then pass through
        },
        loopTarget: "step1",
      },
      {
        name: "step2",
        type: "step",
        agent: "test-agent",
        prompt: "do next thing",
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("completed");
    expect(whenCallCount).toBe(2); // Called twice - once to trigger loop, once to pass through
  });

  test("when condition not met passes through", async () => {
    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do thing",
        output: z.object({ result: z.string() }),
      },
      {
        name: "when_0",
        type: "when",
        condition: () => false, // Never loop
      },
      {
        name: "step2",
        type: "step",
        agent: "test-agent",
        prompt: "do next thing",
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("completed");
    expect(result.context.step2).toEqual({ result: "ok" });
  });

  test("max iterations guard", async () => {
    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do thing",
        output: z.object({ result: z.string() }),
      },
      {
        name: "when_0",
        type: "when",
        condition: () => true, // Always loop back
        loopTarget: "step1",
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition, { maxLoopIterations: 3 });
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("failed");
    expect(result.error).toContain("Max loop iterations");
  });
});

describe("Executor - Abort", () => {
  test("aborted pipeline stops execution", async () => {
    let stepCount = 0;
    let pipelineId: string | undefined;

    mockClient.session.prompt = mock(() => {
      stepCount++;
      if (stepCount === 2) {
        // After first step completes, abort the pipeline
        const instance = store.getPipeline(pipelineId!);
        if (instance) {
          store.updatePipeline(instance.id, { status: "aborted" });
        }
      }
      return Promise.resolve({
        data: { info: { structured_output: { result: "ok" } } },
      });
    });

    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do thing",
        output: z.object({ result: z.string() }),
      },
      {
        name: "step2",
        type: "step",
        agent: "test-agent",
        prompt: "should not run",
        output: z.object({ result: z.string() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    pipelineId = instance.id;
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("aborted");
    // Only first step should have run
    expect(result.context.step1).toEqual({ result: "ok" });
    expect(result.context.step2).toBeUndefined();
  });
});

describe("Executor - Pipeline completion", () => {
  test("completed pipeline returns accumulated context", async () => {
    const outputs = [
      { data: { info: { structured_output: { a: 1 } } } },
      { data: { info: { structured_output: { b: 2 } } } },
    ];
    let outputIndex = 0;

    mockClient.session.prompt = mock(() => {
      const callIndex = (mockClient.session.prompt as any).mock.calls.length;
      if (callIndex % 2 === 0) {
        // Execution call
        return Promise.resolve(outputs[outputIndex++]);
      }
      return Promise.resolve({});
    });

    const definition = createDefinition([
      {
        name: "step1",
        type: "step",
        agent: "test-agent",
        prompt: "do first thing",
        output: z.object({ a: z.number() }),
      },
      {
        name: "step2",
        type: "step",
        agent: "test-agent",
        prompt: "do second thing",
        output: z.object({ b: z.number() }),
      },
    ]);

    const instance = store.createPipeline("test-pipe", {});
    const executor = createExecutor(definition);
    const result = await executor.execute(instance.id, {});

    expect(result.status).toBe("completed");
    expect(result.context.step1).toEqual({ a: 1 });
    expect(result.context.step2).toEqual({ b: 2 });
  });
});

describe("Executor - Error classes", () => {
  test("exports correct error classes", async () => {
    // Verify all expected error classes exist
    expect(ChefError).toBeDefined();
    expect(AgentTimeoutError).toBeDefined();
    expect(AgentError).toBeDefined();
    expect(GateFailureError).toBeDefined();
    expect(MaxIterationsError).toBeDefined();

    // Verify they are Error subclasses
    const chefError = new ChefError("test", "test_type");
    expect(chefError).toBeInstanceOf(Error);
    expect(chefError.name).toBe("ChefError");

    const timeoutError = new AgentTimeoutError("step1", 1000);
    expect(timeoutError).toBeInstanceOf(ChefError);
    expect(timeoutError.name).toBe("AgentTimeoutError");
    expect(timeoutError.message).toContain("step1");
    expect(timeoutError.message).toContain("1000ms");

    const agentError = new AgentError("step1", "something went wrong");
    expect(agentError).toBeInstanceOf(ChefError);
    expect(agentError.name).toBe("AgentError");
    expect(agentError.message).toContain("step1");
    expect(agentError.message).toContain("something went wrong");

    const gateError = new GateFailureError("gate1", "validation failed");
    expect(gateError).toBeInstanceOf(ChefError);
    expect(gateError.name).toBe("GateFailureError");
    expect(gateError.message).toContain("gate1");

    const maxIterError = new MaxIterationsError(5);
    expect(maxIterError).toBeInstanceOf(ChefError);
    expect(maxIterError.name).toBe("MaxIterationsError");
    expect(maxIterError.message).toContain("5");
  });
});