import { Effect, Either, Option, PubSub, Stream } from "effect";
import { describe, expect, it } from "vitest";

import {
  BeatGamePhase,
  BeatGameCancelled,
  BeatGameDriverError,
  BeatGameRunStatus,
  InMemoryBeatGameCheckpointStore,
  beatGameTeamWithDrivers,
  beatGameWithDriver,
  defaultBeatGameStrategy,
  type BeatGameBlockPosition,
  type BeatGameDriverEvent,
  type BeatGameEntityObservation,
} from "../src/index.js";
import {
  blockObservation,
  checkpoint,
  FakeBeatGameDriver,
  installStaircaseMovementSimulation,
  observation,
  postDragonHooks,
} from "./fixtures.js";

async function runUntilExplorationStarts(options: {
  readonly driver: FakeBeatGameDriver;
  readonly store: InMemoryBeatGameCheckpointStore;
  readonly runId: string;
  readonly teamId: string;
}): Promise<{ readonly x: number; readonly z: number }> {
  const { driver, store, runId, teamId } = options;
  driver.xzPathResolver = (x, z, dimension, radius, policy) =>
    Effect.sync(() => {
      driver.xzPaths.push({ x, z, dimension, radius, policy });
    }).pipe(Effect.zipRight(Effect.never));
  await Effect.runPromise(Effect.scoped(
    beatGameWithDriver(driver, {
      runId,
      team: { teamId },
      checkpointStore: store,
      strategy: { observationPollMs: 1 },
    }).pipe(
      Effect.flatMap((run) =>
        Effect.gen(function* () {
          while (driver.xzPaths.length === 0) {
            yield* Effect.sleep(1);
          }
          yield* run.stop;
          yield* run.awaitCompletion.pipe(Effect.either);
        })
      ),
    ),
  ));
  const path = driver.xzPaths[0];
  if (path === undefined) {
    throw new Error("Exploration did not start");
  }
  return path;
}

describe("beat-game run lifecycle", () => {
  it("ignores one transient under-equipped observation at night", async () => {
    const driver = new FakeBeatGameDriver();
    const protectedObservation = observation({
      counts: {
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:cooked_beef": 4,
      },
    });
    driver.currentEnvironment = { gameTime: 14_000n };
    driver.currentObservation = protectedObservation;
    let actionStarted = false;
    let safetyObservations = 0;
    driver.observationResolver = () =>
      Effect.sync(() => {
        if (!actionStarted) {
          return protectedObservation;
        }
        safetyObservations += 1;
        return safetyObservations === 1
          ? observation({ counts: { "minecraft:stone_sword": 1 } })
          : protectedObservation;
      });
    const failures: string[] = [];

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
        hooks: {
          satisfyRequirement: () =>
            Effect.sync(() => {
              actionStarted = true;
            }).pipe(Effect.zipRight(Effect.never)),
        },
      });
      yield* run.events.pipe(
        Stream.runForEach((event) =>
          event.type === "action-failed"
              && event.detail?.includes(
                "night fell while the bot was under-equipped",
              ) === true
            ? Effect.sync(() => {
              failures.push(event.detail ?? "");
            })
            : Effect.void
        ),
        Effect.forkScoped,
      );
      while (safetyObservations < 3) {
        yield* Effect.sleep(1);
      }
      yield* Effect.sleep(5);
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(failures).toEqual([]);
  });

  it("recognizes equipped protection while a container is open", async () => {
    const driver = new FakeBeatGameDriver();
    const protectedObservation = observation({
      counts: {
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:cooked_beef": 4,
      },
      equipment: {
        mainhand: "minecraft:stone_sword",
        offhand: "minecraft:shield",
      },
    });
    const containerObservation = observation({
      counts: { "minecraft:cooked_beef": 4 },
      equipment: protectedObservation.player.equipment,
    });
    driver.currentEnvironment = { gameTime: 14_000n };
    driver.currentObservation = protectedObservation;
    let actionStarted = false;
    let safetyObservations = 0;
    driver.observationResolver = () =>
      Effect.sync(() => {
        if (!actionStarted) {
          return protectedObservation;
        }
        safetyObservations += 1;
        return containerObservation;
      });
    const failures: string[] = [];

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
        hooks: {
          satisfyRequirement: () =>
            Effect.sync(() => {
              actionStarted = true;
            }).pipe(Effect.zipRight(Effect.never)),
        },
      });
      yield* run.events.pipe(
        Stream.runForEach((event) =>
          event.type === "action-failed"
              && event.detail?.includes(
                "night fell while the bot was under-equipped",
              ) === true
            ? Effect.sync(() => {
              failures.push(event.detail ?? "");
            })
            : Effect.void
        ),
        Effect.forkScoped,
      );
      while (safetyObservations < 3) {
        yield* Effect.sleep(1);
      }
      yield* Effect.sleep(5);
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(failures).toEqual([]);
  });

  it("keeps working at night while safely below the surface", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentEnvironment = { gameTime: 14_000n };
    driver.currentObservation = observation({
      position: {
        x: 0.5,
        y: 40,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      counts: { "minecraft:wooden_sword": 1 },
    });
    driver.surfaceColumns = [{
      x: 0,
      z: 0,
      loaded: true,
      surfaceY: 64,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    let actionStarted = false;
    const failures: string[] = [];

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
        hooks: {
          satisfyRequirement: () =>
            Effect.sync(() => {
              actionStarted = true;
            }).pipe(Effect.zipRight(Effect.never)),
        },
      });
      yield* run.events.pipe(
        Stream.runForEach((event) =>
          event.type === "action-failed"
            ? Effect.sync(() => {
              failures.push(event.detail ?? "");
            })
            : Effect.void
        ),
        Effect.forkScoped,
      );
      while (!actionStarted || driver.surfaceQueries.length < 3) {
        yield* Effect.sleep(1);
      }
      yield* Effect.sleep(5);
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(failures).toEqual([]);
    expect(driver.surfaceQueries).toEqual(expect.arrayContaining([
      expect.objectContaining({
        center: expect.objectContaining({ x: 0.5, y: 40, z: 0.5 }),
        radius: 0,
        sampleStep: 1,
      }),
    ]));
    expect(driver.actions).not.toEqual(expect.arrayContaining([
      expect.objectContaining({ type: "dig-block" }),
      expect.objectContaining({ type: "place-block" }),
    ]));
  });

  it("keeps working in a deep cave below a tree canopy", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentEnvironment = { gameTime: 14_000n };
    driver.currentObservation = observation({
      position: {
        x: 0.5,
        y: -51,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      counts: { "minecraft:wooden_sword": 1 },
    });
    driver.surfaceColumns = [{
      x: 0,
      z: 0,
      loaded: true,
      surfaceY: 80,
      blockId: "minecraft:oak_leaves",
      biomeId: "minecraft:forest",
      skyLight: 15,
      blockLight: 0,
    }];
    let actionStarted = false;
    const failures: string[] = [];

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
        hooks: {
          satisfyRequirement: () =>
            Effect.sync(() => {
              actionStarted = true;
            }).pipe(Effect.zipRight(Effect.never)),
        },
      });
      yield* run.events.pipe(
        Stream.runForEach((event) =>
          event.type === "action-failed"
            ? Effect.sync(() => {
              failures.push(event.detail ?? "");
            })
            : Effect.void
        ),
        Effect.forkScoped,
      );
      while (!actionStarted || driver.surfaceQueries.length < 3) {
        yield* Effect.sleep(1);
      }
      yield* Effect.sleep(5);
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    }).pipe(Effect.timeoutFail({
      duration: "2 seconds",
      onTimeout: () => new Error("Timed out waiting for cave work to start"),
    }))));

    expect(failures).toEqual([]);
    expect(driver.actions).not.toEqual(expect.arrayContaining([
      expect.objectContaining({ type: "dig-block" }),
      expect.objectContaining({ type: "place-block" }),
    ]));
  });

  it("does not mistake a tree canopy for safe underground cover", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentEnvironment = { gameTime: 12_000n };
    driver.currentObservation = observation({
      position: {
        x: 0.5,
        y: 64,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
    });
    driver.surfaceColumns = [{
      x: 0,
      z: 0,
      loaded: true,
      surfaceY: 76,
      blockId: "minecraft:oak_leaves",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    let actionStarted = false;
    const failures: string[] = [];
    driver.environmentResolver = () =>
      Effect.succeed({ gameTime: actionStarted ? 14_000n : 12_000n });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
        hooks: {
          satisfyRequirement: () =>
            Effect.sync(() => {
              actionStarted = true;
            }).pipe(Effect.zipRight(Effect.never)),
        },
      });
      yield* run.events.pipe(
        Stream.runForEach((event) =>
          event.type === "action-failed"
              && event.detail?.includes(
                "night fell while the bot was under-equipped",
              ) === true
            ? Effect.sync(() => {
              failures.push(event.detail ?? "");
            })
            : Effect.void
        ),
        Effect.forkScoped,
      );
      while (failures.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    }).pipe(Effect.timeoutFail({
      duration: "2 seconds",
      onTimeout: () => new Error("Timed out waiting for night shelter"),
    }))));

    expect(actionStarted).toBe(true);
    expect(failures).toHaveLength(1);
  });

  it("keeps a night shelter sealed until daylight is confirmed", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentEnvironment = { gameTime: 12_900n };
    driver.currentObservation = observation({
      counts: {
        "minecraft:wooden_sword": 1,
      },
    });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "collect-blocks") {
          driver.currentEnvironment = { gameTime: 14_000n };
        }
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" ? Effect.never : Effect.void,
        ),
      );
    const removedBlocks = new Set<string>();
    let sealPlaced = false;
    let postSealEnvironmentObservations = 0;
    driver.environmentResolver = () =>
      Effect.sync(() => {
        if (!sealPlaced) {
          return driver.currentEnvironment;
        }
        postSealEnvironmentObservations += 1;
        if (postSealEnvironmentObservations === 1) {
          return {};
        }
        if (postSealEnvironmentObservations === 2) {
          return { gameTime: 16_000n };
        }
        if (postSealEnvironmentObservations === 3) {
          return { gameTime: 23_000n };
        }
        return { gameTime: 1_000n };
      });
    const key = (x: number, y: number, z: number) => `${x}:${y}:${z}`;
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds?.includes("minecraft:water") === true) {
        return [];
      }
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      const blockKey = key(position.x, position.y, position.z);
      const isShaft = position.x === 0 && position.z === 0;
      const isSeal = isShaft && position.y === 63;
      const isShaftFloor = isShaft
        && position.y >= 61
        && position.y <= 63;
      const isSealSupport = position.x === 1
        && position.y === 63
        && position.z === 0;
      if (
        isSeal && sealPlaced
        || isSealSupport
        || isShaftFloor && !removedBlocks.has(blockKey)
      ) {
        return [blockObservation(position, {
          blockId: isSeal
            ? "minecraft:dirt"
            : "minecraft:stone",
        })];
      }
      return [blockObservation(position, {
        blockId: "minecraft:air",
        diggable: false,
        replaceable: true,
        solid: false,
      })];
    };
    driver.actionObserver = (action) => {
      if (action.type === "dig-block") {
        const collectedDirt = action.position.y === 63
          ? { "minecraft:dirt": 1 }
          : {};
        removedBlocks.add(key(
          action.position.x,
          action.position.y,
          action.position.z,
        ));
        if (
          action.position.y
            === Math.floor(driver.currentObservation.player.position.y) - 1
        ) {
          driver.currentObservation = observation({
            position: {
              ...driver.currentObservation.player.position,
              y: driver.currentObservation.player.position.y - 1,
            },
            counts: {
              ...driver.currentObservation.inventory.counts,
              ...collectedDirt,
            },
          });
        } else if (action.position.y === 63) {
          sealPlaced = false;
        }
      }
      if (action.type === "place-block") {
        sealPlaced = true;
        removedBlocks.delete(key(0, 63, 0));
      }
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (driver.paths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    const placeIndex = driver.actions.findIndex((action) =>
      action.type === "place-block"
    );
    expect(driver.tasks).toEqual(expect.arrayContaining([
      expect.objectContaining({ type: "collect-blocks" }),
    ]));
    expect(placeIndex).toBeGreaterThan(2);
    expect(driver.actions.slice(0, placeIndex)).toEqual(expect.arrayContaining([
      expect.objectContaining({
        type: "dig-block",
        position: expect.objectContaining({ y: 63 }),
      }),
      expect.objectContaining({
        type: "dig-block",
        position: expect.objectContaining({ y: 62 }),
      }),
      expect.objectContaining({
        type: "dig-block",
        position: expect.objectContaining({ y: 61 }),
      }),
    ]));
    expect(driver.actions[placeIndex]).toEqual({
      type: "place-block",
      against: {
        x: 1,
        y: 63,
        z: 0,
        dimension: "minecraft:overworld",
      },
      face: "west",
      hand: "main",
    });
    expect(driver.paths[0]).toEqual(expect.objectContaining({
      position: expect.objectContaining({
        x: 0,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      }),
      radius: 1,
    }));
    expect(postSealEnvironmentObservations).toBeGreaterThanOrEqual(5);
    expect(driver.actions.filter(({ type }) => type === "place-block"))
      .toHaveLength(1);
  }, 10_000);

  it("leaves a resumed sealed shelter after morning", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentEnvironment = { gameTime: 14_000n };
    driver.currentObservation = observation({
      position: {
        x: 0.5,
        y: 60,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      counts: {
        "minecraft:stone_pickaxe": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.surfaceColumns = [{
      x: 0,
      z: 0,
      loaded: true,
      surfaceY: 62,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    let environmentObservations = 0;
    driver.environmentResolver = () =>
      Effect.sync(() => {
        environmentObservations += 1;
        return environmentObservations === 1
          ? { gameTime: 14_000n }
          : { gameTime: 1_000n };
      });
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds?.includes("minecraft:water") === true) {
        return [];
      }
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      return [blockObservation(position, position.y === 62
        ? { blockId: "minecraft:oak_log" }
        : {
          blockId: "minecraft:air",
          diggable: false,
          replaceable: true,
          solid: false,
        })];
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (driver.paths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.paths[0]).toMatchObject({
      position: {
        x: 0.5,
        y: 63,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      policy: {
        allowMining: true,
        allowPlacing: true,
      },
    });
    expect(driver.actions).toEqual(expect.arrayContaining([
      expect.objectContaining({
        type: "select-item",
        selector: { itemIds: expect.arrayContaining([
          "minecraft:stone_pickaxe",
        ]) },
      }),
      expect.objectContaining({
        type: "dig-block",
        position: {
          x: 0,
          y: 62,
          z: 0,
          dimension: "minecraft:overworld",
        },
      }),
    ]));
  }, 10_000);

  it("moves away from a night shelter shaft that would flood", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentEnvironment = { gameTime: 14_000n };
    driver.currentObservation = observation({
      counts: {
        "minecraft:dirt": 1,
        "minecraft:wooden_sword": 1,
      },
      position: { x: 0.5, y: 64, z: 0.5 },
    });
    driver.surfaceColumns = [
      { x: 4, z: 0 },
      { x: 4, z: 1 },
      { x: 5, z: 0 },
    ].map(({ x, z }) => ({
      x,
      z,
      loaded: true,
      surfaceY: 63,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }));
    const removedBlocks = new Set<string>();
    const key = (x: number, y: number, z: number) => `${x}:${y}:${z}`;
    let sealPlaced = false;
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds?.includes("minecraft:water") === true) {
        return [];
      }
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      const blockKey = key(position.x, position.y, position.z);
      const unstableShaft = position.x === 0 && position.z === 0;
      const unstableShaftSupport = position.x === -1
        && position.y === 63
        && position.z === 0;
      const floodingShaftNeighbor = position.x === 1
        && position.y === 62
        && position.z === 0;
      const stableShaft = position.x === 4 && position.z === 0;
      const stableSeal = stableShaft && position.y === 63;
      const stableSealSupport = position.x === 5
        && position.y === 63
        && position.z === 0;
      const solidUnstableFloor = unstableShaft
        && position.y >= 61
        && position.y <= 63;
      const solidStableFloor = stableShaft
        && position.y >= 61
        && position.y <= 63
        && !removedBlocks.has(blockKey);
      if (floodingShaftNeighbor) {
        return [blockObservation(position, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
          solid: false,
        })];
      }
      if (
        stableSeal && sealPlaced
        || stableSealSupport
        || unstableShaftSupport
        || solidUnstableFloor
        || solidStableFloor
      ) {
        return [blockObservation(position, {
          blockId: stableSeal && sealPlaced
            ? "minecraft:dirt"
            : "minecraft:stone",
        })];
      }
      return [blockObservation(position, {
        blockId: "minecraft:air",
        diggable: false,
        replaceable: true,
        solid: false,
      })];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        driver.currentObservation = observation({
          counts: driver.currentObservation.inventory.counts,
          position,
        });
      });
    driver.actionObserver = (action) => {
      if (action.type === "dig-block") {
        removedBlocks.add(key(
          action.position.x,
          action.position.y,
          action.position.z,
        ));
        if (
          action.position.x === 4
          && action.position.z === 0
          && action.position.y
            === Math.floor(driver.currentObservation.player.position.y) - 1
        ) {
          driver.currentObservation = observation({
            counts: driver.currentObservation.inventory.counts,
            position: {
              ...driver.currentObservation.player.position,
              y: driver.currentObservation.player.position.y - 1,
            },
          });
        }
        if (action.position.x === 4 && action.position.y === 63) {
          sealPlaced = false;
        }
      }
      if (action.type === "place-block") {
        sealPlaced = true;
        removedBlocks.delete(key(4, 63, 0));
        driver.currentEnvironment = { gameTime: 1_000n };
      }
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        !driver.actions.some(({ type }) => type === "place-block")
        || driver.paths.length < 2
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.paths[0]).toEqual(expect.objectContaining({
      position: {
        x: 4.5,
        y: 64,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 0.25,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        avoidFluids: true,
      }),
    }));
    expect(driver.actions).not.toEqual(expect.arrayContaining([
      expect.objectContaining({
        type: "dig-block",
        position: expect.objectContaining({ x: 0, z: 0 }),
      }),
    ]));
    expect(driver.actions).toEqual(expect.arrayContaining([
      expect.objectContaining({
        type: "dig-block",
        position: expect.objectContaining({ x: 4, y: 63, z: 0 }),
      }),
      expect.objectContaining({
        type: "dig-block",
        position: expect.objectContaining({ x: 4, y: 62, z: 0 }),
      }),
      expect.objectContaining({
        type: "dig-block",
        position: expect.objectContaining({ x: 4, y: 61, z: 0 }),
      }),
    ]));
  }, 10_000);

  it("interrupts night shelter relocation to defend against a hostile", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentEnvironment = { gameTime: 14_000n };
    driver.currentObservation = observation({
      counts: {
        "minecraft:dirt": 8,
        "minecraft:wooden_sword": 1,
      },
      position: { x: 0.5, y: 64, z: 0.5 },
    });
    driver.surfaceColumns = [-1, 0, 1].flatMap((deltaX) =>
      [-1, 0, 1].map((deltaZ) => ({
        x: 4 + deltaX,
        z: deltaZ,
        loaded: true,
        surfaceY: 63,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      }))
    );
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds?.includes("minecraft:water") === true) {
        return [];
      }
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      const stableGround = position.x >= 3
        && position.x <= 5
        && position.z >= -1
        && position.z <= 1
        && position.y <= 63;
      return [blockObservation(position, stableGround
        ? { blockId: "minecraft:stone" }
        : {
          blockId: "minecraft:air",
          diggable: false,
          replaceable: true,
          solid: false,
        })];
    };
    const zombie = {
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const satisfies BeatGameEntityObservation;
    driver.entityQueryResolver = (query) =>
      driver.paths.length > 0 && query.selector.categories?.includes(2)
        ? [zombie]
        : [];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" || task.type === "flee"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        !driver.tasks.some(({ type }) =>
          type === "attack-entity" || type === "flee"
        )
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.paths[0]).toEqual(expect.objectContaining({
      radius: 0.25,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        avoidFluids: true,
      }),
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: zombie.networkId }),
    }));
  }, 10_000);

  it("creates distance from visible hostiles before sheltering", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentEnvironment = { gameTime: 14_000n };
    driver.currentObservation = observation({
      counts: { "minecraft:dirt": 1 },
      health: 4,
      food: 8,
      onGround: false,
    });
    driver.entityResults = [{
      connectionEpoch: "epoch",
      networkId: 42,
      entityType: "minecraft:zombie",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-08-03T10:00:00.000Z",
    }];
    driver.blockQueryResolver = ({ center, selector }) =>
      selector.blockIds?.includes("minecraft:water") === true
        ? []
        : [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        }, {
          blockId: "minecraft:air",
          diggable: false,
          replaceable: true,
          solid: false,
        })];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some(({ type }) => type === "flee")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.tasks[0]).toMatchObject({
      type: "flee",
      selector: {
        categories: [2],
        alive: true,
        requireLineOfSight: true,
      },
      triggerRadius: 24,
      safeDistance: 32,
      completeWhenSafe: true,
    });
    expect(driver.tasks).not.toEqual(expect.arrayContaining([
      expect.objectContaining({ type: "collect-blocks" }),
    ]));
  }, 10_000);

  it("eats available food before building a night shelter", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentEnvironment = { gameTime: 14_000n };
    driver.currentObservation = observation({
      counts: {
        "minecraft:salmon": 8,
        "minecraft:wooden_sword": 1,
      },
      food: 13,
    });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some(({ type }) => type === "auto-eat")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "auto-eat",
      foodItemIds: ["minecraft:salmon"],
      foodLevel: 20,
      maximumMeals: 1,
      completeWhenNoFood: true,
    }));
    expect(driver.paths).toHaveLength(0);
  }, 10_000);

  it("eats toward regeneration before sheltering while wounded", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentEnvironment = { gameTime: 14_000n };
    driver.currentObservation = observation({
      counts: {
        "minecraft:salmon": 7,
        "minecraft:wooden_sword": 1,
      },
      food: 16,
      health: 10,
    });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some(({ type }) => type === "auto-eat")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "auto-eat",
      foodItemIds: ["minecraft:salmon"],
      foodLevel: 20,
      maximumMeals: 1,
      completeWhenNoFood: true,
    }));
    expect(driver.paths).toHaveLength(0);
  }, 10_000);

  it("rechecks wounded hunger while waiting in a shelter", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentEnvironment = { gameTime: 14_000n };
    driver.currentObservation = observation({
      counts: {
        "minecraft:salmon": 2,
        "minecraft:wooden_sword": 1,
      },
      food: 17,
      health: 10,
    });
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds?.includes("minecraft:water") === true) {
        return [];
      }
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      return [blockObservation(position, position.y === 66
        ? { blockId: "minecraft:stone" }
        : {
          blockId: "minecraft:air",
          diggable: false,
          replaceable: true,
          solid: false,
        })];
    };
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "auto-eat"
              && driver.tasks.filter(({ type }) => type === "auto-eat")
                  .length >= 2
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        driver.tasks.filter(({ type }) => type === "auto-eat").length < 2
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.tasks.filter(({ type }) => type === "auto-eat"))
      .toHaveLength(2);
    expect(driver.tasks.filter(({ type }) => type === "auto-eat"))
      .toEqual(expect.arrayContaining([
        expect.objectContaining({ maximumMeals: 1 }),
      ]));
  }, 10_000);

  it("accepts any dry landing while swimming toward a night shelter", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentEnvironment = { gameTime: 14_000n };
    driver.currentObservation = observation({
      counts: {
        "minecraft:dirt": 1,
        "minecraft:wooden_sword": 1,
      },
      onGround: false,
      position: { x: 0.5, y: 62, z: 0.5 },
    });
    driver.surfaceColumns = [4, -4].flatMap((centerX) =>
      [-1, 0, 1].flatMap((deltaX) =>
        [-1, 0, 1].map((deltaZ) => ({
          x: centerX + deltaX,
          z: deltaZ,
          loaded: true,
          surfaceY: 63,
          blockId: "minecraft:grass_block",
          biomeId: "minecraft:plains",
          skyLight: 15,
          blockLight: 0,
        }))
      )
    );
    driver.blockQueryResolver = ({ center, selector }) => {
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      if (selector.blockIds?.includes("minecraft:water") === true) {
        return position.x === 0
          ? [blockObservation(position, {
            blockId: "minecraft:water",
            diggable: false,
            replaceable: true,
            solid: false,
          })]
          : [];
      }
      if (
        position.y === 63
        && (
          position.x >= 3 && position.x <= 5
          || position.x >= -5 && position.x <= -3
        )
        && position.z >= -1
        && position.z <= 1
      ) {
        return [blockObservation(position, {
          blockId: "minecraft:grass_block",
        })];
      }
      return [blockObservation(position, {
        blockId: "minecraft:air",
        diggable: false,
        replaceable: true,
        solid: false,
      })];
    };
    driver.actionObserver = (action) => {
      if (action.type === "set-movement") {
        driver.currentObservation = observation({
          counts: driver.currentObservation.inventory.counts,
          position: { x: 8.5, y: 64, z: 0.5 },
        });
      }
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.actions.some(({ type }) => type === "reset-movement")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    const shorePaths = driver.paths.filter(({ policy }) =>
      policy.avoidFluids === false
    );
    expect(shorePaths).toHaveLength(1);
    expect(driver.currentObservation.player.position).toMatchObject({
      x: 8.5,
      y: 64,
      z: 0.5,
    });
  }, 10_000);

  it("routes from water to dry ground before digging a night shelter", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentEnvironment = { gameTime: 14_000n };
    driver.currentObservation = observation({
      counts: {
        "minecraft:dirt": 1,
        "minecraft:wooden_sword": 1,
      },
      onGround: false,
      position: { x: 0.5, y: 62, z: 0.5 },
    });
    driver.surfaceColumns = [-1, 0, 1].flatMap((deltaX) =>
      [-1, 0, 1].map((deltaZ) => ({
        x: 4 + deltaX,
        z: deltaZ,
        loaded: true,
        surfaceY: 63,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      }))
    );
    driver.blockQueryResolver = ({ center, selector }) => {
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      if (selector.blockIds?.includes("minecraft:water") === true) {
        return position.x === 0 && position.z === 0
          ? [blockObservation(position, {
            blockId: "minecraft:water",
            diggable: false,
            replaceable: true,
            solid: false,
          })]
          : [];
      }
      if (
        position.x >= 3
        && position.x <= 5
        && position.z >= -1
        && position.z <= 1
        && position.y === 63
      ) {
        return [blockObservation(position, {
          blockId: "minecraft:grass_block",
        })];
      }
      return [blockObservation(position, {
        blockId: "minecraft:air",
        diggable: false,
        replaceable: true,
        solid: false,
      })];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (driver.paths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.paths[0]).toEqual(expect.objectContaining({
      position: expect.objectContaining({
        y: 64,
        dimension: "minecraft:overworld",
      }),
      radius: 0.75,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        avoidFluids: false,
      }),
    }));
  }, 10_000);

  it("recovers to the water surface when no dry shelter ground is loaded", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentEnvironment = { gameTime: 14_000n };
    driver.currentObservation = observation({
      counts: { "minecraft:wooden_sword": 1 },
      onGround: false,
      position: { x: 0.5, y: 52, z: 0.5 },
    });
    driver.surfaceColumns = [-1, 0, 1].flatMap((x) =>
      [-1, 0, 1].map((z) => ({
        x,
        z,
        loaded: true,
        surfaceY: 63,
        blockId: "minecraft:water",
        biomeId: "minecraft:ocean",
        skyLight: 15,
        blockLight: 0,
      }))
    );
    driver.blockQueryResolver = ({ center, selector }) => {
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      return selector.blockIds?.includes("minecraft:water") === true
        ? [blockObservation(position, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
          solid: false,
        })]
        : [blockObservation(position, {
          blockId: "minecraft:air",
          diggable: false,
          replaceable: true,
          solid: false,
        })];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (driver.paths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.paths[0]).toEqual(expect.objectContaining({
      position: expect.objectContaining({
        y: 64,
        dimension: "minecraft:overworld",
      }),
      radius: 1.5,
      policy: expect.objectContaining({
        allowMining: true,
        allowPlacing: true,
        avoidFluids: false,
      }),
    }));
  }, 10_000);

  it("adopts a durable checkpoint on a replacement SoulFire instance", async () => {
    const driver = new FakeBeatGameDriver("replacement-instance", "bot-1");
    const store = new InMemoryBeatGameCheckpointStore();
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.COMPLETE,
      {
        runId: "replacement-run",
        teamId: "replacement-team",
        instanceId: "previous-instance",
      },
    ), undefined));

    const result = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "replacement-run",
        team: { teamId: "replacement-team" },
        checkpointStore: store,
      }).pipe(Effect.flatMap(({ awaitCompletion }) => awaitCompletion)),
    ));

    expect(result.finalCheckpoint).toMatchObject({
      instanceId: "replacement-instance",
      botId: "bot-1",
      teamId: "replacement-team",
      planner: { status: BeatGameRunStatus.COMPLETED },
    });
    expect(result.finalCheckpoint.revision).toBeGreaterThan(1);
  });

  it("shelters before resuming a stale corpse recovery at night", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const observedAt = new Date(Date.now() - 15 * 60 * 1_000).toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "night-recovery-run",
      teamId: "night-recovery-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            x: 128,
            y: -24,
            z: -64,
            dimension: "minecraft:overworld",
            inventoryCounts: { "minecraft:iron_pickaxe": 1 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentEnvironment = { gameTime: 16_000n };
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds?.includes("minecraft:water") === true) {
        return [];
      }
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      return [blockObservation(position, position.y === 66
        ? {
          blockId: "minecraft:air",
          diggable: false,
          replaceable: true,
          solid: false,
        }
        : { blockId: "minecraft:stone" })];
    };
    let recoveryAttempts = 0;

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "night-recovery-run",
        team: { teamId: "night-recovery-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
        hooks: {
          recoverDeath: () =>
            Effect.sync(() => {
              recoveryAttempts += 1;
            }).pipe(Effect.zipRight(Effect.never)),
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              recoveryAttempts === 0
              && !driver.actions.some((action) =>
                action.type === "dig-block"
              )
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(recoveryAttempts).toBe(0);
    expect(driver.actions).toContainEqual(expect.objectContaining({
      type: "dig-block",
      position: expect.objectContaining({ y: 63 }),
    }));
  });

  it("recovers visible valuable corpse drops before sheltering", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const observedAt = new Date(Date.now() - 15 * 60 * 1_000).toISOString();
    const deathPosition = {
      x: 24,
      y: 64,
      z: -12,
      dimension: "minecraft:overworld",
    };
    const runId = "visible-night-recovery-run";
    const teamId = "visible-night-recovery-team";
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, { runId, teamId });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_pickaxe": 1 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentEnvironment = { gameTime: 16_000n };
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(6)
        ? [{
          connectionEpoch: "epoch-1",
          networkId: 91,
          entityType: "minecraft:item",
          itemId: "minecraft:iron_pickaxe",
          position: deathPosition,
          velocity: { x: 0, y: 0, z: 0 },
          alive: true,
          health: 5,
          observedAt: new Date().toISOString(),
        }]
        : [];
    let recoveryAttempts = 0;

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId,
        team: { teamId },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
        hooks: {
          recoverDeath: () =>
            Effect.sync(() => {
              recoveryAttempts += 1;
            }).pipe(Effect.zipRight(Effect.never)),
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (recoveryAttempts === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(recoveryAttempts).toBe(1);
    expect(driver.actions.some((action) => action.type === "dig-block"))
      .toBe(false);
  });

  it("prioritizes a fresh corpse over night shelter", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "fresh-night-recovery-run",
      teamId: "fresh-night-recovery-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            x: 24,
            y: 64,
            z: -12,
            dimension: "minecraft:overworld",
            inventoryCounts: { "minecraft:iron_pickaxe": 1 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentEnvironment = { gameTime: 16_000n };
    let recoveryAttempts = 0;

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "fresh-night-recovery-run",
        team: { teamId: "fresh-night-recovery-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
        hooks: {
          recoverDeath: () =>
            Effect.sync(() => {
              recoveryAttempts += 1;
            }).pipe(Effect.zipRight(Effect.never)),
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (recoveryAttempts === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(recoveryAttempts).toBe(1);
    expect(driver.actions.some((action) => action.type === "dig-block"))
      .toBe(false);
  });

  it("restores an unloaded pending corpse despite partial replacement inventory", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 48,
      y: 64,
      z: -12,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date(Date.now() - 3 * 60 * 1_000).toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "durable-death-run",
      teamId: "durable-death-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:cobblestone": 17,
              "minecraft:oak_log": 9,
              "minecraft:wooden_pickaxe": 1,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: {
        "minecraft:cooked_beef": 8,
        "minecraft:oak_log": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 11,
      entityType: "minecraft:polar_bear",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 30,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:polar_bear")
        ? driver.entityResults
        : [];
    const resolvePath = driver.pathResolver;
    driver.pathResolver = (position, radius, policy) =>
      resolvePath(position, radius, policy).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            if (
              position.x === deathPosition.x
              && position.y === deathPosition.y
              && position.z === deathPosition.z
              && position.dimension === deathPosition.dimension
            ) {
              driver.currentObservation = observation({
                position: deathPosition,
                counts: { "minecraft:stone_pickaxe": 1 },
              });
            }
          })
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "durable-death-run",
        team: { teamId: "durable-death-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((event) => event.type === "items-recovered"),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 2,
    }));
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  });

  it("restores a known durable corpse when SoulFire starts on the death screen", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 4,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date(Date.now() - 60_000).toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "death-screen-durable-run",
      teamId: "death-screen-durable-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:stone_pickaxe": 1,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      dead: true,
      health: 0,
      position: {
        x: 32,
        y: 64,
        z: 32,
        dimension: "minecraft:overworld",
      },
    });
    let recoveryPosition:
      | BeatGameEntityObservation["position"]
      | undefined;

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "death-screen-durable-run",
        team: { teamId: "death-screen-durable-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
        hooks: {
          recoverDeath: ({ observation: recoveryObservation }) =>
            Effect.sync(() => {
              recoveryPosition = recoveryObservation.player.position;
              driver.currentObservation = observation({
                position: deathPosition,
                counts: { "minecraft:stone_pickaxe": 1 },
              });
            }),
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((event) =>
                event.type === "items-recovered"
                && event.detail === "Death recovery completed"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(recoveryPosition).toEqual(deathPosition);
  });

  it("increases the respawn delay after repeated corpse-recovery deaths", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const firstObservedAt = new Date(Date.now() - 120_000).toISOString();
    const secondObservedAt = new Date(Date.now() - 60_000).toISOString();
    const thirdObservedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "chained-death-cooldown-run",
      teamId: "chained-death-cooldown-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [
          {
            key: `death:${firstObservedAt}`,
            value: {
              x: 80,
              y: 64,
              z: 0,
              dimension: "minecraft:overworld",
              inventoryCounts: { "minecraft:iron_ingot": 7 },
            },
            observedAt: firstObservedAt,
            confidence: 1,
          },
          {
            key: `death:${secondObservedAt}`,
            value: {
              x: 4,
              y: 64,
              z: 0,
              dimension: "minecraft:overworld",
              inventoryCounts: { "minecraft:oak_log": 4 },
            },
            observedAt: secondObservedAt,
            confidence: 1,
          },
          {
            key: `death:${thirdObservedAt}`,
            value: {
              x: 8,
              y: 64,
              z: 0,
              dimension: "minecraft:overworld",
              inventoryCounts: { "minecraft:rotten_flesh": 1 },
            },
            observedAt: thirdObservedAt,
            confidence: 1,
          },
        ],
      },
    }, undefined));
    driver.currentObservation = observation({
      dead: true,
      health: 0,
      food: 5,
    });

    const [diagnostic, interruptedDuringCooldown] = await Effect.runPromise(Effect.scoped(
      Effect.gen(function* () {
        const run = yield* beatGameWithDriver(driver, {
          runId: "chained-death-cooldown-run",
          team: { teamId: "chained-death-cooldown-team" },
          checkpointStore: store,
          strategy: { observationPollMs: 1 },
        });
        const event = yield* run.events.pipe(
          Stream.filter((candidate) =>
            candidate.type === "diagnostic"
            && candidate.message
              === "Delaying respawn after a chained corpse-recovery death"
          ),
          Stream.runHead,
          Effect.timeout("5 seconds"),
        );
        const interrupted = yield* Effect.race(
          run.events.pipe(
            Stream.filter((candidate) =>
              candidate.type === "action-failed"
              && candidate.detail?.includes(
                "hunger became urgent without available food",
              ) === true
            ),
            Stream.runHead,
            Effect.as(true),
          ),
          Effect.sleep(25).pipe(Effect.as(false)),
        );
        yield* run.stop;
        yield* run.awaitCompletion.pipe(Effect.either);
        return [event, interrupted] as const;
      }),
    ));

    expect(Option.getOrUndefined(diagnostic)).toMatchObject({
      type: "diagnostic",
      data: {
        cooldownMs: 120_000,
        pendingDeaths: 3,
      },
    });
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "auto-respawn",
    }));
    expect(interruptedDuringCooldown).toBe(false);
  });

  it("does not delay respawn for chained trivial corpses", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const firstObservedAt = new Date(Date.now() - 60_000).toISOString();
    const secondObservedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "trivial-chained-death-run",
      teamId: "trivial-chained-death-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [
          {
            key: `death:${firstObservedAt}`,
            value: {
              x: 40,
              y: 64,
              z: 0,
              dimension: "minecraft:overworld",
              inventoryCounts: { "minecraft:bone": 1 },
            },
            observedAt: firstObservedAt,
            confidence: 1,
          },
          {
            key: `death:${secondObservedAt}`,
            value: {
              x: 48,
              y: 64,
              z: 0,
              dimension: "minecraft:overworld",
              inventoryCounts: { "minecraft:sand": 4 },
            },
            observedAt: secondObservedAt,
            confidence: 1,
          },
        ],
      },
    }, undefined));
    driver.currentObservation = observation({ dead: true, health: 0 });
    driver.taskObserver = (task) => {
      if (task.type === "auto-respawn") {
        driver.currentObservation = observation();
      }
    };

    const respawnStarted = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "trivial-chained-death-run",
        team: { teamId: "trivial-chained-death-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            const started = yield* Effect.race(
              Effect.gen(function* () {
                while (!driver.tasks.some((task) =>
                  task.type === "auto-respawn"
                )) {
                  yield* Effect.sleep(1);
                }
                return true;
              }),
              Effect.sleep(250).pipe(Effect.as(false)),
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
            return started;
          })
        ),
      ),
    ));

    expect(respawnStarted).toBe(true);
  });

  it("preserves meaningful inventory when death packets clear it first", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 32,
      y: 48,
      z: -16,
      dimension: "minecraft:overworld",
    };
    const deathObservedAt = new Date().toISOString();
    driver.currentObservation = observation({
      observedAt: deathObservedAt,
      counts: {
        "minecraft:iron_ingot": 10,
        "minecraft:stone_sword": 1,
        "minecraft:cooked_beef": 4,
      },
    });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      Effect.gen(function* () {
        const driverEvents = yield* PubSub.unbounded<BeatGameDriverEvent>();
        driver.events = Stream.fromPubSub(driverEvents);
        const run = yield* beatGameWithDriver(driver, {
          runId: "death-inventory-transition-run",
          team: { teamId: "death-inventory-transition-team" },
          checkpointStore: store,
          strategy: { observationPollMs: 1 },
        });
        while (driver.tasks.length === 0) {
          yield* Effect.sleep(1);
        }
        driver.currentObservation = observation({
          observedAt: deathObservedAt,
          position: deathPosition,
          counts: {},
        });
        yield* Effect.sleep(10);
        driver.currentObservation = observation({
          observedAt: deathObservedAt,
          position: deathPosition,
          counts: {},
          dead: true,
          health: 0,
        });
        yield* PubSub.publish(driverEvents, {
          type: "bot-died",
          observedAt: deathObservedAt,
          message: "Bot was slain",
        });
        yield* Effect.gen(function* () {
          while (
            (yield* store.load("death-inventory-transition-run"))
                ?.memory.deathPositions.length !== 1
          ) {
            yield* Effect.sleep(1);
          }
        }).pipe(Effect.timeout("5 seconds"));
        yield* run.stop;
        yield* run.awaitCompletion.pipe(Effect.either);
      }),
    ));

    const saved = await Effect.runPromise(
      store.load("death-inventory-transition-run"),
    );
    expect(saved?.memory.deathPositions).toContainEqual(expect.objectContaining({
      value: expect.objectContaining({
        ...deathPosition,
        inventoryCounts: {
          "minecraft:iron_ingot": 10,
          "minecraft:stone_sword": 1,
          "minecraft:cooked_beef": 4,
        },
      }),
    }));
  });

  it("does not copy a previous corpse inventory into a later death", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    let observationCount = 0;
    driver.observationResolver = () =>
      Effect.sync(() => {
        observationCount += 1;
        return driver.currentObservation;
      });
    const firstDeathPosition = {
      x: 32,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const secondDeathPosition = {
      x: -48,
      y: 64,
      z: 16,
      dimension: "minecraft:overworld",
    };
    const firstDeathObservedAt = new Date().toISOString();
    const secondDeathObservedAt = new Date(Date.now() + 1_000).toISOString();
    driver.currentObservation = observation({
      counts: {
        "minecraft:oak_log": 12,
        "minecraft:wooden_sword": 1,
      },
    });

    await Effect.runPromise(Effect.scoped(
      Effect.gen(function* () {
        const driverEvents = yield* PubSub.unbounded<BeatGameDriverEvent>();
        driver.events = Stream.fromPubSub(driverEvents);
        const run = yield* beatGameWithDriver(driver, {
          runId: "consecutive-death-inventory-run",
          team: { teamId: "consecutive-death-inventory-team" },
          checkpointStore: store,
          strategy: { observationPollMs: 1 },
        });
        yield* Effect.sleep(20);

        driver.currentObservation = observation({
          observedAt: firstDeathObservedAt,
          position: firstDeathPosition,
          counts: {},
          dead: true,
          health: 0,
        });
        yield* PubSub.publish(driverEvents, {
          type: "bot-died",
          observedAt: firstDeathObservedAt,
        });
        while (
          (yield* store.load("consecutive-death-inventory-run"))
              ?.memory.deathPositions.length !== 1
        ) {
          yield* Effect.sleep(1);
        }

        driver.currentObservation = observation({ counts: {} });
        const observationsBeforeRespawn = observationCount;
        while (observationCount === observationsBeforeRespawn) {
          yield* Effect.sleep(1);
        }
        driver.currentObservation = observation({
          observedAt: secondDeathObservedAt,
          position: secondDeathPosition,
          counts: {},
          dead: true,
          health: 0,
        });
        yield* PubSub.publish(driverEvents, {
          type: "bot-died",
          observedAt: secondDeathObservedAt,
        });
        yield* Effect.gen(function* () {
          while (
            (yield* store.load("consecutive-death-inventory-run"))
                ?.memory.deathPositions.length !== 2
          ) {
            yield* Effect.sleep(1);
          }
        }).pipe(Effect.timeout("5 seconds"));
        yield* run.stop;
        yield* run.awaitCompletion.pipe(Effect.either);
      }),
    ));

    const saved = await Effect.runPromise(
      store.load("consecutive-death-inventory-run"),
    );
    expect(saved?.memory.deathPositions).toContainEqual(expect.objectContaining({
      value: expect.objectContaining({
        ...secondDeathPosition,
        inventoryCounts: {},
      }),
    }));
  });

  it("heals before scouting a restored corpse", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 48,
      y: 64,
      z: -24,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date(Date.now() - 15 * 60 * 1_000).toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "safe-durable-death-run",
      teamId: "safe-durable-death-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:iron_pickaxe": 1,
              "minecraft:cobblestone": 32,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      health: 1.5,
      food: 17,
      counts: {
        "minecraft:beef": 4,
        "minecraft:dirt": 16,
        "minecraft:wooden_sword": 1,
      },
    });
    const timeline: string[] = [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        timeline.push(task.type);
        if (task.type === "auto-eat") {
          driver.currentObservation = observation({
            health: 18,
            food: 20,
            counts: {
              "minecraft:beef": 3,
              "minecraft:dirt": 16,
              "minecraft:wooden_sword": 1,
            },
          });
        }
      });
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        timeline.push("corpse-path");
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "safe-durable-death-run",
        team: { teamId: "safe-durable-death-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            let attempts = 2_000;
            while (
              driver.paths.length === 0
              && attempts > 0
            ) {
              attempts -= 1;
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 24,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        avoidFluids: true,
      }),
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "auto-eat",
      foodLevel: 20,
      maximumMeals: 1,
    }));
    expect(timeline.indexOf("auto-eat")).toBeLessThan(
      timeline.indexOf("corpse-path"),
    );
  });

  it("interrupts corpse travel after unexplained environmental damage", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 48,
      y: 32,
      z: -24,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date(Date.now() - 15 * 60 * 1_000).toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "environmental-damage-recovery-run",
      teamId: "environmental-damage-recovery-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:iron_pickaxe": 1,
              "minecraft:cobblestone": 32,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    const replacementInventory = {
      "minecraft:cooked_beef": 4,
      "minecraft:dirt": 16,
      "minecraft:wooden_pickaxe": 1,
      "minecraft:wooden_sword": 1,
    };
    driver.currentObservation = observation({
      health: 20,
      food: 20,
      counts: replacementInventory,
    });
    let corpsePathInterrupted = false;
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.zipRight(Effect.never),
        Effect.onInterrupt(() =>
          Effect.sync(() => {
            corpsePathInterrupted = true;
          })
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "environmental-damage-recovery-run",
        team: { teamId: "environmental-damage-recovery-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.paths.length === 0) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({
              health: 16,
              food: 20,
              counts: replacementInventory,
            });
            let attempts = 2_000;
            while (!corpsePathInterrupted && attempts > 0) {
              attempts -= 1;
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(corpsePathInterrupted).toBe(true);
  });

  it("digs out when repeated environmental damage has no attacker", async () => {
    const driver = new FakeBeatGameDriver();
    const counts = { "minecraft:wooden_pickaxe": 1 };
    const headPosition = {
      x: 0,
      y: 65,
      z: 0,
      dimension: "minecraft:overworld",
    };
    let actionStarted = false;
    let obstructed = true;
    let health = 20;
    driver.currentObservation = observation({ counts, health });
    driver.observationResolver = () =>
      Effect.sync(() => {
        if (actionStarted && obstructed) {
          health = Math.max(0, health - 1);
        }
        driver.currentObservation = observation({ counts, health });
        return driver.currentObservation;
      });
    driver.blockQueryResolver = (query) =>
      obstructed
          && query.center.x === 0.5
          && query.center.y === 65.5
          && query.center.z === 0.5
        ? [blockObservation(headPosition, {
          blockId: "minecraft:gravel",
        })]
        : [];
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        if (
          action.type === "dig-block"
          && action.position.x === headPosition.x
          && action.position.y === headPosition.y
          && action.position.z === headPosition.z
        ) {
          obstructed = false;
        }
        return {};
      });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
        hooks: {
          satisfyRequirement: () =>
            Effect.sync(() => {
              actionStarted = true;
            }).pipe(Effect.zipRight(Effect.never)),
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.actions.some((action) =>
              action.type === "dig-block"
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          }).pipe(Effect.timeoutFail({
            duration: "2 seconds",
            onTimeout: () =>
              new Error("Timed out waiting for the environmental escape"),
          }))
        ),
      ),
    ));

    expect(driver.actions).toContainEqual({
      type: "dig-block",
      position: headPosition,
    });
    expect(health).toBeGreaterThan(0);
  });

  it("does not restart an in-progress corpse recovery meal", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 96,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const runId = "single-corpse-meal-run";
    const teamId = "single-corpse-meal-team";
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId,
      teamId,
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:stone_sword": 1 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      health: 14,
      food: 6,
      counts: {
        "minecraft:cod": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      return task.type === "auto-eat" ? Effect.never : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId,
        team: { teamId },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "auto-eat")) {
        yield* Effect.sleep(1);
      }
      yield* Effect.sleep(250);
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.tasks.filter((task) => task.type === "auto-eat"))
      .toHaveLength(1);
  });

  it("preserves newly gathered food until the corpse travel reserve is ready", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const runId = "corpse-food-reserve-run";
    const teamId = "corpse-food-reserve-team";
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId,
      teamId,
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_pickaxe": 1 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    const recoveryCounts = {
      "minecraft:dirt": 16,
      "minecraft:oak_log": 12,
      "minecraft:wooden_pickaxe": 1,
      "minecraft:wooden_sword": 1,
    };
    driver.currentObservation = observation({
      health: 14,
      food: 11,
      counts: recoveryCounts,
    });
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 301,
      entityType: "minecraft:salmon",
      position: {
        x: 3,
        y: 62,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    let salmonAvailable = true;
    driver.entityQueryResolver = (query) =>
      salmonAvailable
          && query.selector.entityTypes?.includes("minecraft:salmon") === true
        ? [salmon]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          salmonAvailable = false;
          driver.currentObservation = observation({
            health: 14,
            food: 11,
            counts: {
              ...recoveryCounts,
              "minecraft:salmon": 1,
            },
          });
        }
      });
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId,
        team: { teamId },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.gen(function* () {
        while (driver.xzPaths.length === 0) {
          yield* Effect.sleep(1);
        }
      }).pipe(Effect.timeout("5 seconds"));
      yield* Effect.sleep(20);
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.currentObservation.inventory.counts["minecraft:salmon"])
      .toBe(1);
    expect(driver.tasks.some((task) => task.type === "auto-eat"))
      .toBe(false);
  });

  it("recovers a lifecycle death even after an immediate respawn", async () => {
    const driver = new FakeBeatGameDriver();
    const deathObservedAt = new Date().toISOString();
    const deathPosition = {
      x: 24,
      y: 64,
      z: -12,
      dimension: "minecraft:the_end",
    };
    driver.currentObservation = observation({
      dimension: "minecraft:the_end",
      position: deathPosition,
      counts: {
        "minecraft:cooked_beef": 16,
        "minecraft:bow": 1,
        "minecraft:arrow": 32,
      },
    });
    driver.events = Stream.make({
      type: "bot-died",
      observedAt: deathObservedAt,
      message: "Bot was shot by Skeleton",
    } as const);
    const store = new InMemoryBeatGameCheckpointStore();
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.FIGHT_ENDER_DRAGON,
      {
        runId: "lifecycle-death-run",
        teamId: "lifecycle-death-team",
      },
    ), undefined));
    let recoveries = 0;
    let recoveredPosition: typeof deathPosition | undefined;

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "lifecycle-death-run",
        team: { teamId: "lifecycle-death-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
        hooks: {
          recoverDeath: ({ observation: current }) =>
            Effect.sync(() => {
              recoveries += 1;
              recoveredPosition = current.player.position;
            }),
          fightEnderDragon: () => Effect.never,
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (recoveries === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(recoveries).toBe(1);
    expect(recoveredPosition).toEqual(deathPosition);
  });

  it("fights a ranged corpse-route blocker while healthy and barehanded", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 48,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "naked-recovery-run",
      teamId: "naked-recovery-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:iron_pickaxe": 1,
              "minecraft:stone_sword": 1,
              "minecraft:water_bucket": 1,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      position: {
        x: 0,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 17,
      entityType: "minecraft:skeleton",
      position: {
        x: 4,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "naked-recovery-run",
        team: { teamId: "naked-recovery-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) =>
              task.type === "attack-entity"
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: 17 }),
      selectBestWeapon: true,
    }));
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  });

  it("fights a ranged attacker while recovering a corpse with a weapon", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 48,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "wounded-recovery-run",
      teamId: "wounded-recovery-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:iron_pickaxe": 1,
              "minecraft:stone_sword": 1,
              "minecraft:water_bucket": 1,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      health: 14,
      counts: { "minecraft:wooden_sword": 1 },
    });
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 18,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        driver.taskObserver(task);
        if (task.type === "attack-entity") {
          driver.entityResults = [];
        }
      }).pipe(
        Effect.zipRight(Effect.void),
      );
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "wounded-recovery-run",
        team: { teamId: "wounded-recovery-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* Effect.gen(function* () {
              while (
                !driver.tasks.some((task) => task.type === "attack-entity")
              ) {
                yield* Effect.sleep(1);
              }
            }).pipe(Effect.timeout("5 seconds"));
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        entityType: "minecraft:skeleton",
      }),
      selectBestWeapon: true,
    }));
    expect(driver.actions.some((action) =>
      action.type === "set-movement" && action.sprint === true
    )).toBe(false);
  });

  it("eats before a long corpse route when hunger would disable sprinting", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 96,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "fed-recovery-run",
      teamId: "fed-recovery-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:iron_pickaxe": 1,
              "minecraft:stone_sword": 1,
              "minecraft:water_bucket": 1,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      food: 14,
      counts: {
        "minecraft:mutton": 8,
        "minecraft:wooden_sword": 1,
      },
    });
    const timeline: string[] = [];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        timeline.push("path");
      }).pipe(Effect.zipRight(Effect.never));
    driver.taskObserver = (task) => {
      timeline.push(task.type);
      if (task.type === "auto-eat") {
        driver.currentObservation = observation({
          food: 16,
          counts: {
            "minecraft:mutton": 7,
            "minecraft:wooden_sword": 1,
          },
        });
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "fed-recovery-run",
        team: { teamId: "fed-recovery-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            let attempts = 1_000;
            while (
              (
                !driver.tasks.some((task) => task.type === "auto-eat")
                || driver.paths.length === 0
              )
              && attempts > 0
            ) {
              attempts -= 1;
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 2,
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "auto-eat",
      foodItemIds: ["minecraft:mutton"],
      maximumMeals: 1,
      completeWhenNoFood: true,
    }));
    expect(timeline.indexOf("auto-eat")).toBeLessThan(
      timeline.indexOf("path"),
    );
  });

  it("interrupts corpse travel to hunt when hunger becomes critical", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 96,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "critical-corpse-hunger-run",
      teamId: "critical-corpse-hunger-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_pickaxe": 1 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    const chicken = {
      connectionEpoch: "epoch-1",
      networkId: 52,
      entityType: "minecraft:chicken",
      position: {
        x: 3,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 4,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({ food: 7 });
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:chicken") === true
        ? [chicken]
        : [];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        driver.currentObservation = observation({ food: 6 });
      }).pipe(Effect.zipRight(Effect.never));
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "critical-corpse-hunger-run",
        team: { teamId: "critical-corpse-hunger-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* Effect.gen(function* () {
              while (!driver.tasks.some((task) =>
                task.type === "attack-entity"
              )) {
                yield* Effect.sleep(1);
              }
            }).pipe(Effect.timeout("2 seconds"));
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 2,
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: chicken.networkId }),
    }));
  });

  it("does not risk returning to a corpse for disposable blocks", async () => {
    const driver = new FakeBeatGameDriver();
    const deathObservedAt = new Date().toISOString();
    const deathPosition = {
      x: 24,
      y: 64,
      z: -12,
      dimension: "minecraft:overworld",
    };
    driver.currentObservation = observation({
      position: deathPosition,
      counts: { "minecraft:dirt": 18 },
    });
    driver.events = Stream.make({
      type: "bot-died",
      observedAt: deathObservedAt,
      message: "Bot drowned",
    } as const);

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((event) => event.type === "items-recovered"),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
  });

  it("skips a stored corpse containing only trivial mob drops", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 24,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "trivial-corpse-run",
      teamId: "trivial-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:arrow": 1,
              "minecraft:bone": 1,
              "minecraft:ink_sac": 2,
              "minecraft:sand": 4,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "trivial-corpse-run",
        team: { teamId: "trivial-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((candidate) =>
                candidate.type === "action-succeeded"
                && candidate.action === "recover-death"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
    expect(driver.entityQueries.some((query) =>
      query.selector.categories?.includes(6)
    )).toBe(false);
    const saved = await Effect.runPromise(store.load("trivial-corpse-run"));
    expect(saved?.memory.deathPositions).toEqual([]);
  });

  it("abandons a distant renewable corpse and clears its checkpoint", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "renewable-corpse-run",
      teamId: "renewable-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:egg": 3,
              "minecraft:feather": 3,
              "minecraft:beetroot_seeds": 1,
              "minecraft:melon_seeds": 1,
              "minecraft:oak_log": 1,
              "minecraft:oak_sapling": 1,
              "minecraft:pitcher_pod": 1,
              "minecraft:pumpkin_seeds": 1,
              "minecraft:torchflower_seeds": 1,
              "minecraft:wheat_seeds": 1,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation();

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "renewable-corpse-run",
        team: { teamId: "renewable-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((event) =>
                event.type === "action-succeeded"
                && event.action === "recover-death"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
    const saved = await Effect.runPromise(
      store.load("renewable-corpse-run"),
    );
    expect(saved?.memory.deathPositions).toEqual([]);
  });

  it("restarts overworld preparation when no corpse drops remain", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 4,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "burned-corpse-run",
      teamId: "burned-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:iron_pickaxe": 1,
              "minecraft:lava_bucket": 1,
              "minecraft:water_bucket": 1,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation();

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "burned-corpse-run",
        team: { teamId: "burned-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((event) =>
                event.type === "action-succeeded"
                && event.action === "recover-death"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const saved = await Effect.runPromise(store.load("burned-corpse-run"));
    expect(saved?.planner.phase).toBe(BeatGamePhase.PREPARE_OVERWORLD);
    expect(saved?.memory.deathPositions).toEqual([]);
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
  });

  it("keeps an unreachable valuable corpse after repeated safe recovery attempts", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 82,
      y: 30,
      z: 92,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "unreachable-corpse-run",
      teamId: "unreachable-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:iron_pickaxe": 1,
              "minecraft:lava_bucket": 1,
              "minecraft:water_bucket": 1,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: {
        "minecraft:wooden_sword": 1,
        "minecraft:wooden_pickaxe": 1,
        "minecraft:cooked_chicken": 3,
      },
    });
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.zipRight(Effect.fail(new BeatGameDriverError({
          operation: "pathfind",
          code: "unreachable",
          retryable: false,
          message: "No safe route found to the corpse",
        }))),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "unreachable-corpse-run",
        team: { teamId: "unreachable-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((event) =>
                event.type === "diagnostic"
                && event.message
                  === "Keeping a valuable corpse pending after failed recovery attempts"
                && event.data?.recoveryFailures === 3
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));
    const corpsePaths = driver.paths.filter((path) =>
      path.position.x === deathPosition.x
      && path.position.y === deathPosition.y
      && path.position.z === deathPosition.z
      && path.position.dimension === deathPosition.dimension
    );
    expect(corpsePaths).toHaveLength(6);
    expect(corpsePaths.map((path) => path.policy.avoidFluids)).toEqual([
      true,
      false,
      true,
      false,
      true,
      false,
    ]);
    const saved = await Effect.runPromise(
      store.load("unreachable-corpse-run"),
    );
    expect(saved?.planner.phase).toBe(BeatGamePhase.ENTER_NETHER);
    expect(saved?.memory.deathPositions).toHaveLength(1);
  });

  it("does not mistake a distant matching drop for corpse recovery", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 80,
      y: 64,
      z: -40,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "unrelated-drop-recovery-run",
      teamId: "unrelated-drop-recovery-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:stone_sword": 1,
              "minecraft:cooked_beef": 8,
              "minecraft:cobblestone": 24,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation();
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        driver.currentObservation = observation({
          counts: { "minecraft:string": 1 },
          position: deathPosition,
        });
      });
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(6) && query.radius >= 24
        ? [{
          connectionEpoch: "epoch-1",
          networkId: 44,
          entityType: "minecraft:item",
          itemId: "minecraft:stone_sword",
          position: { ...deathPosition, x: deathPosition.x + 24 },
          velocity: { x: 0, y: 0, z: 0 },
          alive: true,
          health: 5,
          observedAt: "2026-01-01T00:00:00.000Z",
        }]
        : [];

    const recoveryDetails: string[] = [];
    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "unrelated-drop-recovery-run",
        team: { teamId: "unrelated-drop-recovery-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.tap((event) =>
                Effect.sync(() => {
                  if (
                    event.type === "items-recovered"
                    && event.detail !== undefined
                  ) {
                    recoveryDetails.push(event.detail);
                  }
                })
              ),
              Stream.filter((event) =>
                event.type === "items-recovered"
                && event.detail
                  === "No corpse drops remain after the safe recovery attempt"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const saved = await Effect.runPromise(
      store.load("unrelated-drop-recovery-run"),
    );
    expect(recoveryDetails).not.toContain("Death recovery completed");
    expect(saved?.memory.deathPositions).toHaveLength(0);
  });

  it("recovers substantial renewable progress across a long spawn return", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 342,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "substantial-renewable-corpse-run",
      teamId: "substantial-renewable-corpse-team",
    });
    const corpseInventory = {
      "minecraft:cobblestone": 17,
      "minecraft:oak_log": 9,
      "minecraft:wooden_pickaxe": 1,
    };
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: corpseInventory,
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation();
    const resolvePath = driver.pathResolver;
    driver.pathResolver = (position, radius, policy) =>
      resolvePath(position, radius, policy).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            if (
              position.x === deathPosition.x
              && position.y === deathPosition.y
              && position.z === deathPosition.z
            ) {
              driver.currentObservation = observation({
                position: deathPosition,
                counts: corpseInventory,
              });
            }
          })
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "substantial-renewable-corpse-run",
        team: { teamId: "substantial-renewable-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((event) =>
                event.type === "action-succeeded"
                && event.action === "recover-death"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 2,
    }));
    expect(driver.tasks.some((task) => task.type === "collect-blocks"))
      .toBe(false);
  });

  it("abandons substantial renewable progress when replacement is cheaper than travel", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "far-renewable-corpse-run",
      teamId: "far-renewable-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:oak_log": 10,
              "minecraft:string": 2,
              "minecraft:bone": 2,
              "minecraft:leather": 3,
              "minecraft:white_wool": 1,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation();

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "far-renewable-corpse-run",
        team: { teamId: "far-renewable-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((event) =>
                event.type === "action-succeeded"
                && event.action === "recover-death"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
    const saved = await Effect.runPromise(
      store.load("far-renewable-corpse-run"),
    );
    expect(saved?.memory.deathPositions).toEqual([]);
  });

  it("completes valuable recovery with a prepared travel kit", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "valuable-corpse-run",
      teamId: "valuable-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:iron_ingot": 7,
              "minecraft:cooked_beef": 4,
              "minecraft:dirt": 16,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: {
        "minecraft:wooden_sword": 1,
        "minecraft:oak_log": 12,
        "minecraft:dirt": 16,
        "minecraft:cooked_beef": 8,
      },
    });
    const resolvePath = driver.pathResolver;
    driver.pathResolver = (position, radius, policy) =>
      resolvePath(position, radius, policy).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            if (
              position.x === deathPosition.x
              && position.y === deathPosition.y
              && position.z === deathPosition.z
            ) {
              driver.currentObservation = observation({
                position: deathPosition,
                counts: { "minecraft:iron_ingot": 7 },
              });
            }
          })
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "valuable-corpse-run",
        team: { teamId: "valuable-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((event) =>
                event.type === "action-succeeded"
                && event.action === "recover-death"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 2,
    }));
  });

  it("escapes an enclosed respawn pocket before corpse preparation", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: -38,
      z: -200,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "enclosed-corpse-run",
      teamId: "enclosed-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      position: { x: 0.5, y: 63, z: 0.5 },
      counts: {
        "minecraft:dirt": 16,
        "minecraft:wooden_pickaxe": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.surfaceColumns = [{
      x: 4,
      z: 0,
      loaded: true,
      surfaceY: 64,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds?.includes("minecraft:water") === true) {
        return [];
      }
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      const cardinalDistance = Math.abs(position.x) + Math.abs(position.z);
      const enclosed = cardinalDistance === 1
        && (position.y === 63 || position.y === 64);
      return [blockObservation(position, enclosed
        ? { blockId: "minecraft:stone" }
        : {
          blockId: "minecraft:air",
          diggable: false,
          replaceable: true,
          solid: false,
        })];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "enclosed-corpse-run",
        team: { teamId: "enclosed-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.paths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
        Effect.timeoutFail({
          duration: "5 seconds",
          onTimeout: () => new Error("Timed out waiting for pocket recovery"),
        }),
      ),
    ));

    expect(driver.paths[0]).toMatchObject({
      position: {
        x: 4.5,
        y: 65,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      policy: {
        allowMining: true,
        allowPlacing: true,
        avoidFluids: true,
      },
    });
  });

  it("falls back to nearby fish after a bounded dry corpse food search", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "aquatic-corpse-food-run",
      teamId: "aquatic-corpse-food-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 30,
      entityType: "minecraft:salmon",
      position: {
        x: 30,
        y: 62,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 18,
      food: 10,
      counts: {
        "minecraft:dirt": 16,
        "minecraft:oak_log": 12,
        "minecraft:wooden_pickaxe": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:salmon") === true
        ? [salmon]
        : [];
    const resolvePath = driver.pathResolver;
    driver.pathResolver = (position, radius, policy) =>
      resolvePath(position, radius, policy).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            if (
              position.x === salmon.position.x
              && position.y === salmon.position.y
              && position.z === salmon.position.z
            ) {
              driver.currentObservation = observation({
                health: 18,
                food: 10,
                position: { x: 28 },
                counts: {
                  "minecraft:dirt": 16,
                  "minecraft:oak_log": 12,
                  "minecraft:wooden_pickaxe": 1,
                  "minecraft:wooden_sword": 1,
                },
              });
            }
          })
        ),
      );
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "aquatic-corpse-food-run",
        team: { teamId: "aquatic-corpse-food-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* Effect.gen(function* () {
              while (!driver.tasks.some((task) =>
                task.type === "attack-entity"
              )) {
                yield* Effect.sleep(1);
              }
            }).pipe(Effect.timeoutFail({
              duration: "2 seconds",
              onTimeout: () =>
                new Error(
                  "Timed out waiting for aquatic corpse provisioning",
                ),
            }));
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        networkId: salmon.networkId,
        entityType: salmon.entityType,
      }),
    }));
    expect(driver.paths).toHaveLength(0);
    expect(driver.xzPaths).toHaveLength(2);
  });

  it("recovers a nearby corpse before preparing at low health", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 2.5,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "local-corpse-food-run",
      teamId: "local-corpse-food-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      health: 5,
      food: 9,
      counts: { "minecraft:wooden_sword": 1 },
    });
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(6)
        ? [{
          connectionEpoch: "epoch-1",
          networkId: 71,
          entityType: "minecraft:item",
          itemId: "minecraft:iron_ingot",
          position: deathPosition,
          velocity: { x: 0, y: 0, z: 0 },
          alive: true,
          health: 5,
          observedAt: new Date().toISOString(),
        }]
        : [];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.zipRight(
          position.x === deathPosition.x
              && position.y === deathPosition.y
              && position.z === deathPosition.z
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "local-corpse-food-run",
        team: { teamId: "local-corpse-food-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.paths.some(({ position }) =>
              position.x === deathPosition.x
              && position.y === deathPosition.y
              && position.z === deathPosition.z
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 2,
    }));
    expect(driver.xzPaths).toHaveLength(0);
  });

  it("tries an existing route to a corpse below before mining by hand", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 2.5,
      y: 20,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "vertical-corpse-run",
      teamId: "vertical-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({ health: 5, food: 9 });
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(6)
        ? [{
          connectionEpoch: "epoch-1",
          networkId: 72,
          entityType: "minecraft:item",
          itemId: "minecraft:iron_ingot",
          position: deathPosition,
          velocity: { x: 0, y: 0, z: 0 },
          alive: true,
          health: 5,
          observedAt: new Date().toISOString(),
        }]
        : [];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.zipRight(
          position.x === deathPosition.x
              && position.y === deathPosition.y
              && position.z === deathPosition.z
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "vertical-corpse-run",
        team: { teamId: "vertical-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.paths.some(({ position }) =>
              position.x === deathPosition.x
              && position.y === deathPosition.y
              && position.z === deathPosition.z
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 2,
      policy: expect.objectContaining({ allowMining: false }),
    }));
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "collect-blocks",
    }));
    expect(driver.xzPaths).toHaveLength(0);
  });

  it("does not replenish a healthy food reserve after every recovery meal", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "fed-corpse-run",
      teamId: "fed-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: {
        "minecraft:wooden_sword": 1,
        "minecraft:wooden_pickaxe": 1,
        "minecraft:dirt": 16,
        "minecraft:oak_log": 12,
        "minecraft:beef": 7,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 31,
      entityType: "minecraft:cow",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:cow")
        ? driver.entityResults
        : [];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.zipRight(
          position.x === deathPosition.x ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "fed-corpse-run",
        team: { teamId: "fed-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* Effect.gen(function* () {
              while (
                !driver.paths.some(({ position }) =>
                  position.x === deathPosition.x
                )
              ) {
                yield* Effect.sleep(1);
              }
            }).pipe(Effect.timeout("5 seconds"));
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "attack-entity",
    }));
    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 2,
    }));
  });

  it("accepts a viable food reserve after reaching corpse staging range", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 24,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date(Date.now() - 10 * 60_000).toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "staged-corpse-food-run",
      teamId: "staged-corpse-food-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      health: 20,
      food: 16,
      position: {
        x: 444,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      counts: {
        "minecraft:stone_sword": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:dirt": 16,
        "minecraft:oak_log": 12,
        "minecraft:salmon": 5,
      },
      remainingDurability: { "minecraft:stone_pickaxe": 131 },
    });
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.zipRight(
          position.x === deathPosition.x
              && position.y === deathPosition.y
              && position.z === deathPosition.z
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "staged-corpse-food-run",
        team: { teamId: "staged-corpse-food-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.paths.some(({ position }) =>
              position.x === deathPosition.x
              && position.y === deathPosition.y
              && position.z === deathPosition.z
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "attack-entity",
    }));
    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 2,
    }));
  });

  it("clears inventory slots before collecting nearby corpse drops", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 4,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "full-inventory-corpse-run",
      teamId: "full-inventory-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:diamond": 1,
              "minecraft:furnace": 2,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: {
        "minecraft:stone_sword": 1,
        "minecraft:leaf_litter": 64,
      },
      emptyPlayerSlots: 0,
    });
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(6)
        ? [
          {
            connectionEpoch: "epoch-1",
            networkId: 91,
            entityType: "minecraft:item",
            itemId: "minecraft:diamond",
            position: deathPosition,
            velocity: { x: 0, y: 0, z: 0 },
            alive: true,
            health: 5,
            observedAt,
          },
          {
            connectionEpoch: "epoch-1",
            networkId: 92,
            entityType: "minecraft:item",
            itemId: "minecraft:furnace",
            position: deathPosition,
            velocity: { x: 0, y: 0, z: 0 },
            alive: true,
            health: 5,
            observedAt,
          },
        ]
        : [];
    driver.blockQueryResolver = ({ center, selector }) =>
      selector.diggable === true
        ? [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        })]
        : [];
    const timeline: string[] = [];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        const isCorpsePath = position.x === deathPosition.x
          && position.y === deathPosition.y
          && position.z === deathPosition.z
          && radius === 2;
        timeline.push(isCorpsePath ? "corpse-path" : "inventory-path");
        if (isCorpsePath) {
          return;
        }
        const current = driver.currentObservation;
        driver.currentObservation = observation({
          counts: current.inventory.counts,
          ...(current.inventory.emptyPlayerSlots === undefined
            ? {}
            : {
              emptyPlayerSlots: current.inventory.emptyPlayerSlots,
            }),
          position,
          rotation: current.player.rotation,
        });
      }).pipe(
        Effect.zipRight(
          position.x === deathPosition.x
              && position.y === deathPosition.y
              && position.z === deathPosition.z
              && radius === 2
            ? Effect.never
            : Effect.void,
        ),
      );
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        const current = driver.currentObservation;
        if (action.type === "look") {
          driver.currentObservation = observation({
            counts: current.inventory.counts,
            ...(current.inventory.emptyPlayerSlots === undefined
              ? {}
              : {
                emptyPlayerSlots: current.inventory.emptyPlayerSlots,
              }),
            position: current.player.position,
            rotation: { yaw: action.yaw, pitch: action.pitch },
          });
        }
        if (action.type === "toss-items") {
          timeline.push("toss");
          const counts = { ...current.inventory.counts };
          delete counts["minecraft:leaf_litter"];
          driver.currentObservation = observation({
            counts,
            emptyPlayerSlots: 4,
            position: current.player.position,
            rotation: current.player.rotation,
          });
        }
        return {};
      });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "full-inventory-corpse-run",
        team: { teamId: "full-inventory-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!timeline.includes("corpse-path")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(timeline).toContain("toss");
    expect(timeline.indexOf("toss")).toBeLessThan(
      timeline.indexOf("corpse-path"),
    );
  });

  it("bootstraps equipment from surface logs outside the current line of sight", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 320,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = "2026-01-01T00:00:00.000Z";
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "bootstrap-corpse-run",
      teamId: "bootstrap-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation();

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "bootstrap-corpse-run",
        team: { teamId: "bootstrap-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "collect-blocks",
      blockIds: expect.arrayContaining(["minecraft:oak_log"]),
      count: 12,
      requireLineOfSight: false,
      targetYRange: { minimum: 60, maximum: 66 },
    }));
    const logCollectionIndex = driver.tasks.findIndex((task) =>
      task.type === "collect-blocks"
      && task.blockIds.includes("minecraft:oak_log")
    );
    expect(driver.taskPolicies[logCollectionIndex]?.minimumY).toBe(63);
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
  });

  it("races directly to corpse drops that are already ticking near spawn", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 144,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "active-corpse-run",
      teamId: "active-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:iron_ingot": 9,
              "minecraft:shield": 1,
              "minecraft:stone_sword": 1,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation();
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.zipRight(
          position.x === deathPosition.x ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "active-corpse-run",
        team: { teamId: "active-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.paths.some(({ position }) =>
                position.x === deathPosition.x
              )
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.some((task) => task.type === "collect-blocks"))
      .toBe(false);
    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 2,
    }));
  });

  it("prepares food before approaching an old corpse inside the active range", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 144,
      y: 20,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date(Date.now() - 10 * 60_000).toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "old-active-corpse-run",
      teamId: "old-active-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 9 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: {
        "minecraft:dirt": 16,
        "minecraft:oak_log": 12,
        "minecraft:wooden_pickaxe": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:cow",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:cow") ? [cow] : [];

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "old-active-corpse-run",
        team: { teamId: "old-active-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "attack-entity")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    }).pipe(Effect.timeout("5 seconds"))));

    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
    }));
  });

  it("immediately follows an existing route to loaded corpse drops below", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 24,
      y: -31,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date(Date.now() - 10 * 60_000).toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "loaded-deep-corpse-run",
      teamId: "loaded-deep-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:iron_ingot": 7,
              "minecraft:iron_pickaxe": 1,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      health: 14,
      food: 8,
      counts: { "minecraft:dirt": 11 },
    });
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(6)
        ? [{
          connectionEpoch: "epoch-1",
          networkId: 73,
          entityType: "minecraft:item",
          itemId: "minecraft:iron_ingot",
          position: deathPosition,
          velocity: { x: 0, y: 0, z: 0 },
          alive: true,
          health: 5,
          observedAt: new Date().toISOString(),
        }]
        : [];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.zipRight(
          position.x === deathPosition.x
              && position.y === deathPosition.y
              && position.z === deathPosition.z
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "loaded-deep-corpse-run",
        team: { teamId: "loaded-deep-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.paths.some(({ position }) =>
              position.x === deathPosition.x
              && position.y === deathPosition.y
              && position.z === deathPosition.z
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 2,
      policy: expect.objectContaining({ allowMining: false }),
    }));
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "collect-blocks",
    }));
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "attack-entity",
    }));
    expect(driver.xzPaths).toHaveLength(0);
  });

  it("prepares outside corpse chunk-loading range", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: -31,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date(Date.now() - 10 * 60_000).toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "corpse-staging-run",
      teamId: "corpse-staging-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      health: 14,
      food: 8,
      position: {
        x: 450,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
    });
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "corpse-staging-run",
        team: { teamId: "corpse-staging-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.xzPaths[0]).toEqual(expect.objectContaining({
      x: 444,
      z: 0,
      dimension: deathPosition.dimension,
    }));
    expect(driver.xzPaths[0]?.x).toBeLessThan(
      driver.currentObservation.player.position.x,
    );
  });

  it("scouts a nearby shallow old corpse before gathering supplies", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 72,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date(Date.now() - 10 * 60_000).toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "shallow-corpse-scout-run",
      teamId: "shallow-corpse-scout-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 9 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      health: 14,
      food: 8,
    });
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(6) ? [] : driver.entityResults;
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (position.x === deathPosition.x) {
          driver.currentObservation = observation({
            health: 14,
            food: 8,
            position: {
              x: deathPosition.x - 23.5,
              y: deathPosition.y,
              z: deathPosition.z,
              dimension: deathPosition.dimension,
            },
          });
        }
      });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "shallow-corpse-scout-run",
        team: { teamId: "shallow-corpse-scout-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((event) =>
                event.type === "items-recovered"
                && event.detail
                  === "Abandoned a stale corpse after confirming no drops remain nearby"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 24,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        avoidFluids: true,
      }),
    }));
    expect(driver.tasks).toHaveLength(0);
    expect(
      (await Effect.runPromise(store.load("shallow-corpse-scout-run")))
        ?.memory.deathPositions,
    ).toHaveLength(0);
  });

  it("arms itself after partially recovering an active corpse", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 144,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "partial-active-corpse-run",
      teamId: "partial-active-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:iron_ingot": 9,
              "minecraft:shield": 1,
              "minecraft:stone_sword": 1,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: { "minecraft:oak_log": 10 },
    });
    driver.recipeResolver = (resultItemId) => [{
      recipeId: resultItemId,
      recipeType: "minecraft:crafting",
      resultItemId,
      resultCount: 1,
      ingredients: [],
    }];
    driver.craftabilityResolver = () => ({
      canCraft: true,
      maximumCraftCount: 1,
      missing: [],
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:crafting_table") === true
        ? [blockObservation({
          x: 2,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:crafting_table" })]
        : [];
    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "partial-active-corpse-run",
        team: { teamId: "partial-active-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "craft")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "craft",
    }));
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
  });

  it("does not craft a recovery weapon until enough wood was collected", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 176,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "deferred-bootstrap-craft-run",
      teamId: "deferred-bootstrap-craft-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation();

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "deferred-bootstrap-craft-run",
        team: { teamId: "deferred-bootstrap-craft-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              driver.tasks.filter((task) => task.type === "collect-blocks")
                  .length < 2
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.some((task) => task.type === "craft")).toBe(false);
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
  });

  it("abandons recovery armament work when hunger becomes critical", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "critical-recovery-hunger-run",
      teamId: "critical-recovery-hunger-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            x: 700,
            y: 64,
            z: 0,
            dimension: "minecraft:overworld",
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({ food: 7 });
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:salmon",
      position: {
        x: 2,
        y: 63,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:salmon") === true
        ? [salmon]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" || task.type === "attack-entity"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "critical-recovery-hunger-run",
        team: { teamId: "critical-recovery-hunger-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({ food: 6 });
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const collectIndex = driver.tasks.findIndex(
      (task) => task.type === "collect-blocks",
    );
    const attackIndex = driver.tasks.findIndex(
      (task) => task.type === "attack-entity",
    );
    expect(collectIndex).toBeGreaterThanOrEqual(0);
    expect(attackIndex).toBeGreaterThan(collectIndex);
  });

  it("gathers disposable scaffolding instead of spending recovery wood", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "bootstrap-blocks-run",
      teamId: "bootstrap-blocks-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: {
        "minecraft:oak_log": 12,
        "minecraft:wooden_sword": 1,
      },
    });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "bootstrap-blocks-run",
        team: { teamId: "bootstrap-blocks-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "collect-blocks",
      blockIds: expect.arrayContaining([
        "minecraft:dirt",
        "minecraft:grass_block",
      ]),
    }));
    expect(driver.taskPolicies.at(-1)).toEqual(expect.objectContaining({
      avoidFluids: false,
      allowPlacing: false,
    }));
  });

  it("secures food before optional corpse recovery buffers when hurt", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "hungry-corpse-bootstrap-run",
      teamId: "hungry-corpse-bootstrap-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      food: 17,
      health: 8,
      counts: {
        "minecraft:wooden_sword": 1,
      },
    });
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:cow",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:cow") ? [cow] : [];

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "hungry-corpse-bootstrap-run",
        team: { teamId: "hungry-corpse-bootstrap-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const attackIndex = driver.tasks.findIndex((task) =>
      task.type === "attack-entity"
    );
    const collectIndex = driver.tasks.findIndex((task) =>
      task.type === "collect-blocks"
    );
    expect(attackIndex).toBeGreaterThanOrEqual(0);
    expect(collectIndex).toBe(-1);
  });

  it("stabilizes critical hunger before resuming a pending corpse recovery", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 4,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "critical-hunger-recovery-run",
      teamId: "critical-hunger-recovery-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_pickaxe": 1 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      food: 6,
      counts: { "minecraft:wooden_sword": 1 },
    });

    const firstAction = await Effect.runPromise(Effect.scoped(
      Effect.gen(function* () {
        const run = yield* beatGameWithDriver(driver, {
          runId: "critical-hunger-recovery-run",
          team: { teamId: "critical-hunger-recovery-team" },
          checkpointStore: store,
          strategy: { observationPollMs: 1 },
        });
        const action = yield* run.events.pipe(
          Stream.filter((event) => event.type === "action-started"),
          Stream.runHead,
          Effect.timeout("5 seconds"),
        );
        yield* run.stop;
        yield* run.awaitCompletion.pipe(Effect.either);
        return action;
      }),
    ));

    expect(Option.getOrUndefined(firstAction)).toMatchObject({
      type: "action-started",
      action: "satisfy:food-supply",
    });
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
  });

  it("only hunts animals along a distant corpse recovery route", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "directed-corpse-food-run",
      teamId: "directed-corpse-food-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      food: 17,
      health: 8,
      counts: {
        "minecraft:dirt": 16,
        "minecraft:oak_log": 12,
        "minecraft:wooden_sword": 1,
      },
    });
    const animalBehind = {
      connectionEpoch: "epoch-1",
      networkId: 41,
      entityType: "minecraft:cow",
      position: {
        x: -20,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    const animalAhead = {
      ...animalBehind,
      networkId: 42,
      position: {
        ...animalBehind.position,
        x: 20,
      },
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:cow")
        ? [animalBehind, animalAhead]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "directed-corpse-food-run",
        team: { teamId: "directed-corpse-food-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        networkId: animalAhead.networkId,
      }),
    }));
  });

  it("hunts nearby fish when critical recovery hunger makes dry detours unsafe", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "dry-corpse-food-run",
      teamId: "dry-corpse-food-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:salmon",
      position: {
        x: 3,
        y: 62,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      food: 6,
      health: 12,
      counts: {
        "minecraft:dirt": 16,
        "minecraft:oak_log": 12,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:salmon") === true
        ? [salmon]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "dry-corpse-food-run",
        team: { teamId: "dry-corpse-food-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.xzPaths).toHaveLength(0);
    const attackIndex = driver.tasks.findIndex(
      (task) => task.type === "attack-entity",
    );
    expect(driver.tasks[attackIndex]).toEqual(expect.objectContaining({
      target: expect.objectContaining({ networkId: salmon.networkId }),
    }));
    expect(driver.taskPolicies[attackIndex]).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: false,
      sprint: true,
    });
    expect(driver.paths).toHaveLength(0);
  });

  it("hunts nearby fish before starving during low-health corpse recovery", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "low-health-aquatic-corpse-food-run",
      teamId: "low-health-aquatic-corpse-food-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 44,
      entityType: "minecraft:salmon",
      position: {
        x: 3,
        y: 62,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      food: 13,
      health: 8,
      counts: {
        "minecraft:dirt": 16,
        "minecraft:oak_log": 12,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:salmon") === true
        ? [salmon]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "low-health-aquatic-corpse-food-run",
        team: { teamId: "low-health-aquatic-corpse-food-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.xzPaths).toHaveLength(0);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: salmon.networkId }),
    }));
    expect(driver.paths).toHaveLength(0);
  });

  it("collects urgent corpse recovery food before the outer air guard replans", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "corpse-food-drop-air-run",
      teamId: "corpse-food-drop-air-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        explorationFrontiers: {
          "minecraft:overworld:prepare-corpse-recovery-food": {
            origin: driver.currentObservation.player.position,
            nextIndex: 3,
            lastPosition: driver.currentObservation.player.position,
          },
        },
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    const recoveryCounts = {
      "minecraft:cod": 7,
      "minecraft:dirt": 42,
      "minecraft:oak_log": 8,
      "minecraft:wooden_pickaxe": 1,
      "minecraft:wooden_sword": 1,
    };
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 51,
      entityType: "minecraft:salmon",
      position: {
        x: 1,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const satisfies BeatGameEntityObservation;
    const codDrop = {
      connectionEpoch: "epoch-1",
      networkId: 52,
      entityType: "minecraft:item",
      itemId: "minecraft:cod",
      position: {
        x: 3,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const satisfies BeatGameEntityObservation;
    let salmonAlive = true;
    let dropAlive = false;
    driver.currentObservation = observation({
      food: 9,
      counts: recoveryCounts,
    });
    driver.entityQueryResolver = (query) => {
      if (query.selector.networkId === codDrop.networkId) {
        return dropAlive ? [codDrop] : [];
      }
      if (query.selector.entityTypes?.includes("minecraft:item") === true) {
        return dropAlive ? [codDrop] : [];
      }
      if (
        query.selector.entityTypes?.includes("minecraft:salmon") === true
      ) {
        return salmonAlive ? [salmon] : [];
      }
      return [];
    };
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type !== "attack-entity") {
          return;
        }
        salmonAlive = false;
        dropAlive = true;
        driver.currentObservation = observation({
          air: 195,
          food: 9,
          counts: recoveryCounts,
        });
      });
    const resolvePath = driver.pathResolver;
    driver.pathResolver = (position, radius, policy) =>
      resolvePath(position, radius, policy).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            if (
              position.x !== codDrop.position.x
              || position.y !== codDrop.position.y
              || position.z !== codDrop.position.z
            ) {
              return;
            }
            dropAlive = false;
            driver.currentObservation = observation({
              air: 190,
              food: 9,
              position: codDrop.position,
              counts: { ...recoveryCounts, "minecraft:cod": 8 },
            });
          })
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "corpse-food-drop-air-run",
        team: { teamId: "corpse-food-drop-air-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              (driver.currentObservation.inventory.counts["minecraft:cod"]
                ?? 0) < 8
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          }).pipe(Effect.timeoutFail({
            duration: "5 seconds",
            onTimeout: () =>
              new Error("Timed out waiting for the urgent cod drop pickup"),
          }))
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: codDrop.position,
    }));
    expect(driver.currentObservation.inventory.counts["minecraft:cod"]).toBe(
      8,
    );
  }, 10_000);

  it("ignores fish above critical hunger while searching for corpse food", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "dry-moderate-corpse-food-run",
      teamId: "dry-moderate-corpse-food-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      food: 10,
      health: 18,
      counts: {
        "minecraft:dirt": 16,
        "minecraft:oak_log": 12,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:salmon",
      position: {
        x: 3,
        y: 62,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "dry-moderate-corpse-food-run",
        team: { teamId: "dry-moderate-corpse-food-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
    expect(driver.xzPaths[0]).toMatchObject({
      dimension: deathPosition.dimension,
      policy: {
        allowMining: false,
        allowPlacing: false,
        sprint: false,
      },
    });
  });

  it("crosses water directly while critically searching for corpse recovery food", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "urgent-corpse-food-route-run",
      teamId: "urgent-corpse-food-route-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      food: 6,
      health: 12,
      counts: {
        "minecraft:dirt": 16,
        "minecraft:oak_log": 12,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(
        Effect.zipRight(
          policy.avoidFluids === false ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "urgent-corpse-food-route-run",
        team: { teamId: "urgent-corpse-food-route-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.xzPaths.some(({ policy }) =>
                policy.avoidFluids === false
              )
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.xzPaths.find(({ policy }) =>
      policy.avoidFluids === false
    )).toMatchObject({
      policy: {
        allowMining: false,
        allowPlacing: false,
        avoidFluids: false,
        sprint: false,
      },
    });
  });

  it("protects the corpse recovery building reserve while hunting for food", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "protected-corpse-reserve-run",
      teamId: "protected-corpse-reserve-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: {
        "minecraft:dirt": 16,
        "minecraft:wooden_sword": 1,
      },
    });
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 41,
      entityType: "minecraft:cow",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:cow") ? [cow] : [];
    const resolveTask = driver.taskResolver;
    driver.taskResolver = (task, execution) =>
      resolveTask(task, execution).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            if (task.type !== "attack-entity") {
              return;
            }
            driver.currentObservation = observation({
              counts: {
                ...driver.currentObservation.inventory.counts,
                "minecraft:beef": 8,
              },
            });
          })
        ),
      );
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.zipRight(
          position.x === deathPosition.x ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "protected-corpse-reserve-run",
        team: { teamId: "protected-corpse-reserve-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.paths.some(({ position }) =>
                position.x === deathPosition.x
              )
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const attackIndex = driver.tasks.findIndex((task) =>
      task.type === "attack-entity"
    );
    expect(attackIndex).toBeGreaterThanOrEqual(0);
    expect(driver.taskPolicies[attackIndex]).toEqual(expect.objectContaining({
      allowPlacing: false,
      avoidFluids: true,
    }));
    expect(driver.currentObservation.inventory.counts["minecraft:dirt"])
      .toBe(16);
  });

  it("tops off a distant recovery reserve that is one item short", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "buffered-corpse-food-run",
      teamId: "buffered-corpse-food-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: {
        "minecraft:beef": 7,
        "minecraft:dirt": 16,
        "minecraft:oak_log": 12,
        "minecraft:wooden_sword": 1,
      },
    });
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 41,
      entityType: "minecraft:cow",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:cow") ? [cow] : [];
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      return task.type === "attack-entity" ? Effect.never : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "buffered-corpse-food-run",
        team: { teamId: "buffered-corpse-food-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "attack-entity")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: cow.networkId }),
    }));
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
  });

  it("does not bypass a missing food reserve after bounded preparation", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const runId = "bounded-corpse-food-reserve-run";
    const teamId = "bounded-corpse-food-reserve-team";
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId,
      teamId,
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: {
        "minecraft:beef": 3,
        "minecraft:dirt": 16,
        "minecraft:oak_log": 12,
        "minecraft:wooden_pickaxe": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId,
        team: { teamId },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      yield* run.events.pipe(
        Stream.filter((event) =>
          event.type === "diagnostic"
          && event.message
            === "Continuing preparation for a valuable distant corpse"
          && event.data?.preparationFailures === 8
          && event.data.foodReserveStillMissing === true
        ),
        Stream.runHead,
        Effect.timeout("10 seconds"),
      );
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
  }, 15_000);

  it("keeps preparing instead of risking a low-health valuable recovery", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 300,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const runId = "bounded-nearby-corpse-run";
    const teamId = "bounded-nearby-corpse-team";
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId,
      teamId,
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathRecoveryFailures: {
          [`${observedAt}:preparation`]: 7,
        },
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_pickaxe": 2 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({ health: 5, food: 16 });
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
        driver.currentObservation = observation({
          health: 5,
          food: 16,
          position: {
            ...driver.currentObservation.player.position,
            x: driver.currentObservation.player.position.x + 10,
          },
        });
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId,
        team: { teamId },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      yield* run.events.pipe(
        Stream.filter((event) =>
          event.type === "diagnostic"
          && event.message
            === "Continuing preparation for a valuable distant corpse"
          && event.data?.preparationFailures === 8
        ),
        Stream.runHead,
      );
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    }).pipe(Effect.timeout("10 seconds"))));

    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
    expect(driver.xzPaths.length).toBeLessThan(8);
    const saved = await Effect.runPromise(store.load(runId));
    expect(saved?.memory.deathRecoveryFailures?.[
      `${observedAt}:preparation`
    ]).toBe(8);
  }, 15_000);

  it("abandons distant recovery after three bounded food searches", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "resumable-corpse-food-run",
      teamId: "resumable-corpse-food-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      food: 7,
      counts: {
        "minecraft:dirt": 16,
        "minecraft:wooden_sword": 1,
      },
    });
    const deepZombie = {
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:zombie",
      position: {
        x: 10,
        y: 39,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:zombie")
        ? [deepZombie]
        : [];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.sleep(1)));

    const recoveryPathCount = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "resumable-corpse-food-run",
        team: { teamId: "resumable-corpse-food-team" },
        checkpointStore: store,
        strategy: {
          maximumActionRetries: 1,
          observationPollMs: 1,
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* Effect.gen(function* () {
              while (
                (yield* store.load("resumable-corpse-food-run"))
                    ?.memory.deathPositions.length !== 0
              ) {
                yield* Effect.sleep(1);
              }
            }).pipe(Effect.timeoutFail({
              duration: "5 seconds",
              onTimeout: () =>
                new Error("The bounded corpse food search did not finish"),
            }));
            const pathCount = driver.xzPaths.length;
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
            return pathCount;
          })
        ),
      ),
    ));

    expect(recoveryPathCount).toBe(6);
    const saved = await Effect.runPromise(
      store.load("resumable-corpse-food-run"),
    );
    expect(saved?.planner.retryCount).toBe(0);
    expect(saved?.memory.deathPositions).toHaveLength(0);
    expect(driver.xzPaths.every(({ x, z }) =>
      x > 0 && z === 0
    )).toBe(true);
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "attack-entity",
    }));
  });

  it("abandons a stale valuable corpse once its loaded area has no matching drops", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 24,
      y: 20,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "stale-valuable-corpse-run",
      teamId: "stale-valuable-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: {
              "minecraft:iron_pickaxe": 1,
              "minecraft:cooked_beef": 5,
            },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      health: 20,
      food: 20,
    });
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(6) ? [] : driver.entityResults;

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "stale-valuable-corpse-run",
        team: { teamId: "stale-valuable-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((event) =>
                event.type === "items-recovered"
                && event.detail
                  === "Abandoned a stale corpse after confirming no drops remain nearby"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const saved = await Effect.runPromise(
      store.load("stale-valuable-corpse-run"),
    );
    expect(saved?.memory.deathPositions).toHaveLength(0);
    expect(driver.paths).toHaveLength(0);
    expect(driver.xzPaths).toHaveLength(0);
    expect(driver.tasks).toHaveLength(0);
  });

  it("keeps a valuable distant corpse pending until its recovery kit is ready", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "bounded-corpse-equipment-run",
      teamId: "bounded-corpse-equipment-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_pickaxe": 1 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation();
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.zipRight(Effect.fail(new BeatGameDriverError({
          operation: "pathfind",
          retryable: true,
          message: "The exploration waypoint was unreachable",
        }))),
      );

    const recoveryActivity = await Effect.runPromise(Effect.scoped(
      Effect.gen(function* () {
        const run = yield* beatGameWithDriver(driver, {
          runId: "bounded-corpse-equipment-run",
          team: { teamId: "bounded-corpse-equipment-team" },
          checkpointStore: store,
          strategy: {
            maximumActionRetries: 1,
            observationPollMs: 1,
          },
        });
        yield* run.events.pipe(
          Stream.filter((event) =>
            event.type === "diagnostic"
            && event.message
              === "Continuing preparation for a valuable distant corpse"
            && event.data?.preparationFailures === 4
          ),
          Stream.runHead,
          Effect.timeout("5 seconds"),
        );
        const earlySearches = driver.tasks.filter((task) =>
          task.type === "collect-blocks"
        ).length;
        yield* run.events.pipe(
          Stream.filter((event) =>
            event.type === "diagnostic"
            && event.message
              === "Continuing preparation for a valuable distant corpse"
            && event.data?.preparationFailures === 10
          ),
          Stream.runHead,
          Effect.timeout("10 seconds"),
        );
        const boundedSearches = driver.tasks.filter((task) =>
          task.type === "collect-blocks"
        ).length;
        const directRecoveryAttempts = driver.paths.filter(({ position }) =>
          position.x === deathPosition.x
          && position.y === deathPosition.y
          && position.z === deathPosition.z
          && position.dimension === deathPosition.dimension
        ).length;
        yield* run.stop;
        yield* run.awaitCompletion.pipe(Effect.either);
        return {
          boundedSearches,
          directRecoveryAttempts,
          earlySearches,
        };
      }),
    ));

    expect(recoveryActivity.earlySearches).toBe(4);
    expect(recoveryActivity.boundedSearches).toBeGreaterThanOrEqual(10);
    expect(recoveryActivity.directRecoveryAttempts).toBe(0);
    const saved = await Effect.runPromise(
      store.load("bounded-corpse-equipment-run"),
    );
    expect(saved?.memory.deathPositions).toHaveLength(1);
  }, 25_000);

  it("searches for corpse recovery supplies along the recovery route", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "directed-corpse-preparation-run",
      teamId: "directed-corpse-preparation-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_pickaxe": 1 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "directed-corpse-preparation-run",
        team: { teamId: "directed-corpse-preparation-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      while (driver.xzPaths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    }).pipe(Effect.timeout("5 seconds"))));

    const firstLeg = driver.xzPaths[0];
    expect(firstLeg).toBeDefined();
    expect(firstLeg?.x).toBeGreaterThan(0.5);
    expect(Math.abs(firstLeg?.z ?? Number.POSITIVE_INFINITY)).toBeLessThan(1);
    expect(firstLeg?.policy).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: true,
    });
    expect(
      Math.abs(deathPosition.x - (firstLeg?.x ?? 0)),
    ).toBeLessThan(Math.abs(deathPosition.x - 0.5));
  });

  it("detours when the directed corpse supply route is blocked", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const observedAt = new Date().toISOString();
    const runId = "detoured-corpse-preparation-run";
    const teamId = "detoured-corpse-preparation-team";
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId,
      teamId,
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_pickaxe": 1 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(
        Effect.zipRight(
          driver.xzPaths.length === 0
            ? Effect.fail(new BeatGameDriverError({
              operation: "pathfindXZ",
              retryable: true,
              message: "The directed recovery route is blocked",
            }))
            : Effect.never,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId,
        team: { teamId },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      while (driver.xzPaths.length < 2) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    }).pipe(Effect.timeout("5 seconds"))));

    const [directedLeg, detourLeg] = driver.xzPaths;
    expect(directedLeg?.x).toBeGreaterThan(0.5);
    expect(Math.abs(directedLeg?.z ?? Number.POSITIVE_INFINITY)).toBeLessThan(
      1,
    );
    expect(Math.abs(detourLeg?.x ?? Number.POSITIVE_INFINITY)).toBeLessThan(1);
    expect(detourLeg?.z).toBeGreaterThan(0.5);
  });

  it("preserves a valuable corpse while preparation moves meaningfully closer", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const runId = "progressing-corpse-equipment-run";
    const teamId = "progressing-corpse-equipment-team";
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId,
      teamId,
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_pickaxe": 1 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "collect-blocks") {
          const current = driver.currentObservation;
          driver.currentObservation = observation({
            position: {
              ...current.player.position,
              x: current.player.position.x + 16,
            },
            health: current.player.health,
            food: current.player.food,
            counts: current.inventory.counts,
          });
        }
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId,
        team: { teamId },
        checkpointStore: store,
        strategy: {
          maximumActionRetries: 1,
          observationPollMs: 1,
        },
      });
      while (
        driver.tasks.filter((task) => task.type === "collect-blocks").length
          < 9
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    const saved = await Effect.runPromise(store.load(runId));
    expect(saved?.memory.deathPositions).toContainEqual(expect.objectContaining({
      observedAt,
    }));
  }, 15_000);

  it("does not count preparation misses as corpse pickup failures", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 700,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "staged-corpse-recovery-run",
      teamId: "staged-corpse-recovery-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    const preparedCounts = {
      "minecraft:dirt": 16,
      "minecraft:wooden_sword": 1,
      "minecraft:cooked_chicken": 3,
    };
    driver.currentObservation = observation({
      food: 7,
      counts: {
        "minecraft:dirt": 16,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(6)
        ? [{
          connectionEpoch: "epoch-1",
          networkId: 44,
          entityType: "minecraft:item",
          itemId: "minecraft:iron_ingot",
          position: deathPosition,
          velocity: { x: 0, y: 0, z: 0 },
          alive: true,
          health: 5,
          observedAt: "2026-01-01T00:00:00.000Z",
        }]
        : [];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
        if (driver.xzPaths.length === 4) {
          driver.currentObservation = observation({
            counts: preparedCounts,
          });
        }
      });
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (
          position.x === deathPosition.x
          && position.y === deathPosition.y
          && position.z === deathPosition.z
          && position.dimension === deathPosition.dimension
        ) {
          driver.currentObservation = observation({
            position: deathPosition,
            counts: preparedCounts,
          });
        }
      });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "staged-corpse-recovery-run",
        team: { teamId: "staged-corpse-recovery-team" },
        checkpointStore: store,
        strategy: {
          maximumActionRetries: 1,
          observationPollMs: 1,
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((event) =>
                event.type === "diagnostic"
                && event.message
                  === "Keeping a valuable corpse pending after failed recovery attempts"
                && event.data?.recoveryFailures === 3
              ),
              Stream.runHead,
              Effect.timeout("15 seconds"),
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const corpsePaths = driver.paths.filter(({ position }) =>
      position.x === deathPosition.x
      && position.y === deathPosition.y
      && position.z === deathPosition.z
      && position.dimension === deathPosition.dimension
    );
    expect(driver.xzPaths.length).toBeGreaterThanOrEqual(4);
    expect(corpsePaths).toHaveLength(3);
    const saved = await Effect.runPromise(
      store.load("staged-corpse-recovery-run"),
    );
    expect(saved?.memory.deathPositions).toHaveLength(1);
  }, 20_000);

  it("keeps an incomplete food bootstrap active until direct recovery is safe", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 270,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "continued-corpse-food-run",
      teamId: "continued-corpse-food-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: {
        "minecraft:dirt": 16,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
        driver.currentObservation = observation({
          position: {
            x: 30,
            y: 64,
            z: 0,
            dimension: "minecraft:overworld",
          },
          counts: {
            "minecraft:dirt": 16,
            "minecraft:wooden_sword": 1,
          },
        });
      }).pipe(Effect.zipRight(Effect.sleep(1)));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "continued-corpse-food-run",
        team: { teamId: "continued-corpse-food-team" },
        checkpointStore: store,
        strategy: {
          maximumActionRetries: 1,
          observationPollMs: 1,
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* Effect.gen(function* () {
              while (driver.xzPaths.length < 2) {
                yield* Effect.sleep(1);
              }
            }).pipe(Effect.timeoutFail({
              duration: "5 seconds",
              onTimeout: () =>
                new Error("Food preparation stopped inside the threshold"),
            }));
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
  });

  it("replaces a worn stone pickaxe before a deep corpse recovery", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 100,
      y: -38,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId: "excavation-corpse-run",
      teamId: "excavation-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: {
        "minecraft:cobblestone": 3,
        "minecraft:crafting_table": 1,
        "minecraft:dirt": 16,
        "minecraft:oak_log": 12,
        "minecraft:oak_planks": 3,
        "minecraft:stick": 2,
        "minecraft:stone_pickaxe": 1,
        "minecraft:wooden_sword": 1,
        "minecraft:cooked_beef": 8,
      },
      remainingDurability: {
        "minecraft:stone_pickaxe": 50,
      },
    });
    driver.recipeResolver = (resultItemId) =>
      resultItemId === "minecraft:stone_pickaxe"
        ? [{
          recipeId: "stone-pickaxe",
          recipeType: "minecraft:crafting_shaped",
          resultItemId,
          resultCount: 1,
          ingredients: [],
        }]
        : [];
    driver.craftabilityResolver = () => ({
      canCraft: true,
      maximumCraftCount: 1,
      requiredStation: "minecraft:crafting_table",
      missing: [],
    });
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:crafting_table") === true
        ? [blockObservation({
          x: 2,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:crafting_table" })]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "craft" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "excavation-corpse-run",
        team: { teamId: "excavation-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) =>
                task.type === "craft" && task.recipeId === "stone-pickaxe"
              )
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "craft",
      recipeId: "wooden-pickaxe",
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "craft",
      recipeId: "stone-pickaxe",
    }));
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
  });

  it("replaces a worn wooden pickaxe before a deep corpse recovery", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 100,
      y: -38,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const runId = "durable-excavation-corpse-run";
    const teamId = "durable-excavation-corpse-team";
    const initial = checkpoint(BeatGamePhase.ENTER_NETHER, {
      runId,
      teamId,
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_pickaxe": 1 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: {
        "minecraft:cobblestone": 3,
        "minecraft:cooked_beef": 8,
        "minecraft:crafting_table": 1,
        "minecraft:dirt": 16,
        "minecraft:oak_log": 12,
        "minecraft:wooden_pickaxe": 1,
        "minecraft:wooden_sword": 1,
      },
      remainingDurability: {
        "minecraft:wooden_pickaxe": 3,
      },
    });
    driver.recipeResolver = (resultItemId) =>
      resultItemId === "minecraft:stone_pickaxe"
        ? [{
          recipeId: "stone-pickaxe",
          recipeType: "minecraft:crafting_shaped",
          resultItemId,
          resultCount: 1,
          ingredients: [],
        }]
        : [];
    driver.craftabilityResolver = () => ({
      canCraft: true,
      maximumCraftCount: 1,
      requiredStation: "minecraft:crafting_table",
      missing: [],
    });
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:crafting_table") === true
        ? [blockObservation({
          x: 2,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:crafting_table" })]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "craft" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId,
        team: { teamId },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) =>
                task.type === "craft" && task.recipeId === "stone-pickaxe"
              )
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
        Effect.timeout("5 seconds"),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "craft",
      recipeId: "stone-pickaxe",
    }));
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: deathPosition,
    }));
  });

  it("finishes a nearby excavation by hand when it cannot prepare a pickaxe", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const deathPosition = {
      x: 24,
      y: 40,
      z: 0,
      dimension: "minecraft:overworld",
    };
    const observedAt = new Date().toISOString();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "close-excavation-corpse-run",
      teamId: "close-excavation-corpse-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        deathPositions: [{
          key: `death:${observedAt}`,
          value: {
            ...deathPosition,
            inventoryCounts: { "minecraft:iron_ingot": 7 },
          },
          observedAt,
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      counts: {
        "minecraft:oak_planks": 2,
        "minecraft:stick": 2,
        "minecraft:wooden_sword": 1,
      },
    });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "close-excavation-corpse-run",
        team: { teamId: "close-excavation-corpse-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.paths.some(({ position }) =>
                position.x === deathPosition.x
                && position.y === deathPosition.y
                && position.z === deathPosition.z
              )
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.some((task) => task.type === "craft")).toBe(false);
  });

  it("returns to recover useful inventory after death", async () => {
    const driver = new FakeBeatGameDriver();
    const deathObservedAt = new Date().toISOString();
    const deathPosition = {
      x: 24,
      y: 64,
      z: -12,
      dimension: "minecraft:overworld",
    };
    driver.currentObservation = observation({
      position: deathPosition,
      counts: {
        "minecraft:cobblestone": 24,
        "minecraft:stone_pickaxe": 1,
      },
    });
    driver.events = Stream.make({
      type: "bot-died",
      observedAt: deathObservedAt,
      message: "Bot was slain by Zombie",
    } as const);

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((event) => event.type === "items-recovered"),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 2,
    }));
  });

  it("values a corpse from the last living inventory snapshot", async () => {
    const driver = new FakeBeatGameDriver();
    const deathPosition = {
      x: 24,
      y: 64,
      z: -12,
      dimension: "minecraft:overworld",
    };
    const livingObservation = observation({
      position: deathPosition,
      counts: {
        "minecraft:cobblestone": 24,
        "minecraft:stone_pickaxe": 1,
      },
    });
    driver.currentObservation = observation({
      dead: true,
      health: 0,
      position: deathPosition,
    });
    let observations = 0;
    driver.observationResolver = () =>
      Effect.sync(() => {
        observations += 1;
        return observations === 1
          ? livingObservation
          : driver.currentObservation;
      });
    driver.taskObserver = (task) => {
      if (task.type === "auto-respawn") {
        driver.currentObservation = observation();
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.paths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: deathPosition,
      radius: 2,
    }));
  });

  it("retains a valuable corpse when observation detects another death", async () => {
    const driver = new FakeBeatGameDriver();
    const originalDeathAt = new Date().toISOString();
    const secondDeathAt = new Date(Date.now() + 1).toISOString();
    const originalDeathPosition = {
      x: 24,
      y: 64,
      z: -12,
      dimension: "minecraft:overworld",
    };
    const secondDeathPosition = {
      x: 4,
      y: 64,
      z: 2,
      dimension: "minecraft:overworld",
    };
    driver.events = Stream.make({
      type: "bot-died",
      observedAt: originalDeathAt,
      message: "Bot was slain while carrying iron",
    } as const);
    driver.currentObservation = observation({
      position: originalDeathPosition,
      counts: { "minecraft:iron_ingot": 7 },
    });
    const recoveryPositions: BeatGameBlockPosition[] = [];

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
        hooks: {
          recoverDeath: ({ observation: current }) =>
            Effect.gen(function* () {
              recoveryPositions.push(current.player.position);
              if (recoveryPositions.length === 1) {
                driver.currentObservation = observation({
                  position: secondDeathPosition,
                });
                yield* Effect.sleep(5);
                driver.currentObservation = observation({
                  dead: true,
                  health: 0,
                  observedAt: secondDeathAt,
                  position: secondDeathPosition,
                });
                return yield* Effect.never;
              }
              if (recoveryPositions.length === 2) {
                driver.currentObservation = observation({
                  position: secondDeathPosition,
                  counts: { "minecraft:stone_sword": 1 },
                });
                return;
              }
              driver.currentObservation = observation({
                position: originalDeathPosition,
                counts: { "minecraft:iron_ingot": 7 },
              });
            }),
        },
      });
      while (recoveryPositions.length < 3) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(recoveryPositions).toEqual([
      originalDeathPosition,
      secondDeathPosition,
      originalDeathPosition,
    ]);
  });

  it("resumes item recovery after fighting a melee hostile", async () => {
    const driver = new FakeBeatGameDriver();
    const deathObservedAt = new Date().toISOString();
    const deathPosition = {
      x: 24,
      y: 64,
      z: -12,
      dimension: "minecraft:overworld",
    };
    const zombie = {
      connectionEpoch: "epoch-1",
      networkId: 31,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({
      dead: true,
      health: 0,
      observedAt: deathObservedAt,
      position: deathPosition,
    });
    driver.taskObserver = (task) => {
      if (task.type === "attack-entity") {
        driver.entityResults = [];
      }
    };
    let recoveries = 0;

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
        hooks: {
          recoverDeath: () =>
            Effect.sync(() => {
              recoveries += 1;
              if (recoveries === 1) {
                driver.currentObservation = observation();
                driver.entityResults = [zombie];
              }
            }).pipe(
              Effect.zipRight(
                recoveries === 0 ? Effect.never : Effect.void,
              ),
            ),
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (recoveries < 2) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(recoveries).toBe(2);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        connectionEpoch: zombie.connectionEpoch,
        networkId: zombie.networkId,
      }),
      selectBestWeapon: true,
    }));
  });

  it("resumes promptly after evading a corpse recovery attacker", async () => {
    const driver = new FakeBeatGameDriver();
    const deathObservedAt = new Date().toISOString();
    const deathPosition = {
      x: 24,
      y: 64,
      z: -12,
      dimension: "minecraft:overworld",
    };
    const spider = {
      connectionEpoch: "epoch-1",
      networkId: 33,
      entityType: "minecraft:spider",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 16,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({
      dead: true,
      health: 0,
      observedAt: deathObservedAt,
      position: deathPosition,
      counts: { "minecraft:iron_ingot": 7 },
    });
    driver.taskObserver = (task) => {
      if (task.type === "flee") {
        driver.entityResults = [];
      }
    };
    let recoveries = 0;

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
        hooks: {
          recoverDeath: () => {
            const waitForInterruption = recoveries === 0;
            return Effect.sync(() => {
              recoveries += 1;
              if (recoveries === 1) {
                driver.currentObservation = observation({ health: 6 });
                driver.entityResults = [spider];
              }
            }).pipe(
              Effect.zipRight(
                waitForInterruption ? Effect.never : Effect.void,
              ),
            );
          },
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (recoveries < 2) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(recoveries).toBe(2);
    expect(driver.tasks.filter((task) => task.type === "flee")).toHaveLength(1);
  });

  it("knocks back a zombie that catches a corpse recovery flee route", async () => {
    const driver = new FakeBeatGameDriver();
    const deathPosition = {
      x: 24,
      y: 64,
      z: -12,
      dimension: "minecraft:overworld",
    };
    const zombie = {
      connectionEpoch: "epoch-1",
      networkId: 34,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({
      dead: true,
      health: 0,
      position: deathPosition,
      counts: { "minecraft:iron_ingot": 7 },
    });
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2)
          || query.selector.networkId === zombie.networkId
        ? [zombie]
        : [];
    let interruptedEscapes = 0;
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.currentObservation = observation({ health: 3 });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "flee" ? Effect.never : Effect.void,
        ),
        Effect.onInterrupt(() =>
          Effect.sync(() => {
            if (task.type === "flee") {
              interruptedEscapes += 1;
            }
          })
        ),
      );

    const stateBeforeStop = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
        hooks: {
          recoverDeath: () =>
            Effect.sync(() => {
              driver.currentObservation = observation({ health: 6 });
              driver.entityResults = [zombie];
            }).pipe(Effect.zipRight(Effect.never)),
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* Effect.sleep(250);
            const result = {
              interruptedEscapes,
              fleeTasks: driver.tasks.filter((task) => task.type === "flee")
                .length,
            };
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
            return result;
          })
        ),
      ),
    ));

    expect(stateBeforeStop.interruptedEscapes).toBeGreaterThanOrEqual(1);
    expect(stateBeforeStop.fleeTasks).toBeGreaterThanOrEqual(1);
    const fleeIndex = driver.tasks.findIndex((task) => task.type === "flee");
    expect(driver.taskPolicies[fleeIndex]?.allowMining).toBe(false);
    expect(driver.actions).toContainEqual({
      type: "attack-entity",
      connectionEpoch: zombie.connectionEpoch,
      networkId: zombie.networkId,
      sprinting: true,
    });
    expect(driver.actions.some((action) =>
      action.type === "set-movement" && action.forward === true
    )).toBe(false);
  }, 10_000);

  it("keeps monitoring for new attackers after resuming item recovery", async () => {
    const driver = new FakeBeatGameDriver();
    const deathObservedAt = new Date().toISOString();
    const deathPosition = {
      x: 20,
      y: 64,
      z: 20,
      dimension: "minecraft:overworld",
    };
    const attackers = [31, 32].map((networkId) => ({
      connectionEpoch: "epoch-1",
      networkId,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const));
    driver.currentObservation = observation({
      dead: true,
      health: 0,
      observedAt: deathObservedAt,
      position: deathPosition,
    });
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskObserver = (task) => {
      if (task.type === "attack-entity") {
        driver.entityResults = [];
      }
    };
    let recoveries = 0;

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
        hooks: {
          recoverDeath: () => {
            const waitForInterruption = recoveries < attackers.length;
            return Effect.sync(() => {
              driver.currentObservation = observation();
              const attacker = attackers[recoveries];
              driver.entityResults = attacker === undefined
                ? []
                : [attacker];
              recoveries += 1;
            }).pipe(
              Effect.zipRight(
                waitForInterruption ? Effect.never : Effect.void,
              ),
            );
          },
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (recoveries < 3) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(recoveries).toBe(3);
    expect(
      driver.tasks.filter((task) => task.type === "attack-entity"),
    ).toHaveLength(2);
  });

  it("sprints and dynamically flees the hostile group around a creeper", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = Array.from({ length: 18 }, (_, index) => ({
      x: -(index + 1),
      z: 0,
      loaded: true,
      surfaceY: 63,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }));
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 41,
      entityType: "minecraft:creeper",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    let moving = false;
    driver.actionObserver = (action) => {
      if (action.type === "set-movement" && action.forward === true) {
        moving = true;
      } else if (action.type === "reset-movement") {
        moving = false;
      }
    };
    driver.observationResolver = () =>
      Effect.sync(() => {
        if (moving) {
          driver.currentObservation = {
            ...driver.currentObservation,
            player: {
              ...driver.currentObservation.player,
              position: {
                ...driver.currentObservation.player.position,
                x: driver.currentObservation.player.position.x - 0.8,
              },
            },
          };
        }
        return driver.currentObservation;
      });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.entityResults = [];
        }
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const fleeIndex = driver.tasks.findIndex((task) => task.type === "flee");
    expect(driver.tasks[fleeIndex]).toEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
      triggerRadius: 12,
      safeDistance: 24,
    }));
    expect(driver.taskPolicies[fleeIndex]).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: true,
      maxFallDistance: 3,
      sprint: true,
    });
    expect(driver.paths).toHaveLength(0);
    expect(driver.xzPaths).toHaveLength(0);
    expect(driver.actions).toContainEqual({
      type: "set-movement",
      forward: true,
      jump: true,
      sprint: true,
    });
    expect(driver.actions).toContainEqual({ type: "reset-movement" });
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "attack-entity",
    }));
  });

  it("re-sprints along a group-safe route when creepers close during flee planning", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = Array.from({ length: 37 * 37 }, (_, index) => {
      const x = index % 37 - 18;
      const z = Math.floor(index / 37) - 18;
      return {
        x,
        z,
        loaded: true,
        surfaceY: 63,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      };
    });
    const eastCreeper = {
      connectionEpoch: "epoch-1",
      networkId: 41,
      entityType: "minecraft:creeper",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    const westCreeper = {
      ...eastCreeper,
      networkId: 42,
      position: { ...eastCreeper.position, x: -6 },
    } as const;
    driver.entityResults = [eastCreeper, westCreeper];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" || task.type === "flee"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              driver.actions.filter((action) =>
                action.type === "set-movement"
                && action.forward === true
                && action.jump === true
                && action.sprint === true
              ).length < 2
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const sprintLooks = driver.actions.filter((action) =>
      action.type === "look" && action.pitch === 0
    );
    expect(sprintLooks.length).toBeGreaterThanOrEqual(2);
    const firstSprintLook = sprintLooks[0];
    if (firstSprintLook?.type === "look") {
      expect(Math.abs(Math.abs(firstSprintLook.yaw) - 90))
        .toBeGreaterThanOrEqual(45);
    }
    expect(driver.tasks.filter((task) => task.type === "flee")).toHaveLength(
      1,
    );
    expect(driver.currentObservation.player.health).toBe(20);
  }, 10_000);

  it("changes direction when an emergency creeper sprint is blocked", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = Array.from({ length: 37 * 37 }, (_, index) => ({
      x: index % 37 - 18,
      z: Math.floor(index / 37) - 18,
      loaded: true,
      surfaceY: 63,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }));
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 41,
      entityType: "minecraft:creeper",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              driver.actions.filter((action) =>
                action.type === "look" && action.pitch === 0
              ).length < 3
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const escapeLooks = driver.actions.filter((action) =>
      action.type === "look" && action.pitch === 0
    );
    expect(escapeLooks).toHaveLength(3);
    expect(escapeLooks[1]).toEqual(expect.objectContaining({ type: "look" }));
    expect(escapeLooks[2]).toEqual(expect.objectContaining({ type: "look" }));
    if (escapeLooks[1]?.type === "look" && escapeLooks[2]?.type === "look") {
      expect(Math.abs(escapeLooks[1].yaw - escapeLooks[2].yaw))
        .toBeGreaterThanOrEqual(45);
      expect(-Math.sin(escapeLooks[1].yaw * Math.PI / 180)).toBeLessThan(-0.2);
      expect(-Math.sin(escapeLooks[2].yaw * Math.PI / 180)).toBeLessThan(-0.2);
    }
    expect(driver.surfaceQueries.length).toBeGreaterThanOrEqual(2);
    expect(driver.actions.filter((action) =>
      action.type === "set-movement" && action.forward === true
    )).toHaveLength(1);
  }, 10_000);

  it("blind-sprints from a closing creeper when flee replanning stalls", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({ health: 6, food: 13 });
    const distantCreeper = {
      connectionEpoch: "epoch-1",
      networkId: 41,
      entityType: "minecraft:creeper",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    const closingCreeper = {
      ...distantCreeper,
      position: { ...distantCreeper.position, x: 5 },
      observedAt: "2026-01-01T00:00:02.000Z",
    } as const;
    driver.entityResults = [distantCreeper];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.entityResults = [closingCreeper];
        }
      }).pipe(
        Effect.zipRight(task.type === "flee" ? Effect.never : Effect.void),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.actions.some((action) =>
        action.type === "set-movement"
        && action.forward === true
        && action.jump === true
        && action.sprint === true
      )) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
    expect(driver.actions).toContainEqual({
      type: "set-movement",
      forward: true,
      jump: true,
      sprint: true,
    });
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "attack-entity",
    }));
  }, 10_000);

  it("lets an occluded creeper flee route finish planning", async () => {
    const driver = new FakeBeatGameDriver();
    const creeper = {
      connectionEpoch: "epoch-1",
      networkId: 41,
      entityType: "minecraft:creeper",
      position: {
        x: 4,
        y: 62,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    let fleeCompleted = false;
    let fleeInterruptions = 0;
    driver.entityQueryResolver = (query) => {
      if (query.selector.requireLineOfSight === true) {
        return [];
      }
      return query.selector.networkId === creeper.networkId
          || query.selector.categories?.includes(2) === true
          || query.selector.entityTypes?.includes("minecraft:creeper") === true
        ? [creeper]
        : [];
    };
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "flee"
            ? Effect.sleep(250).pipe(
              Effect.tap(() =>
                Effect.sync(() => {
                  fleeCompleted = true;
                  driver.entityQueryResolver = () => [];
                })
              ),
              Effect.onInterrupt(() =>
                Effect.sync(() => {
                  fleeInterruptions += 1;
                })
              ),
            )
            : task.type === "collect-blocks"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!fleeCompleted) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(fleeInterruptions).toBe(0);
    expect(driver.tasks.filter((task) => task.type === "flee")).toHaveLength(
      1,
    );
    expect(driver.entityQueries).toContainEqual(expect.objectContaining({
      radius: 6,
      selector: expect.objectContaining({
        entityTypes: ["minecraft:creeper"],
        alive: true,
        requireLineOfSight: true,
      }),
    }));
  }, 10_000);

  it("allows a submerged escape route to reach dry land", async () => {
    const driver = new FakeBeatGameDriver();
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 41,
      entityType: "minecraft:creeper",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    driver.blockQueryResolver = ({ center, selector }) =>
      selector.blockIds?.includes("minecraft:water") === true
        ? [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        }, {
          blockId: "minecraft:water",
          replaceable: true,
        })]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.entityResults = [];
        }
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const fleeIndex = driver.tasks.findIndex((task) => task.type === "flee");
    expect(driver.taskPolicies[fleeIndex]).toMatchObject({
      allowPlacing: false,
      avoidFluids: false,
      maxFallDistance: 3,
    });
  });

  it("allows water when no dry creeper escape corridor exists", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = Array.from({ length: 18 }, (_, index) => ({
      x: -(index + 1),
      z: 0,
      loaded: true,
      surfaceY: 63,
      blockId: "minecraft:water",
      biomeId: "minecraft:river",
      skyLight: 15,
      blockLight: 0,
    }));
    driver.blockQueryResolver = ({ center, selector }) =>
      selector.blockIds?.includes("minecraft:water") === true
        ? [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        }, {
          blockId: "minecraft:water",
          replaceable: true,
        })]
        : [];
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 41,
      entityType: "minecraft:creeper",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.entityResults = [];
        }
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const fleeIndex = driver.tasks.findIndex((task) => task.type === "flee");
    expect(driver.taskPolicies[fleeIndex]).toMatchObject({
      allowPlacing: false,
      avoidFluids: false,
      maxFallDistance: 3,
    });
    expect(driver.actions).toContainEqual(expect.objectContaining({
      type: "set-movement",
      forward: true,
      jump: true,
      sprint: true,
    }));
  });

  it("uses a fluid-avoiding route instead of blind sprinting beside lava", async () => {
    const driver = new FakeBeatGameDriver();
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 41,
      entityType: "minecraft:creeper",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    driver.blockQueryResolver = ({ radius, selector }) =>
      radius > 1
          && selector.blockIds?.includes("minecraft:lava") === true
        ? [blockObservation({
          x: 0,
          y: 63,
          z: 1,
          dimension: "minecraft:overworld",
        }, {
          blockId: "minecraft:lava",
          replaceable: true,
        })]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.entityResults = [];
        }
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" || task.type === "flee"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "flee")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    const fleeIndex = driver.tasks.findIndex((task) => task.type === "flee");
    expect(driver.taskPolicies[fleeIndex]).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: true,
    });
    expect(driver.actions).not.toContainEqual(expect.objectContaining({
      type: "set-movement",
      forward: true,
      jump: true,
      sprint: true,
    }));
  });

  it("mines out of rough terrain when a creeper escape route fails", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: { x: 0, y: 58, z: 0 },
      counts: {
        "minecraft:dirt": 16,
        "minecraft:oak_log": 8,
        "minecraft:wooden_pickaxe": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:creeper",
      position: {
        x: 5,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    driver.surfaceColumns = [
      {
        x: 0,
        z: 0,
        loaded: true,
        surfaceY: 57,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: 3,
        z: 0,
        loaded: true,
        surfaceY: 64,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
    ];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "flee"
            ? Effect.fail(new BeatGameDriverError({
              operation: "task.flee",
              code: "unreachable",
              retryable: true,
              message: "The bot is trapped below the creeper",
            }))
            : Effect.never,
        ),
      );
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        !driver.tasks.some((task) => task.type === "flee")
        || !driver.paths.some(({ policy }) =>
          policy.allowMining === true
          && policy.allowPlacing === true
          && policy.maxSearchTimeMs === 5_000
        )
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
    expect(driver.paths.find(({ policy }) =>
      policy.allowMining === true
      && policy.allowPlacing === true
      && policy.maxSearchTimeMs === 5_000
    )).toMatchObject({
      position: {
        x: 3.5,
        y: 65,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 0.75,
      policy: {
        allowMining: true,
        allowPlacing: true,
        avoidFluids: true,
        sprint: false,
        maxSearchTimeMs: 5_000,
      },
    });
  }, 10_000);

  it("carves an upward staircase out of a dry shaft", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: { x: 0.5, y: 61.2, z: 0.5 },
      counts: {
        "minecraft:cooked_beef": 4,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:creeper",
      position: {
        x: 4,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    driver.surfaceColumns = Array.from({ length: 9 }, (_, index) => ({
      x: index % 3 + 2,
      z: Math.floor(index / 3) - 1,
      loaded: true,
      surfaceY: 64,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }));
    const blocks = new Map<string, ReturnType<typeof blockObservation>>();
    const setBlock = (
      position: BeatGameBlockPosition,
      overrides: Parameters<typeof blockObservation>[1] = {},
    ) => {
      blocks.set(
        `${position.x}:${position.y}:${position.z}`,
        blockObservation(position, overrides),
      );
    };
    for (let rise = 1; rise <= 4; rise += 1) {
      setBlock({
        x: rise,
        y: 61 + rise - 1,
        z: 0,
        dimension: "minecraft:overworld",
      }, rise === 4 ? { blockId: "minecraft:grass_block" } : {});
      for (const y of [61 + rise, 62 + rise]) {
        setBlock({
          x: rise,
          y,
          z: 0,
          dimension: "minecraft:overworld",
        }, rise === 4
          ? {
            blockId: "minecraft:air",
            diggable: false,
            replaceable: true,
            solid: false,
          }
          : {});
      }
    }
    driver.blockQueryResolver = ({ center, radius, selector }) => {
      if (radius > 0.25 || Object.keys(selector).length > 0) {
        return [];
      }
      const block = blocks.get(
        `${Math.floor(center.x)}:${Math.floor(center.y)}:${
          Math.floor(center.z)
        }`,
      );
      return block === undefined ? [] : [block];
    };
    driver.actionObserver = (action) => {
      if (action.type !== "dig-block") {
        return;
      }
      setBlock(action.position, {
        blockId: "minecraft:air",
        diggable: false,
        replaceable: true,
        solid: false,
      });
    };
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "flee"
            ? Effect.fail(new BeatGameDriverError({
              operation: "task.flee",
              code: "unreachable",
              retryable: true,
              message: "The bot is trapped in a dry shaft",
            }))
            : Effect.never,
        ),
      );
    driver.pathResolver = (position, radius, policy) => {
      const record = Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      });
      if (radius !== 0.35) {
        return record.pipe(
          Effect.zipRight(Effect.fail(new BeatGameDriverError({
            operation: "pathfind",
            code: "unreachable",
            retryable: true,
            message: "The sealed vertical shaft has no walkable route",
          }))),
        );
      }
      return record.pipe(Effect.tap(() => Effect.sync(() => {
        driver.currentObservation = {
          ...driver.currentObservation,
          player: {
            ...driver.currentObservation.player,
            position,
          },
        };
        if (position.y === 65) {
          driver.entityResults = [];
        }
      })));
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      for (
        let polls = 0;
        polls < 1_000 && driver.currentObservation.player.position.y < 65;
        polls += 1
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.currentObservation.player.position.y).toBe(65);
    expect(driver.actions.filter((action) => action.type === "dig-block"))
      .toHaveLength(6);
    expect(driver.paths.filter(({ radius }) => radius === 0.35).map(
      ({ position }) => position,
    )).toEqual([
      expect.objectContaining({ x: 1.5, y: 62, z: 0.5 }),
      expect.objectContaining({ x: 2.5, y: 63, z: 0.5 }),
      expect.objectContaining({ x: 3.5, y: 64, z: 0.5 }),
      expect.objectContaining({ x: 4.5, y: 65, z: 0.5 }),
    ]);
  }, 10_000);

  it("detects nearby creepers without requiring line of sight", async () => {
    const driver = new FakeBeatGameDriver();
    const creeper = {
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:creeper",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:creeper")
        && query.selector.requireLineOfSight !== true
        ? [creeper]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.entityQueryResolver = () => [];
        }
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.entityQueries).toContainEqual(expect.objectContaining({
      radius: 12,
      selector: expect.objectContaining({
        entityTypes: expect.arrayContaining(["minecraft:creeper"]),
        alive: true,
      }),
    }));
    const fleeIndex = driver.tasks.findIndex((task) => task.type === "flee");
    expect(driver.tasks[fleeIndex]).toEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
    expect(driver.taskPolicies[fleeIndex]?.sprint).toBe(true);
  });

  it("keeps escaping a nearby creeper when a ranged attacker deals damage", async () => {
    const driver = new FakeBeatGameDriver();
    const creeper = {
      connectionEpoch: "epoch-1",
      networkId: 41,
      entityType: "minecraft:creeper",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    const skeleton = {
      ...creeper,
      networkId: 42,
      entityType: "minecraft:skeleton",
      position: { ...creeper.position, x: 8 },
    } as const;
    driver.entityResults = [creeper];
    let interruptedEscapes = 0;
    let escapes = 0;
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type !== "flee") {
          return;
        }
        escapes += 1;
        driver.entityResults = [creeper, skeleton];
        driver.currentObservation = observation({ health: 17 });
      }).pipe(
        Effect.zipRight(
          task.type === "flee" ? Effect.never : Effect.void,
        ),
        Effect.onInterrupt(() =>
          Effect.sync(() => {
            if (task.type === "flee") {
              interruptedEscapes += 1;
            }
          })
        ),
      );

    const interruptedBeforeStop = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (escapes === 0) {
              yield* Effect.sleep(1);
            }
            yield* Effect.sleep(250);
            const result = interruptedEscapes;
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
            return result;
          })
        ),
      ),
    ));

    expect(interruptedBeforeStop).toBe(0);
    expect(escapes).toBe(1);
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "attack-entity",
    }));
    expect(driver.tasks.filter((task) => task.type === "flee")).toHaveLength(1);
  }, 10_000);

  it("knocks back a secondary pursuer and resumes group-aware creeper evasion", async () => {
    const driver = new FakeBeatGameDriver();
    const creeper = {
      connectionEpoch: "epoch-1",
      networkId: 41,
      entityType: "minecraft:creeper",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    const spider = {
      ...creeper,
      networkId: 42,
      entityType: "minecraft:spider",
      position: { ...creeper.position, x: 2 },
    } as const;
    driver.entityResults = [creeper];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.entityResults = [
            { ...creeper, position: { ...creeper.position, x: 13 } },
            spider,
          ];
          driver.currentObservation = observation({ health: 17 });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" || task.type === "flee"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "flee")) {
        yield* Effect.sleep(1);
      }
      while (
        driver.tasks.filter((task) => task.type === "flee").length < 2
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.actions).toContainEqual({
      type: "attack-entity",
      connectionEpoch: spider.connectionEpoch,
      networkId: spider.networkId,
      sprinting: true,
    });
    const escapes = driver.tasks.filter((task) => task.type === "flee");
    expect(escapes).toHaveLength(2);
    expect(escapes).toEqual(expect.arrayContaining([
      expect.objectContaining({
        selector: { categories: [2], alive: true },
      }),
    ]));
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "attack-entity",
    }));
  }, 10_000);

  it("restarts a stalled ranged escape after another hit", async () => {
    const driver = new FakeBeatGameDriver();
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 45,
      entityType: "minecraft:skeleton",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({ health: 8 });
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
          || query.selector.networkId === skeleton.networkId
        ? [skeleton]
        : [];
    let interruptedEscapes = 0;
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.currentObservation = observation({ health: 5 });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" || task.type === "flee"
            ? Effect.never
            : Effect.void,
        ),
        Effect.onInterrupt(() =>
          Effect.sync(() => {
            if (task.type === "flee") {
              interruptedEscapes += 1;
            }
          })
        ),
      );

    const stateBeforeStop = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { minimumHealth: 4, observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* Effect.sleep(250);
            const result = {
              interruptedEscapes,
              fleeTasks: driver.tasks.filter((task) => task.type === "flee")
                .length,
            };
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
            return result;
          })
        ),
      ),
    ));

    expect(stateBeforeStop).toEqual({
      interruptedEscapes: 1,
      fleeTasks: 2,
    });
    expect(driver.tasks.filter((task) => task.type === "flee")).toHaveLength(2);
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "attack-entity",
    }));
  });

  it("keeps witch evasion active when a zombie catches up", async () => {
    const driver = new FakeBeatGameDriver();
    const witch = {
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:witch",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 26,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    const zombie = {
      ...witch,
      networkId: 44,
      entityType: "minecraft:zombie",
      position: { ...witch.position, x: 2 },
      health: 20,
    } as const;
    driver.entityResults = [witch];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.entityResults = [
            { ...witch, position: { ...witch.position, x: 14 } },
            zombie,
          ];
          driver.currentObservation = observation({ health: 17 });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" || task.type === "flee"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "flee")) {
        yield* Effect.sleep(1);
      }
      yield* Effect.sleep(250);
      yield* run.stop;
    })));

    expect(driver.tasks.filter((task) => task.type === "flee")).toHaveLength(1);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "attack-entity",
    }));
  });

  it("preempts a ranged retreat when a creeper approaches", async () => {
    const driver = new FakeBeatGameDriver();
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:skeleton",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    const creeper = {
      ...skeleton,
      networkId: 44,
      entityType: "minecraft:creeper",
      position: { ...skeleton.position, x: 4 },
    } as const;
    driver.currentObservation = observation({ health: 8 });
    let creeperApproaching = false;
    driver.entityQueryResolver = (query) => {
      if (query.selector.networkId === skeleton.networkId) {
        return [skeleton];
      }
      if (
        query.selector.entityTypes?.includes("minecraft:creeper") === true
      ) {
        return creeperApproaching ? [creeper] : [];
      }
      return query.selector.categories?.includes(2) === true
        ? creeperApproaching ? [creeper, skeleton] : [skeleton]
        : [];
    };
    let interruptedEscapes = 0;
    let escapes = 0;
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type !== "flee") {
          return false;
        }
        escapes += 1;
        if (escapes === 1) {
          creeperApproaching = true;
          return true;
        }
        creeperApproaching = false;
        return false;
      }).pipe(
        Effect.flatMap((shouldRemainActive) =>
          task.type === "collect-blocks" || shouldRemainActive
            ? Effect.never
            : Effect.void
        ),
        Effect.onInterrupt(() =>
          Effect.sync(() => {
            if (task.type === "flee") {
              interruptedEscapes += 1;
            }
          })
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (escapes < 2) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(interruptedEscapes).toBe(1);
    expect(driver.tasks.filter((task) => task.type === "flee")).toEqual([
      expect.objectContaining({
        selector: { categories: [2], alive: true },
      }),
      expect.objectContaining({
        selector: { categories: [2], alive: true },
      }),
    ]);
    expect(driver.currentObservation.player.health).toBe(8);
  }, 10_000);

  it("does not abandon work for a creeper outside its proactive range", async () => {
    const driver = new FakeBeatGameDriver();
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:creeper",
      position: {
        x: 10,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "collect-blocks")) {
        yield* Effect.sleep(1);
      }
      yield* Effect.sleep(250);
      yield* run.stop;
    })));

    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  });

  it("does not pursue a submerged drowned that is not attacking", async () => {
    const driver = new FakeBeatGameDriver();
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 44,
      entityType: "minecraft:drowned",
      position: {
        x: 0,
        y: 55,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "collect-blocks")) {
        yield* Effect.sleep(1);
      }
      yield* Effect.sleep(250);
      yield* run.stop;
    })));

    expect(driver.entityQueries).toContainEqual(expect.objectContaining({
      selector: expect.objectContaining({
        categories: [2],
        alive: true,
        requireLineOfSight: true,
      }),
    }));
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  });

  it("stops escaping once a creeper is outside its trigger radius", async () => {
    const driver = new FakeBeatGameDriver();
    const creeper = {
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:creeper",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 8,
      counts: { "minecraft:cooked_beef": 1 },
    });
    driver.entityResults = [creeper];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.entityResults = [{
            ...creeper,
            position: { ...creeper.position, x: 16 },
          }];
          driver.currentObservation = observation({
            health: 20,
            counts: { "minecraft:cooked_beef": 1 },
          });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            yield* Effect.sleep(250);
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toHaveLength(0);
    expect(driver.tasks.filter((task) => task.type === "flee")).toHaveLength(1);
  });

  it("uses a water bucket before food when retreating from lava", async () => {
    const driver = new FakeBeatGameDriver();
    let inLava = true;
    driver.currentObservation = observation({
      health: 16,
      counts: {
        "minecraft:cooked_beef": 4,
        "minecraft:water_bucket": 1,
      },
    });
    driver.blockQueryResolver = ({ center, selector }) =>
      inLava
        && selector.blockIds?.includes("minecraft:lava") === true
        ? [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        }, {
          blockId: "minecraft:lava",
          replaceable: true,
        })]
        : [];
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        if (action.type === "look") {
          driver.currentObservation = {
            ...driver.currentObservation,
            player: {
              ...driver.currentObservation.player,
              rotation: {
                yaw: action.yaw,
                pitch: action.pitch,
              },
            },
          };
        }
        if (action.type === "use-item") {
          inLava = false;
          driver.currentObservation = observation({
            health: 20,
            counts: {
              "minecraft:bucket": 1,
              "minecraft:cooked_beef": 4,
            },
          });
        }
        return {};
      });

    const retreatCompleted = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            const event = yield* run.events.pipe(
              Stream.filter((candidate) =>
                candidate.type === "action-succeeded"
                && candidate.action === "retreat"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
            return event;
          })
        ),
      ),
    ));

    expect(Option.isSome(retreatCompleted)).toBe(true);
    expect(driver.actions).toContainEqual({
      type: "select-item",
      selector: { itemIds: ["minecraft:water_bucket"] },
    });
    expect(driver.actions).toContainEqual({ type: "use-item", hand: "main" });
  });

  it("enters nearby water before retreating while on fire", async () => {
    const driver = new FakeBeatGameDriver();
    const water = {
      x: 2,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    driver.currentObservation = observation({
      health: 16,
      fireTicks: 80,
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:water") === true
        ? [blockObservation(water, {
          blockId: "minecraft:water",
          replaceable: true,
        })]
        : [];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        driver.currentObservation = observation({
          position,
          health: 20,
          fireTicks: 0,
        });
      });

    const retreatCompleted = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            const event = yield* run.events.pipe(
              Stream.filter((candidate) =>
                candidate.type === "action-succeeded"
                && candidate.action === "retreat"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
            return event;
          })
        ),
      ),
    ));

    expect(Option.isSome(retreatCompleted)).toBe(true);
    expect(driver.paths).toContainEqual({
      position: {
        x: 2.5,
        y: 64.5,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 0.75,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        avoidFluids: false,
        maxFallDistance: 1,
      }),
    });
  });

  it("replans when a retreat target cannot be reached", async () => {
    const driver = new FakeBeatGameDriver();
    const zombie = {
      connectionEpoch: "epoch-1",
      networkId: 45,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 8,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({ health: 8 });
    driver.entityResults = [zombie];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.entityResults = [];
          driver.currentObservation = observation({ health: 20 });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-nearest"
            ? Effect.fail(new BeatGameDriverError({
              operation: "task.attack-nearest",
              retryable: true,
              message: "Unable to reach the target entity",
            }))
            : Effect.void,
        ),
      );

    const retreatCompleted = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            const event = yield* run.events.pipe(
              Stream.filter((candidate) =>
                candidate.type === "action-succeeded"
                && candidate.action === "retreat"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
            return event;
          })
        ),
      ),
    ));

    expect(Option.isSome(retreatCompleted)).toBe(true);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-nearest",
      selector: {
        categories: [2],
        alive: true,
      },
    }));
    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: {
        x: -24,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      radius: 4,
      policy: expect.objectContaining({
        allowPlacing: false,
      }),
    }));
  });

  it("keeps fleeing instead of eating while a hidden hostile can chase", async () => {
    const driver = new FakeBeatGameDriver();
    const zombie = {
      connectionEpoch: "epoch-1",
      networkId: 451,
      entityType: "minecraft:zombie",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 6,
      food: 18,
      counts: {
        "minecraft:cooked_beef": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
          && query.selector.requireLineOfSight !== true
        ? [zombie]
        : [];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            for (
              let attempt = 0;
              attempt < 4_000 && driver.xzPaths.length === 0;
              attempt += 1
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.some((task) => task.type === "auto-eat")).toBe(false);
    expect(driver.xzPaths).toContainEqual(expect.objectContaining({
      x: -24,
      z: 0,
      dimension: "minecraft:overworld",
      radius: 4,
      policy: expect.objectContaining({
        sprint: true,
        allowMining: false,
        allowPlacing: false,
      }),
    }));
  });

  it("fights one close hostile at a time without attempting a generic escape", async () => {
    const driver = new FakeBeatGameDriver();
    const hostiles = [
      {
        connectionEpoch: "epoch-1",
        networkId: 46,
        entityType: "minecraft:zombie",
        position: {
          x: 2,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        },
        velocity: { x: 0, y: 0, z: 0 },
        alive: true,
        health: 20,
        observedAt: "2026-01-01T00:00:01.000Z",
      },
      {
        connectionEpoch: "epoch-1",
        networkId: 47,
        entityType: "minecraft:spider",
        position: {
          x: 3,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        },
        velocity: { x: 0, y: 0, z: 0 },
        alive: true,
        health: 16,
        observedAt: "2026-01-01T00:00:01.000Z",
      },
    ] as const;
    driver.currentObservation = observation({
      health: 8,
      counts: { "minecraft:cooked_beef": 1 },
    });
    driver.entityResults = [...hostiles];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-nearest") {
          driver.entityResults = [];
          driver.currentObservation = observation({ health: 20 });
        }
      }).pipe(
        Effect.zipRight(Effect.void),
      );

    const retreatCompleted = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            const event = yield* run.events.pipe(
              Stream.filter((candidate) =>
                candidate.type === "action-succeeded"
                && candidate.action === "retreat"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
            return event;
          })
        ),
      ),
    ));

    expect(Option.isSome(retreatCompleted)).toBe(true);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-nearest",
      selector: {
        categories: [2],
        alive: true,
      },
      selectBestWeapon: true,
    }));
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  });

  it("finishes a close underground melee fight before reacting to ranged hostiles", async () => {
    const driver = new FakeBeatGameDriver();
    const position = {
      x: 0,
      y: 23,
      z: 0,
      dimension: "minecraft:overworld",
    };
    driver.currentObservation = observation({
      health: 20,
      position,
      counts: {
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 48,
      entityType: "minecraft:skeleton",
      position: {
        ...position,
        x: 8,
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }, {
      connectionEpoch: "epoch-1",
      networkId: 49,
      entityType: "minecraft:zombie",
      position: {
        ...position,
        x: 2,
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-nearest") {
          driver.currentObservation = observation({
            health: 6,
            position,
            counts: {
              "minecraft:shield": 1,
              "minecraft:stone_sword": 1,
            },
          });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-nearest" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* Effect.sleep(20);
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-nearest",
      maximumTargets: 1,
      selectBestWeapon: true,
    }));
    expect(driver.tasks.some((task) =>
      task.type === "attack-entity"
      && task.target.networkId === 48
    )).toBe(false);
    expect(driver.actions.some((action) =>
      action.type === "set-movement" && action.sprint === true
    )).toBe(false);
  });

  it("escapes underground threats toward the Overworld surface", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = [{
      x: 0,
      z: 0,
      loaded: true,
      surfaceY: 64,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.currentObservation = observation({
      health: 4,
      position: {
        x: 0,
        y: 30,
        z: 0,
        dimension: "minecraft:overworld",
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:creeper",
      position: {
        x: 6,
        y: 30,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.paths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths[0]).toEqual({
      position: {
        x: -24,
        y: 80,
        z: 0,
        dimension: "minecraft:overworld",
      },
      radius: 17,
      policy: expect.objectContaining({
        allowMining: true,
        allowPlacing: true,
        maxSearchTimeMs: 3_000,
      }),
    });
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  });

  it("escapes aggressive neutral mobs while ignoring calm ones", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      counts: { "minecraft:cooked_beef": 1 },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 11,
      entityType: "minecraft:wolf",
      position: {
        x: 1,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 8,
      observedAt: "2026-01-01T00:00:00.000Z",
    }, {
      connectionEpoch: "epoch-1",
      networkId: 12,
      entityType: "minecraft:polar_bear",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 30,
      target: {
        connectionEpoch: "epoch-1",
        networkId: 99,
      },
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.taskObserver = (task) => {
      if (task.type === "flee") {
        driver.entityResults = [];
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "flee")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.entityQueries[0]).toMatchObject({
      radius: 24,
      selector: {
        entityTypes: expect.arrayContaining(["minecraft:polar_bear"]),
        alive: true,
      },
      maximumResults: 8,
    });
    expect(driver.tasks.filter((task) => task.type === "flee")).toEqual([
      expect.objectContaining({
        selector: {
          networkId: 12,
          alive: true,
        },
        triggerRadius: 24,
        safeDistance: 32,
        maximumEscapes: 2,
      }),
    ]);
  });

  it("flees a ranged hostile at critical health despite carrying a shield", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 3,
      counts: {
        "minecraft:cooked_beef": 1,
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 13,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskObserver = (task) => {
      if (task.type === "flee") {
        driver.entityResults = [];
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "flee")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
  });

  it("evades an approaching melee hostile before contact while wounded", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      counts: {
        "minecraft:cooked_beef": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 14,
      entityType: "minecraft:zombie",
      position: {
        x: 10,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
      triggerRadius: 12,
      safeDistance: 24,
    }));
    expect(driver.tasks.some((task) =>
      task.type === "attack-nearest" || task.type === "attack-entity"
    )).toBe(false);
  });

  it("evades ranged hostiles while critically hurt and unarmed", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      counts: {
        "minecraft:cooked_beef": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 15,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.surfaceColumns = Array.from({ length: 18 }, (_, index) =>
      index + 1
    ).flatMap((distance) =>
      [-2, -1, 0, 1, 2].map((z) => ({
        x: -distance,
        z,
        loaded: true,
        surfaceY: 63,
        blockId: "minecraft:grass_block",
        skyLight: 15,
        blockLight: 0,
      }))
    );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "flee")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions).toContainEqual({
      type: "set-movement",
      forward: true,
      jump: true,
      sprint: true,
    });
    expect(driver.actions).toContainEqual({
      type: "set-movement",
      left: true,
      right: false,
    });
    expect(driver.actions).toContainEqual({
      type: "set-movement",
      left: false,
      right: true,
    });
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
      triggerRadius: 24,
      safeDistance: 32,
    }));
    expect(driver.tasks.some((task) =>
      task.type === "attack-nearest" || task.type === "attack-entity"
    )).toBe(false);
  });

  it("knocks back and flees a close ranged hostile at critical health", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({ health: 6, food: 9 });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 21,
      entityType: "minecraft:skeleton",
      position: {
        x: 1.5,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "flee")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions).toContainEqual({
      type: "attack-entity",
      connectionEpoch: "epoch-1",
      networkId: 21,
      sprinting: true,
    });
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
      triggerRadius: 24,
      safeDistance: 32,
    }));
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  });

  it("keeps fleeing when a ranged attacker closes the gap", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({ health: 8 });
    let skeleton: BeatGameEntityObservation = {
      connectionEpoch: "epoch-1",
      networkId: 22,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    };
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2)
          || query.selector.networkId === skeleton.networkId
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          skeleton = {
            ...skeleton,
            position: { ...skeleton.position, x: 1.5 },
          };
          driver.entityResults = [skeleton];
          driver.currentObservation = observation({ health: 6 });
        }
      }).pipe(
        Effect.zipRight(task.type === "flee" ? Effect.never : Effect.void),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { minimumHealth: 4, observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* Effect.sleep(250);
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.filter((task) => task.type === "flee")).toHaveLength(2);
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  });

  it("turns to fight when an armed ranged escape is caught", async () => {
    const driver = new FakeBeatGameDriver();
    let skeleton: BeatGameEntityObservation = {
      connectionEpoch: "epoch-1",
      networkId: 23,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    };
    const secondSkeleton: BeatGameEntityObservation = {
      ...skeleton,
      networkId: 24,
      position: { ...skeleton.position, x: 7 },
    };
    driver.currentObservation = observation({
      health: 15,
      counts: { "minecraft:stone_sword": 1 },
    });
    driver.entityResults = [skeleton, secondSkeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.networkId === undefined
        ? driver.entityResults
        : driver.entityResults.filter((entity) =>
          entity.networkId === query.selector.networkId
        );
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          skeleton = {
            ...skeleton,
            position: { ...skeleton.position, x: 2 },
          };
          driver.entityResults = [skeleton, secondSkeleton];
          driver.currentObservation = observation({
            health: 10,
            counts: { "minecraft:stone_sword": 1 },
          });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "flee" || task.type === "attack-entity"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        networkId: skeleton.networkId,
        entityType: "minecraft:skeleton",
      }),
      selectBestWeapon: true,
    }));
  });

  it("uses fluid-avoiding dynamic escape instead of sprinting into water", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      counts: {
        "minecraft:cooked_beef": 1,
      },
    });
    const skeleton: BeatGameEntityObservation = {
      connectionEpoch: "epoch-1",
      networkId: 19,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    };
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.blockQueryResolver = ({ center, selector }) =>
      selector.blockIds?.includes("minecraft:water") && center.x < -1
        ? [blockObservation(
          {
            x: Math.floor(center.x),
            y: Math.floor(center.y),
            z: Math.floor(center.z),
            dimension: center.dimension,
          },
          { blockId: "minecraft:water", replaceable: true },
        )]
        : [];
    driver.surfaceColumns = [-9, -8, -7].flatMap((x) =>
      [-1, 0, 1].map((z) => ({
        x,
        z,
        loaded: true,
        surfaceY: 63,
        blockId: "minecraft:grass_block",
        skyLight: 15,
        blockLight: 0,
      }))
    );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions.some((action) =>
      action.type === "set-movement" && action.forward === true
    )).toBe(false);
    const fleeIndex = driver.tasks.findIndex((task) => task.type === "flee");
    expect(driver.tasks[fleeIndex]).toMatchObject({
      type: "flee",
      selector: { categories: [2], alive: true },
      triggerRadius: 24,
      safeDistance: 32,
    });
    expect(driver.taskPolicies[fleeIndex]).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: true,
    });
    expect(driver.surfaceQueries).toContainEqual(expect.objectContaining({
      radius: 16,
      sampleStep: 1,
    }));
  });

  it("swim-strafes away from a ranged hostile when already in water", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({ health: 8 });
    const bogged: BeatGameEntityObservation = {
      connectionEpoch: "epoch-1",
      networkId: 23,
      entityType: "minecraft:bogged",
      position: {
        x: 6,
        y: 62,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 16,
      observedAt: "2026-01-01T00:00:00.000Z",
    };
    driver.entityResults = [bogged];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
        ? driver.entityResults
        : [];
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
        ? [blockObservation({
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          replaceable: true,
        })]
        : [];

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions).toContainEqual({
      type: "set-movement",
      forward: true,
      jump: true,
      sprint: true,
    });
    expect(driver.actions).toContainEqual({
      type: "set-movement",
      left: true,
      right: false,
    });
    expect(driver.actions).toContainEqual({
      type: "set-movement",
      left: false,
      right: true,
    });
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      triggerRadius: 24,
      safeDistance: 32,
    }));
  });

  it("swims directly away from a drowned when no shore route is loaded", async () => {
    const driver = new FakeBeatGameDriver();
    const position = {
      x: 0,
      y: 61,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const drowned = {
      connectionEpoch: "epoch-1",
      networkId: 23,
      entityType: "minecraft:drowned",
      position: { ...position, x: 6 },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 5,
      food: 17,
      position,
      counts: { "minecraft:wooden_sword": 1 },
    });
    driver.entityResults = [drowned];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
          || query.selector.networkId === drowned.networkId
        ? driver.entityResults
        : [];
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
        ? [blockObservation({
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          replaceable: true,
        })]
        : [];

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.actions.some((action) =>
              action.type === "set-movement"
              && action.forward === true
              && action.jump === true
              && action.sprint === true
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions).toContainEqual({
      type: "set-movement",
      forward: true,
      jump: true,
      sprint: true,
    });
    expect(driver.actions).toContainEqual(expect.objectContaining({
      type: "look",
      pitch: 0,
    }));
  });

  it("knocks back a drowned that catches a low-health swim escape", async () => {
    const driver = new FakeBeatGameDriver();
    const position = {
      x: 0,
      y: 61,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const drowned = {
      connectionEpoch: "epoch-1",
      networkId: 24,
      entityType: "minecraft:drowned",
      position: { ...position, x: 8 },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 8,
      food: 17,
      position,
      counts: { "minecraft:wooden_sword": 1 },
    });
    driver.entityResults = [drowned];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
          || query.selector.networkId === drowned.networkId
        ? driver.entityResults
        : [];
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
        ? [blockObservation({
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          replaceable: true,
        })]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" || task.type === "flee"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({
              health: 6,
              food: 17,
              position,
              counts: { "minecraft:wooden_sword": 1 },
            });
            driver.entityResults = [{
              ...drowned,
              position: { ...drowned.position, x: 3 },
            }];
            while (!driver.actions.some((action) =>
              action.type === "attack-entity"
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions).toContainEqual({
      type: "attack-entity",
      connectionEpoch: drowned.connectionEpoch,
      networkId: drowned.networkId,
      sprinting: true,
    });
    expect(driver.actions).toContainEqual({
      type: "select-item",
      selector: { itemIds: expect.arrayContaining(["minecraft:wooden_sword"]) },
    });
  }, 10_000);

  it("escapes a drowned toward dry ground instead of staying submerged", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 5,
      food: 17,
      position: {
        x: 0,
        y: 58,
        z: 0,
        dimension: "minecraft:overworld",
      },
      counts: { "minecraft:wooden_sword": 1 },
    });
    const drowned: BeatGameEntityObservation = {
      connectionEpoch: "epoch-1",
      networkId: 24,
      entityType: "minecraft:drowned",
      position: {
        x: 3,
        y: 60,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    };
    driver.entityResults = [drowned];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
          || query.selector.networkId === drowned.networkId
        ? driver.entityResults
        : [];
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
        ? [blockObservation({
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          replaceable: true,
        })]
        : [];
    driver.surfaceColumns = [-8, -7, -6].flatMap((x) =>
      [-1, 0, 1].map((z) => ({
        x,
        z,
        loaded: true,
        surfaceY: 63,
        blockId: "minecraft:grass_block",
        skyLight: 15,
        blockLight: 0,
      }))
    );
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.paths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths[0]).toMatchObject({
      position: {
        y: 64,
        dimension: "minecraft:overworld",
      },
      radius: 1.5,
      policy: {
        allowMining: false,
        allowPlacing: false,
        avoidFluids: false,
        sprint: true,
      },
    });
    expect(driver.paths[0]?.position.x).toBeLessThan(0);
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  });

  it("uses bounded dynamic pathfinding instead of sprinting off a cliff", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      position: {
        x: 0,
        y: 92,
        z: 0,
        dimension: "minecraft:overworld",
      },
      counts: { "minecraft:cooked_beef": 1 },
    });
    const skeleton: BeatGameEntityObservation = {
      connectionEpoch: "epoch-1",
      networkId: 20,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 92,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    };
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.surfaceColumns = [
      {
        x: -1,
        z: 0,
        loaded: true,
        surfaceY: 77,
        blockId: "minecraft:grass_block",
        skyLight: 15,
        blockLight: 0,
      },
      ...[-9, -8, -7].flatMap((x) =>
        [-1, 0, 1].map((z) => ({
          x,
          z,
          loaded: true,
          surfaceY: 91,
          blockId: "minecraft:grass_block",
          skyLight: 15,
          blockLight: 0,
        }))
      ),
    ];

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions.some((action) =>
      action.type === "set-movement" && action.forward === true
    )).toBe(false);
    const fleeIndex = driver.tasks.findIndex((task) => task.type === "flee");
    expect(driver.tasks[fleeIndex]).toMatchObject({
      type: "flee",
      selector: { categories: [2], alive: true },
      triggerRadius: 24,
      safeDistance: 32,
    });
    expect(driver.taskPolicies[fleeIndex]).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: true,
      maxFallDistance: 3,
    });
  });

  it("evades ranged hostiles while wounded without a shield", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 15,
      counts: {
        "minecraft:wooden_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 18,
      entityType: "minecraft:bogged",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 16,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "flee")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      triggerRadius: 24,
      safeDistance: 32,
    }));
    expect(driver.tasks.some((task) =>
      task.type === "attack-nearest" || task.type === "attack-entity"
    )).toBe(false);
  });

  it("keeps closing on a ranged attacker after a nonlethal wound", async () => {
    const driver = new FakeBeatGameDriver();
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 181,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 20,
      food: 19,
      counts: { "minecraft:stone_sword": 1 },
    });
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
          || query.selector.networkId === skeleton.networkId
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.currentObservation = observation({
            health: 17,
            food: 19,
            counts: { "minecraft:stone_sword": 1 },
          });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "attack-entity")) {
        yield* Effect.sleep(1);
      }
      yield* Effect.sleep(20);
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: skeleton.networkId }),
      selectBestWeapon: true,
    }));
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  });

  it("fights a ranged route blocker bare-handed while healthy and fed", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 20,
      food: 20,
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 19,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.currentObservation = observation({
            health: 14,
            food: 16,
          });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* Effect.sleep(400);
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        networkId: 19,
        entityType: "minecraft:skeleton",
      }),
      selectBestWeapon: true,
    }));
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  });

  it("evades a distant ranged attacker instead of chasing it bare-handed", async () => {
    const driver = new FakeBeatGameDriver();
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 20,
      entityType: "minecraft:skeleton",
      position: {
        x: 15,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({ health: 20, food: 20 });
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2)
          || query.selector.networkId === skeleton.networkId
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.entityResults = [];
        }
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "flee")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      triggerRadius: 24,
      safeDistance: 32,
    }));
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  });

  it("fights a ranged hostile from a confined shaft when armed", async () => {
    const driver = new FakeBeatGameDriver();
    const shaftPosition = {
      x: 75,
      y: 62,
      z: -38,
      dimension: "minecraft:overworld",
    };
    driver.currentObservation = observation({
      health: 8,
      position: shaftPosition,
      counts: { "minecraft:stone_sword": 1 },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 17,
      entityType: "minecraft:skeleton",
      position: {
        ...shaftPosition,
        x: shaftPosition.x + 4,
        y: shaftPosition.y + 2,
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskObserver = (task) => {
      if (task.type === "attack-entity") {
        driver.entityResults = [];
        driver.currentObservation = observation({
          health: 20,
          position: shaftPosition,
          counts: { "minecraft:stone_sword": 1 },
        });
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        entityType: "minecraft:skeleton",
      }),
      selectBestWeapon: true,
    }));
    expect(driver.actions.some((action) =>
      action.type === "set-movement" && action.sprint === true
    )).toBe(false);
  });

  it("keeps its shield raised instead of fleeing a ranged fight wounded", async () => {
    const driver = new FakeBeatGameDriver();
    const bogged = {
      connectionEpoch: "epoch-1",
      networkId: 16,
      entityType: "minecraft:bogged",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 20,
      counts: {
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [bogged];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.currentObservation = observation({
            health: 10,
            position: {
              x: 20,
              y: 64,
              z: 0,
              dimension: "minecraft:overworld",
            },
            counts: {
              "minecraft:shield": 1,
              "minecraft:stone_sword": 1,
            },
          });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
      ),
    );
    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* Effect.sleep(5);
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      useOffhandShield: true,
    }));
    expect(driver.actions.some((action) =>
      action.type === "set-movement" && action.forward === true
    )).toBe(false);
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  });

  it("retreats when a shielded ranged pursuit is wounded without progress", async () => {
    const driver = new FakeBeatGameDriver();
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 161,
      entityType: "minecraft:skeleton",
      position: {
        x: 10,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    const counts = {
      "minecraft:shield": 1,
      "minecraft:stone_sword": 1,
    };
    driver.currentObservation = observation({ health: 20, counts });
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2)
          || query.selector.networkId === skeleton.networkId
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.currentObservation = observation({ health: 15, counts });
        }
        if (task.type === "flee") {
          driver.entityResults = [];
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "flee")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      useOffhandShield: true,
    }));
    const attackIndex = driver.tasks.findIndex((task) =>
      task.type === "attack-entity"
    );
    expect(driver.taskPolicies[attackIndex]).toMatchObject({
      avoidFluids: false,
    });
    const fleeIndex = driver.tasks.findIndex((task) => task.type === "flee");
    expect(fleeIndex).toBeGreaterThan(-1);
    expect(driver.taskPolicies[fleeIndex]).toMatchObject({
      avoidFluids: false,
    });
  }, 10_000);

  it("retreats from a shielded ranged fight before a lethal hit", async () => {
    const driver = new FakeBeatGameDriver();
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 17,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 20,
      counts: {
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2)
          || query.selector.networkId === skeleton.networkId
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.currentObservation = observation({
            health: 5,
            counts: {
              "minecraft:shield": 1,
              "minecraft:stone_sword": 1,
            },
          });
        }
        if (task.type === "flee") {
          driver.entityResults = [];
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      useOffhandShield: true,
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
  });

  it("retreats from a critical underground ranged fight", async () => {
    const driver = new FakeBeatGameDriver();
    const undergroundPosition = {
      x: 0,
      y: 24,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 171,
      entityType: "minecraft:skeleton",
      position: {
        ...undergroundPosition,
        x: undergroundPosition.x + 6,
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    const counts = {
      "minecraft:shield": 1,
      "minecraft:stone_sword": 1,
    };
    driver.currentObservation = observation({
      health: 20,
      position: undergroundPosition,
      counts,
    });
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2)
          || query.selector.networkId === skeleton.networkId
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.currentObservation = observation({
            health: 5,
            position: undergroundPosition,
            counts,
          });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "attack-entity")) {
        yield* Effect.sleep(1);
      }
      while (!driver.tasks.some((task) => task.type === "flee")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      useOffhandShield: true,
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
  });

  it("flees after a shielded ranged attack route fails", async () => {
    const driver = new FakeBeatGameDriver();
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 18,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 10,
      counts: {
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.entityResults = [];
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity"
            ? Effect.fail(new BeatGameDriverError({
              operation: "task.attack-entity",
              code: "unreachable",
              retryable: true,
              message: "The defensive route was blocked",
            }))
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.filter((task) => task.type === "attack-entity"))
      .toHaveLength(1);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
  });

  it("mines out of an underground trap after a ranged defense route fails", async () => {
    const driver = new FakeBeatGameDriver();
    const undergroundPosition = {
      x: 0,
      y: 60,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 181,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 61,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 20,
      position: undergroundPosition,
      counts: {
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.surfaceColumns = [{
      x: -6,
      z: 0,
      loaded: true,
      surfaceY: 70,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:forest",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity"
            ? Effect.fail(new BeatGameDriverError({
              operation: "task.attack-entity",
              code: "unreachable",
              retryable: true,
              message: "The skeleton is above the enclosed tunnel",
            }))
            : Effect.void,
        ),
      );
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        driver.entityResults = [];
        driver.currentObservation = observation({
          position,
          counts: {
            "minecraft:stone_pickaxe": 1,
            "minecraft:stone_sword": 1,
          },
        });
      });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.paths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.filter((task) => task.type === "attack-entity"))
      .toHaveLength(1);
    expect(driver.paths[0]).toEqual({
      position: {
        x: -5.5,
        y: 71,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 0.75,
      policy: expect.objectContaining({
        allowMining: true,
        allowPlacing: true,
        avoidFluids: true,
      }),
    });
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  });

  it("evades before mining upward when a ranged route fails while wounded", async () => {
    const driver = new FakeBeatGameDriver();
    const undergroundPosition = {
      x: 0,
      y: -15,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 182,
      entityType: "minecraft:skeleton",
      position: {
        x: 0,
        y: -7,
        z: 2,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    const counts = {
      "minecraft:shield": 1,
      "minecraft:stone_pickaxe": 1,
      "minecraft:stone_sword": 1,
    };
    driver.currentObservation = observation({
      health: 12,
      position: undergroundPosition,
      counts,
    });
    driver.surfaceColumns = [{
      x: -6,
      z: 0,
      loaded: true,
      surfaceY: 70,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:forest",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2)
          || query.selector.networkId === skeleton.networkId
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.entityResults = [];
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity"
            ? Effect.fail(new BeatGameDriverError({
              operation: "task.attack-entity",
              code: "unreachable",
              retryable: true,
              message: "The skeleton is firing down an enclosed shaft",
            }))
            : Effect.void,
        ),
      );
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.filter((task) => task.type === "attack-entity"))
      .toHaveLength(1);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
    expect(driver.paths).toHaveLength(0);
  });

  it("abandons a shielded ranged pursuit when a hostile group closes in", async () => {
    const driver = new FakeBeatGameDriver();
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 182,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    const zombies = [183, 184].map((networkId, index) => ({
      connectionEpoch: "epoch-1",
      networkId,
      entityType: "minecraft:zombie",
      position: {
        x: 4 + index,
        y: 64,
        z: 2,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const));
    driver.currentObservation = observation({
      health: 20,
      counts: {
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.entityResults = [skeleton, ...zombies];
        } else if (task.type === "flee") {
          driver.entityResults = [];
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.filter((task) => task.type === "attack-entity"))
      .toHaveLength(1);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
  });

  it("eats and regenerates after surviving a defensive fight", async () => {
    const driver = new FakeBeatGameDriver();
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 19,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      counts: { "minecraft:beef": 2 },
    });
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.entityResults = [];
          driver.currentObservation = observation({
            health: 1.5,
            food: 17,
            counts: { "minecraft:beef": 2 },
          });
        }
        if (task.type === "auto-eat") {
          driver.currentObservation = observation({
            health: 18,
            food: 20,
            counts: { "minecraft:beef": 1 },
          });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" || task.type === "auto-eat"
            ? Effect.void
            : Effect.never,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            let attempts = 1_000;
            while (
              !driver.tasks.some((task) => task.type === "auto-eat")
              && attempts > 0
            ) {
              attempts -= 1;
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const attackIndex = driver.tasks.findIndex((task) =>
      task.type === "attack-entity"
    );
    const eatIndex = driver.tasks.findIndex((task) => task.type === "auto-eat");
    expect(attackIndex).toBeGreaterThanOrEqual(0);
    expect(eatIndex).toBeGreaterThan(attackIndex);
    expect(driver.tasks[eatIndex]).toEqual(expect.objectContaining({
      type: "auto-eat",
      foodLevel: 20,
      maximumMeals: 1,
      completeWhenNoFood: true,
    }));
  });

  it("flees an unshielded melee group while healthy", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 20,
      counts: {
        "minecraft:cooked_beef": 1,
      },
    });
    driver.entityResults = [
      {
        connectionEpoch: "epoch-1",
        networkId: 16,
        entityType: "minecraft:zombie",
        position: {
          x: 2,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        },
        velocity: { x: 0, y: 0, z: 0 },
        alive: true,
        health: 20,
        observedAt: "2026-01-01T00:00:00.000Z",
      },
      {
        connectionEpoch: "epoch-1",
        networkId: 17,
        entityType: "minecraft:spider",
        position: {
          x: 4,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        },
        velocity: { x: 0, y: 0, z: 0 },
        alive: true,
        health: 16,
        observedAt: "2026-01-01T00:00:00.000Z",
      },
    ];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskObserver = (task) => {
      if (task.type === "flee") {
        driver.entityResults = [];
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "flee")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: {
        categories: [2],
        alive: true,
      },
    }));
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  });

  it("finishes an armed fast pursuer instead of repeatedly fleeing it", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 18,
      food: 10,
      counts: {
        "minecraft:wooden_sword": 1,
        "minecraft:porkchop": 5,
      },
    });
    const spider = {
      connectionEpoch: "epoch-1",
      networkId: 18,
      entityType: "minecraft:spider",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 16,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityResults = [
      spider,
      {
        ...spider,
        networkId: 19,
        entityType: "minecraft:zombie",
        position: { ...spider.position, x: 7 },
        health: 20,
      },
    ];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskObserver = (task) => {
      if (task.type === "attack-entity") {
        driver.entityResults = [];
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            let attempts = 3_000;
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
              && attempts > 0
            ) {
              attempts -= 1;
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        connectionEpoch: spider.connectionEpoch,
        networkId: spider.networkId,
      }),
      selectBestWeapon: true,
    }));
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  }, 10_000);

  it("flees an unshielded melee group when unable to regenerate", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 14,
      food: 6,
      counts: { "minecraft:wooden_sword": 1 },
    });
    const zombie = {
      connectionEpoch: "epoch-1",
      networkId: 20,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityResults = [
      zombie,
      {
        ...zombie,
        networkId: 21,
        position: { ...zombie.position, x: 7 },
      },
    ];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
  }, 10_000);

  it("flees an unshielded ranged ambush before taking a hit", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 20,
      counts: { "minecraft:wooden_sword": 1 },
    });
    driver.entityResults = [
      {
        connectionEpoch: "epoch-1",
        networkId: 161,
        entityType: "minecraft:zombie",
        position: {
          x: 6,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        },
        velocity: { x: 0, y: 0, z: 0 },
        alive: true,
        health: 20,
        observedAt: "2026-01-01T00:00:00.000Z",
      },
      {
        connectionEpoch: "epoch-1",
        networkId: 162,
        entityType: "minecraft:skeleton",
        position: {
          x: 12,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        },
        velocity: { x: 0, y: 0, z: 0 },
        alive: true,
        health: 20,
        observedAt: "2026-01-01T00:00:00.000Z",
      },
    ];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.surfaceColumns = Array.from({ length: 18 }, (_, index) =>
      index + 1
    ).flatMap((distance) =>
      [-2, -1, 0, 1, 2].map((z) => ({
        x: -distance,
        z,
        loaded: true,
        surfaceY: 63,
        blockId: "minecraft:grass_block",
        skyLight: 15,
        blockLight: 0,
      }))
    );
    driver.taskObserver = (task) => {
      if (task.type === "flee") {
        driver.entityResults = [];
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            let attempts = 3_000;
            while (
              !driver.tasks.some((task) => task.type === "flee")
              && attempts > 0
            ) {
              attempts -= 1;
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: {
        categories: [2],
        alive: true,
      },
      triggerRadius: 24,
      safeDistance: 32,
    }));
    expect(driver.actions).toContainEqual({
      type: "set-movement",
      left: true,
      right: false,
    });
    expect(driver.actions).toContainEqual({
      type: "set-movement",
      left: false,
      right: true,
    });
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  }, 10_000);

  it("fights an underground skeleton instead of retreating through a tunnel", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 11,
      food: 13,
      position: {
        x: 0,
        y: 30,
        z: 0,
        dimension: "minecraft:overworld",
      },
      counts: { "minecraft:stone_sword": 1 },
    });
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 163,
      entityType: "minecraft:skeleton",
      position: {
        x: 8,
        y: 30,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskObserver = (task) => {
      if (task.type === "attack-entity") {
        driver.entityResults = [];
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) =>
              task.type === "attack-entity"
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        connectionEpoch: skeleton.connectionEpoch,
        networkId: skeleton.networkId,
      }),
      selectBestWeapon: true,
    }));
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  }, 10_000);

  it("knocks back and escapes a close spider when bare-handed and underfed", async () => {
    const driver = new FakeBeatGameDriver();
    const spiders = [
      {
        connectionEpoch: "epoch-1",
        networkId: 51,
        entityType: "minecraft:spider",
        position: {
          x: 2,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        },
        velocity: { x: 0, y: 0, z: 0 },
        alive: true,
        health: 16,
        observedAt: "2026-01-01T00:00:00.000Z",
      },
      {
        connectionEpoch: "epoch-1",
        networkId: 52,
        entityType: "minecraft:spider",
        position: {
          x: 5,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        },
        velocity: { x: 0, y: 0, z: 0 },
        alive: true,
        health: 16,
        observedAt: "2026-01-01T00:00:00.000Z",
      },
    ];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" || task.type === "flee"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) =>
              task.type === "collect-blocks"
            )) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({ health: 15, food: 14 });
            driver.entityResults = spiders;
            let attempts = 3_000;
            while (
              !driver.tasks.some((task) => task.type === "flee")
              && attempts > 0
            ) {
              attempts -= 1;
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: {
        categories: [2],
        alive: true,
      },
    }));
    expect(driver.actions).toContainEqual({
      type: "attack-entity",
      connectionEpoch: "epoch-1",
      networkId: 51,
      sprinting: true,
    });
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  }, 10_000);

  it("chains direct sprints before replanning around a fast pursuer", async () => {
    const driver = new FakeBeatGameDriver();
    const spider = {
      connectionEpoch: "epoch-1",
      networkId: 521,
      entityType: "minecraft:spider",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 16,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({ health: 9.5, food: 14 });
    driver.entityResults = [spider];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
          || query.selector.networkId === spider.networkId
        ? driver.entityResults
        : [];
    driver.surfaceQueryResolver = (center, radius) =>
      Array.from(
        { length: Math.ceil(radius) * 2 + 1 },
        (_, offset) => ({
          x: Math.floor(center.x) - Math.ceil(radius) + offset,
          z: 0,
          dimension: center.dimension,
          loaded: true,
          surfaceY: 63,
          blockId: "minecraft:stone",
          skyLight: 15,
          blockLight: 0,
        }),
      );
    let directSprints = 0;
    driver.actionObserver = (action) => {
      if (
        action.type !== "set-movement"
        || action.forward !== true
        || action.sprint !== true
      ) {
        return;
      }
      directSprints += 1;
      driver.entityResults = [{
        ...spider,
        position: {
          ...spider.position,
          x: directSprints === 1 ? 13 : 25,
        },
      }];
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      let attempts = 5_000;
      while (directSprints < 2 && attempts > 0) {
        attempts -= 1;
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(directSprints).toBe(2);
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
    expect(driver.actions.filter((action) =>
      action.type === "attack-entity"
      && action.networkId === spider.networkId
    )).toHaveLength(0);
  }, 10_000);

  it("turns on a bare-handed fast pursuer after it wounds an active escape", async () => {
    const driver = new FakeBeatGameDriver();
    const distantSpider = {
      connectionEpoch: "epoch-1",
      networkId: 53,
      entityType: "minecraft:spider",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 16,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
          || query.selector.networkId === distantSpider.networkId
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" || task.type === "flee"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) =>
              task.type === "collect-blocks"
            )) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({ health: 15, food: 14 });
            driver.entityResults = [distantSpider];
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({
              health: 13,
              food: 14,
            });
            driver.entityResults = [{
              ...distantSpider,
              position: { ...distantSpider.position, x: 2 },
            }];
            while (!driver.tasks.some((task) =>
              task.type === "attack-entity"
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.filter((task) => task.type === "flee").length)
      .toBeGreaterThanOrEqual(1);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        connectionEpoch: distantSpider.connectionEpoch,
        networkId: distantSpider.networkId,
      }),
      selectBestWeapon: true,
    }));
  }, 10_000);

  it("turns on a bare-handed spider that catches an ambush escape", async () => {
    const driver = new FakeBeatGameDriver();
    const spider = {
      connectionEpoch: "epoch-1",
      networkId: 531,
      entityType: "minecraft:spider",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 16,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    const skeleton = {
      ...spider,
      networkId: 532,
      entityType: "minecraft:skeleton",
      position: { ...spider.position, x: 12 },
      health: 20,
    } as const;
    driver.entityQueryResolver = (query) => {
      if (query.selector.networkId !== undefined) {
        return driver.entityResults.filter((entity) =>
          entity.networkId === query.selector.networkId
        );
      }
      return query.selector.categories?.includes(2)
        ? driver.entityResults
        : [];
    };
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
              || task.type === "flee"
              || task.type === "attack-entity"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) =>
              task.type === "collect-blocks"
            )) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({ health: 18, food: 8 });
            driver.entityResults = [spider, skeleton];
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({ health: 15, food: 8 });
            driver.entityResults = [{
              ...spider,
              position: { ...spider.position, x: 2 },
            }, skeleton];
            while (!driver.tasks.some((task) =>
              task.type === "attack-entity"
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        connectionEpoch: spider.connectionEpoch,
        networkId: spider.networkId,
      }),
      selectBestWeapon: true,
    }));
  }, 10_000);

  it("knocks back a fast pursuer before it lands another hit", async () => {
    const driver = new FakeBeatGameDriver();
    const distantSpider = {
      connectionEpoch: "epoch-1",
      networkId: 54,
      entityType: "minecraft:spider",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 16,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
          || query.selector.networkId === distantSpider.networkId
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" || task.type === "flee"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 500 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) =>
              task.type === "collect-blocks"
            )) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({ health: 6, food: 6 });
            driver.entityResults = [distantSpider];
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            driver.entityResults = [{
              ...distantSpider,
              position: { ...distantSpider.position, x: 2 },
            }];
            while (!driver.actions.some((action) =>
              action.type === "attack-entity"
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.currentObservation.player.health).toBe(6);
    expect(driver.actions).toContainEqual({
      type: "attack-entity",
      connectionEpoch: distantSpider.connectionEpoch,
      networkId: distantSpider.networkId,
      sprinting: true,
    });
  }, 10_000);

  it("knocks back a zombie that catches a bare-handed escape", async () => {
    const driver = new FakeBeatGameDriver();
    const distantZombie = {
      connectionEpoch: "epoch-1",
      networkId: 55,
      entityType: "minecraft:zombie",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
          || query.selector.networkId === distantZombie.networkId
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" || task.type === "flee"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) =>
              task.type === "collect-blocks"
            )) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({ health: 8, food: 14 });
            driver.entityResults = [distantZombie];
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({ health: 6, food: 14 });
            driver.entityResults = [{
              ...distantZombie,
              position: { ...distantZombie.position, x: 2 },
            }];
            while (!driver.actions.some((action) =>
              action.type === "attack-entity"
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions).toContainEqual({
      type: "attack-entity",
      connectionEpoch: distantZombie.connectionEpoch,
      networkId: distantZombie.networkId,
      sprinting: true,
    });
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  }, 10_000);

  it("turns on a close zombie that catches a healthy armed escape", async () => {
    const driver = new FakeBeatGameDriver();
    const zombie = {
      connectionEpoch: "epoch-1",
      networkId: 54,
      entityType: "minecraft:zombie",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 14,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
          || query.selector.networkId === zombie.networkId
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
              || task.type === "flee"
              || task.type === "attack-entity"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) =>
              task.type === "collect-blocks"
            )) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({
              health: 8,
              food: 14,
              counts: { "minecraft:wooden_sword": 1 },
            });
            driver.entityResults = [zombie];
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            driver.entityResults = [{
              ...zombie,
              position: { ...zombie.position, x: 2 },
            }];
            driver.currentObservation = observation({
              health: 18,
              food: 14,
              counts: { "minecraft:wooden_sword": 1 },
            });
            while (!driver.tasks.some((task) =>
              task.type === "attack-entity"
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.filter((task) => task.type === "flee")).toHaveLength(1);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        connectionEpoch: zombie.connectionEpoch,
        networkId: zombie.networkId,
      }),
      selectBestWeapon: true,
    }));
  }, 10_000);

  it("knocks back and flees a close spider at lethal health", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 2,
      position: {
        x: 0,
        y: 80,
        z: 0,
        dimension: "minecraft:overworld",
      },
      counts: {
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 18,
      entityType: "minecraft:spider",
      position: {
        x: 2,
        y: 80,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 16,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-nearest" || task.type === "attack-entity") {
          driver.entityResults = [];
        } else if (task.type === "flee") {
          driver.entityResults = [];
        }
      });
    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "flee")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions).toContainEqual({
      type: "attack-entity",
      connectionEpoch: "epoch-1",
      networkId: 18,
      sprinting: true,
    });
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  });

  it("keeps fighting a close spider after taking a lethal wound", async () => {
    const driver = new FakeBeatGameDriver();
    const spider = {
      connectionEpoch: "epoch-1",
      networkId: 53,
      entityType: "minecraft:spider",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 16,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      counts: { "minecraft:wooden_sword": 1 },
    });
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.currentObservation = observation({
            health: 5.5,
            counts: { "minecraft:wooden_sword": 1 },
          });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" || task.type === "attack-entity"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            driver.entityResults = [spider];
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* Effect.sleep(20);
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        networkId: spider.networkId,
        entityType: spider.entityType,
      }),
      selectBestWeapon: true,
    }));
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  });

  it("hits a close spider directly when pursuit pathfinding fails", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: { "minecraft:stone_sword": 1 },
    });
    const spider = {
      connectionEpoch: "epoch-1",
      networkId: 54,
      entityType: "minecraft:spider",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 16,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (task.type === "collect-blocks") {
        return Effect.never;
      }
      if (task.type === "attack-entity") {
        return Effect.fail(new BeatGameDriverError({
          operation: "task.attack-entity",
          code: "unreachable",
          retryable: true,
          message: "Unable to reach the adjacent spider",
        }));
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            driver.entityResults = [spider];
            while (!driver.actions.some((action) =>
              action.type === "attack-entity"
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions).toContainEqual({
      type: "select-item",
      selector: { itemIds: [
        "minecraft:netherite_sword",
        "minecraft:diamond_sword",
        "minecraft:iron_sword",
        "minecraft:stone_sword",
        "minecraft:wooden_sword",
      ] },
    });
    expect(driver.actions).toContainEqual({
      type: "attack-entity",
      connectionEpoch: spider.connectionEpoch,
      networkId: spider.networkId,
      sprinting: true,
    });
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  });

  it("defends against a hostile that approaches during recovery", async () => {
    const driver = new FakeBeatGameDriver();
    const zombie = {
      connectionEpoch: "epoch-1",
      networkId: 18,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    const rottenFlesh = {
      connectionEpoch: "epoch-1",
      networkId: 19,
      entityType: "minecraft:item",
      itemId: "minecraft:rotten_flesh",
      itemCount: 1,
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 5,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 20,
      counts: { "minecraft:cooked_beef": 1 },
    });
    let hostileQueries = 0;
    let zombieNearby = false;
    let zombieDefeated = false;
    driver.entityQueryResolver = (query) => {
      if (query.selector.entityTypes?.includes("minecraft:item")) {
        return zombieDefeated ? [rottenFlesh] : [];
      }
      if (!query.selector.categories?.includes(2)) {
        return [];
      }
      hostileQueries += 1;
      if (hostileQueries >= 2 && !zombieDefeated) {
        zombieNearby = true;
      }
      return zombieNearby ? [zombie] : [];
    };
    driver.taskObserver = (task) => {
      if (task.type === "attack-nearest") {
        zombieDefeated = true;
        zombieNearby = false;
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "attack-nearest")
            ) {
              yield* Effect.sleep(1);
            }
            while (
              !driver.paths.some(({ position }) =>
                position.x === rottenFlesh.position.x
                && position.y === rottenFlesh.position.y
                && position.z === rottenFlesh.position.z
              )
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(hostileQueries).toBeGreaterThanOrEqual(2);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-nearest",
      selector: {
        categories: [2],
        alive: true,
      },
      selectBestWeapon: true,
    }));
    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: rottenFlesh.position,
      radius: 1.5,
      policy: expect.objectContaining({
        allowPlacing: false,
        avoidFluids: true,
      }),
    }));
  });

  it("evades a visible witch before entering potion range", async () => {
    const driver = new FakeBeatGameDriver();
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 14,
      entityType: "minecraft:witch",
      position: {
        x: 15,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskObserver = (task) => {
      if (task.type === "attack-nearest") {
        driver.entityResults = [];
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "flee")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.some((task) =>
      task.type === "attack-nearest" || task.type === "attack-entity"
    )).toBe(false);
    const fleeIndex = driver.tasks.findIndex((task) => task.type === "flee");
    expect(driver.tasks[fleeIndex]).toEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
      triggerRadius: 24,
      safeDistance: 32,
    }));
    expect(driver.taskPolicies[fleeIndex]).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: true,
      maxFallDistance: 3,
      sprint: true,
    });
  });

  it("evades a ranged hostile at low health without a shield", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      counts: {
        "minecraft:cooked_beef": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 16,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "flee")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.some((task) =>
      task.type === "attack-nearest" || task.type === "attack-entity"
    )).toBe(false);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
      triggerRadius: 24,
      safeDistance: 32,
    }));
  });

  it("stops an escape route once its threat is no longer nearby", async () => {
    const driver = new FakeBeatGameDriver();
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 17,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({ health: 8 });
    driver.entityResults = [skeleton];
    let targetNearby = true;
    driver.entityQueryResolver = (query) =>
      query.selector.networkId === skeleton.networkId
        ? targetNearby ? [skeleton] : []
        : query.selector.categories?.includes(2)
        ? driver.entityResults
        : [];
    let interruptedEscapes = 0;
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        driver.taskObserver(task);
        if (task.type === "flee") {
          targetNearby = false;
        }
      }).pipe(
        Effect.zipRight(task.type === "flee" ? Effect.never : Effect.void),
        Effect.onInterrupt(() =>
          Effect.sync(() => {
            if (task.type === "flee") {
              interruptedEscapes += 1;
            }
          })
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (interruptedEscapes === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
      triggerRadius: 24,
      safeDistance: 32,
    }));
    expect(interruptedEscapes).toBe(1);
    expect(driver.entityQueries).toContainEqual(expect.objectContaining({
      radius: 32,
      selector: {
        networkId: skeleton.networkId,
        alive: true,
      },
      maximumResults: 1,
    }));
  });

  it("interrupts work and fights back bare-handed after taking damage", async () => {
    const driver = new FakeBeatGameDriver();
    const attacker = {
      connectionEpoch: "epoch-1",
      networkId: 23,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        driver.taskObserver(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
            ? Effect.never
            : Effect.succeed({}),
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            driver.entityResults = [attacker];
            driver.currentObservation = observation({ health: 19 });
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.entityQueries).toContainEqual(expect.objectContaining({
      radius: 24,
      selector: {
        categories: [2],
        alive: true,
        requireLineOfSight: true,
      },
      maximumResults: 32,
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        connectionEpoch: attacker.connectionEpoch,
        networkId: attacker.networkId,
      }),
      selectBestWeapon: true,
    }));
    const defensiveAttack = driver.tasks.find((task) =>
      task.type === "attack-entity"
    );
    expect(defensiveAttack).not.toHaveProperty("maximumAttacks");
    const attackIndex = driver.tasks.findIndex((task) =>
      task.type === "attack-entity"
    );
    expect(driver.taskPolicies[attackIndex]).toEqual(expect.objectContaining({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: true,
      maxSearchTimeMs: 3_000,
    }));
    expect(driver.maximumActiveControlScopes).toBe(1);
  });

  it("evades a ranged drowned before it can keep dealing damage", async () => {
    const driver = new FakeBeatGameDriver();
    const drowned = {
      connectionEpoch: "epoch-1",
      networkId: 54,
      entityType: "minecraft:drowned",
      position: {
        x: 13,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
          || query.selector.networkId === drowned.networkId
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" || task.type === "flee"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            driver.entityResults = [drowned];
            driver.currentObservation = observation({ health: 15 });
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          }).pipe(Effect.timeoutFail({
            duration: "8 seconds",
            onTimeout: () => new Error("Timed out waiting for drowned evasion"),
          }))
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
      triggerRadius: 24,
      safeDistance: 32,
    }));
    const fleeIndex = driver.tasks.findIndex((task) => task.type === "flee");
    expect(driver.taskPolicies[fleeIndex]).toEqual(expect.objectContaining({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: false,
      sprint: true,
    }));
  }, 10_000);

  it("stops pursuing an attacker beyond the defensive leash", async () => {
    const driver = new FakeBeatGameDriver();
    const attacker = {
      connectionEpoch: "epoch-1",
      networkId: 24,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    let interruptedDefensiveAttacks = 0;
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        driver.taskObserver(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
            ? Effect.never
            : task.type === "attack-entity"
            ? Effect.never.pipe(
              Effect.onInterrupt(() =>
                Effect.sync(() => {
                  interruptedDefensiveAttacks += 1;
                })
              ),
            )
            : Effect.succeed({}),
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            driver.entityResults = [attacker];
            driver.currentObservation = observation({ health: 19 });
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({
              health: 19,
              position: { x: 13 },
            });
            while (interruptedDefensiveAttacks === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(interruptedDefensiveAttacks).toBe(1);
    const attackIndex = driver.tasks.findIndex((task) =>
      task.type === "attack-entity"
    );
    expect(driver.taskPolicies[attackIndex]).toEqual(expect.objectContaining({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: true,
    }));
  }, 10_000);

  it("interrupts work to evade multiple attackers after taking damage", async () => {
    const driver = new FakeBeatGameDriver();
    const attackers = [
      {
        connectionEpoch: "epoch-1",
        networkId: 27,
        entityType: "minecraft:zombie",
        position: {
          x: 2,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        },
        velocity: { x: 0, y: 0, z: 0 },
        alive: true,
        health: 20,
        observedAt: "2026-01-01T00:00:01.000Z",
      },
      {
        connectionEpoch: "epoch-1",
        networkId: 28,
        entityType: "minecraft:spider",
        position: {
          x: 3,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        },
        velocity: { x: 0, y: 0, z: 0 },
        alive: true,
        health: 16,
        observedAt: "2026-01-01T00:00:01.000Z",
      },
    ] as const;
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        driver.taskObserver(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
            ? Effect.never
            : Effect.succeed({}),
        ),
      );
    driver.taskObserver = (task) => {
      if (task.type === "flee") {
        driver.entityResults = [];
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            driver.entityResults = [...attackers];
            driver.currentObservation = observation({ health: 19 });
            while (
              !driver.tasks.some((task) => task.type === "flee")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
      triggerRadius: 12,
      safeDistance: 24,
    }));
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  });

  it("leaves a nearby neutral Enderman alone", async () => {
    const driver = new FakeBeatGameDriver();
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 25,
      entityType: "minecraft:enderman",
      position: {
        x: 3,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 40,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        driver.taskObserver(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
            ? Effect.never
            : Effect.succeed({}),
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            let attempts = 1_000;
            while (
              !driver.entityQueries.some((query) =>
                query.selector.categories?.includes(2)
              )
              && attempts > 0
            ) {
              attempts -= 1;
              yield* Effect.sleep(1);
            }
            yield* Effect.sleep(10);
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.entityQueries).toContainEqual(expect.objectContaining({
      selector: expect.objectContaining({
        categories: [2],
        alive: true,
      }),
    }));
    expect(driver.tasks.some((task) =>
      task.type === "attack-nearest" || task.type === "attack-entity"
    )).toBe(false);
  });

  it("escapes an attacking Enderman into nearby water", async () => {
    const driver = new FakeBeatGameDriver();
    const attacker = {
      connectionEpoch: "epoch-1",
      networkId: 26,
      entityType: "minecraft:enderman",
      position: {
        x: 3,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 40,
      target: { connectionEpoch: "epoch-1", networkId: 1 },
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water")
        ? [blockObservation({
          x: 0,
          y: 63,
          z: 3,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:water" })]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        driver.taskObserver(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
            ? Effect.never
            : Effect.succeed({}),
        ),
      );
    driver.taskObserver = (task) => {
      if (task.type === "flee") {
        driver.entityResults = [];
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            driver.entityResults = [attacker];
            driver.currentObservation = observation({ health: 18 });
            while (!driver.paths.some(({ position }) =>
              position.x === 0.5
              && position.y === 63.5
              && position.z === 3.5
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: {
        x: 0.5,
        y: 63.5,
        z: 3.5,
        dimension: "minecraft:overworld",
      },
      radius: 1.5,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        avoidFluids: false,
      }),
    }));
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  });

  it("uses a bare-handed knockback without sprinting into unknown terrain", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      counts: { "minecraft:cooked_beef": 1 },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 24,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskObserver = (task) => {
      if (task.type === "attack-nearest") {
        driver.entityResults = [];
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "flee")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions).toContainEqual({
      type: "attack-entity",
      connectionEpoch: "epoch-1",
      networkId: 24,
      sprinting: true,
    });
    expect(driver.actions.some((action) =>
      action.type === "set-movement" && action.forward === true
    )).toBe(false);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
  });

  it("escapes a close zombie at lethal health despite having a weapon", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 4,
      counts: {
        "minecraft:cooked_beef": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 25,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "flee")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions).toContainEqual({
      type: "attack-entity",
      connectionEpoch: "epoch-1",
      networkId: 25,
      sprinting: true,
    });
    expect(driver.tasks.some((task) =>
      task.type === "attack-nearest" || task.type === "attack-entity"
    )).toBe(false);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: {
        categories: [2],
        alive: true,
      },
    }));
  });

  it("repeats knockback instead of committing to a zombie at low health", async () => {
    const driver = new FakeBeatGameDriver();
    let zombie: BeatGameEntityObservation = {
      connectionEpoch: "epoch-1",
      networkId: 25,
      entityType: "minecraft:zombie",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    };
    driver.currentObservation = observation({
      health: 8,
      counts: {
        "minecraft:cooked_beef": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.entityResults = [zombie];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
          || query.selector.networkId === zombie.networkId
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          zombie = {
            ...zombie,
            position: { ...zombie.position, x: 2 },
          };
          driver.entityResults = [zombie];
        }
      }).pipe(
        Effect.zipRight(task.type === "flee" ? Effect.never : Effect.void),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        driver.actions.filter((action) => action.type === "attack-entity")
            .length < 2
        && !driver.tasks.some((task) => task.type === "attack-entity")
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(
      driver.actions.filter((action) => action.type === "attack-entity"),
    ).toHaveLength(2);
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: { categories: [2], alive: true },
    }));
  }, 10_000);

  it("dynamically replans an escape from a pursuing zombie", async () => {
    const driver = new FakeBeatGameDriver();
    const zombie = {
      connectionEpoch: "epoch-1",
      networkId: 53,
      entityType: "minecraft:zombie",
      position: {
        x: 4,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({ health: 4 });
    driver.entityResults = [zombie];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2)
          || query.selector.networkId === zombie.networkId
        ? driver.entityResults
        : [];

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: {
        categories: [2],
        alive: true,
      },
      triggerRadius: 12,
      safeDistance: 24,
      completeWhenSafe: true,
    }));
    expect(driver.xzPaths).toHaveLength(0);
  });

  it("fights an armed close zombie while healthy", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 20,
      counts: {
        "minecraft:cooked_beef": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 26,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) =>
              task.type === "attack-nearest" || task.type === "attack-entity"
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        connectionEpoch: "epoch-1",
        networkId: 26,
      }),
    }));
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(false);
  });

  it("disengages from a barehanded defense after the first wound", async () => {
    const driver = new FakeBeatGameDriver();
    const zombie = {
      connectionEpoch: "epoch-1",
      networkId: 25,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({ health: 20 });
    driver.entityResults = [zombie];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.currentObservation = observation({ health: 17.5 });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );
    const resolvePath = driver.pathResolver;
    driver.pathResolver = (position, radius, policy) =>
      resolvePath(position, radius, policy).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            driver.entityResults = [];
          })
        ),
      );
    const resolveXZPath = driver.xzPathResolver;
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      resolveXZPath(x, z, dimension, radius, policy).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            driver.entityResults = [];
          })
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) =>
              task.type === "attack-nearest" || task.type === "attack-entity"
            )) {
              yield* Effect.sleep(1);
            }
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: zombie.networkId }),
    }));
    expect(driver.tasks.some((task) => task.type === "flee")).toBe(true);
    expect(driver.paths).toHaveLength(0);
    expect(driver.xzPaths).toHaveLength(0);
  });

  it("disengages from an armed close melee defense after a lethal wound", async () => {
    const driver = new FakeBeatGameDriver();
    const zombie = {
      connectionEpoch: "epoch-1",
      networkId: 26,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 20,
      counts: { "minecraft:wooden_sword": 1 },
    });
    driver.entityResults = [zombie];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.currentObservation = observation({
            health: 7,
            counts: { "minecraft:wooden_sword": 1 },
          });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );
    const resolvePath = driver.pathResolver;
    driver.pathResolver = (position, radius, policy) =>
      resolvePath(position, radius, policy).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            driver.entityResults = [];
          })
        ),
      );
    const resolveXZPath = driver.xzPathResolver;
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      resolveXZPath(x, z, dimension, radius, policy).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            driver.entityResults = [];
          })
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) =>
              task.type === "attack-nearest" || task.type === "attack-entity"
            )) {
              yield* Effect.sleep(1);
            }
            while (!driver.tasks.some((task) => task.type === "flee")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: zombie.networkId }),
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: {
        categories: [2],
        alive: true,
      },
    }));
    expect(driver.actions).toContainEqual({
      type: "attack-entity",
      connectionEpoch: zombie.connectionEpoch,
      networkId: zombie.networkId,
      sprinting: true,
    });
  });

  it("disengages from a drowned at ocean level after heavy damage", async () => {
    const driver = new FakeBeatGameDriver();
    const position = {
      x: 0,
      y: 61,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const drowned = {
      connectionEpoch: "epoch-1",
      networkId: 27,
      entityType: "minecraft:drowned",
      position: { ...position, x: 2 },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 20,
      position,
      counts: { "minecraft:wooden_sword": 1 },
    });
    driver.surfaceColumns = Array.from({ length: 10 }, (_, index) => ({
      x: -(index + 1),
      z: 0,
      loaded: true,
      surfaceY: 60,
      blockId: "minecraft:grass_block",
      skyLight: 15,
      blockLight: 0,
    }));
    driver.entityResults = [drowned];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.currentObservation = observation({
            health: 7,
            position,
            counts: { "minecraft:wooden_sword": 1 },
          });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );
    const resolvePath = driver.pathResolver;
    driver.pathResolver = (target, radius, policy) =>
      resolvePath(target, radius, policy).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            driver.entityResults = [];
          })
        ),
      );
    const resolveXZPath = driver.xzPathResolver;
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      resolveXZPath(x, z, dimension, radius, policy).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            driver.entityResults = [];
          })
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "flee")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "flee",
      selector: {
        categories: [2],
        alive: true,
      },
    }));
    expect(driver.actions).toContainEqual({
      type: "set-movement",
      forward: true,
      jump: true,
      sprint: true,
    });
  });

  it("does not preemptively flee from a distant melee hostile while healthy", async () => {
    const driver = new FakeBeatGameDriver();
    const spider = {
      connectionEpoch: "epoch-1",
      networkId: 242,
      entityType: "minecraft:spider",
      position: {
        x: 12,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 16,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({ health: 20 });
    driver.entityResults = [spider];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    const resolvePath = driver.pathResolver;
    driver.pathResolver = (position, radius, policy) =>
      resolvePath(position, radius, policy).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            driver.entityResults = [];
          })
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.entityQueries.some((query) =>
                query.selector.requireLineOfSight === true
              )
            ) {
              yield* Effect.sleep(1);
            }
            yield* Effect.sleep(5);
            yield* run.stop;
          })
        ),
      ),
    ));

    expect(driver.entityQueries).toContainEqual(expect.objectContaining({
      radius: 24,
      selector: {
        categories: [2],
        alive: true,
        requireLineOfSight: true,
      },
    }));
    expect(driver.paths).toHaveLength(0);
    expect(driver.actions.some((action) => action.type === "attack-entity"))
      .toBe(false);
  });

  it("does not abandon the surface to pursue a hostile far below", async () => {
    const driver = new FakeBeatGameDriver();
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 243,
      entityType: "minecraft:skeleton",
      position: {
        x: 4,
        y: 53,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({
      position: {
        x: 0,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      counts: { "minecraft:wooden_sword": 1 },
    });
    driver.entityResults = [skeleton];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.entityQueries.some((query) =>
                query.selector.requireLineOfSight === true
              )
            ) {
              yield* Effect.sleep(1);
            }
            yield* Effect.sleep(5);
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.some((task) =>
      task.type === "attack-nearest"
      || task.type === "attack-entity"
      || task.type === "flee"
    )).toBe(false);
  });

  it("keeps using knockback without sprinting when no escape route exists", async () => {
    const driver = new FakeBeatGameDriver();
    const attacker = {
      connectionEpoch: "epoch-1",
      networkId: 241,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) ? driver.entityResults : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
            ? Effect.never
            : task.type === "flee"
            ? Effect.fail(new BeatGameDriverError({
              operation: "task.flee",
              code: "unreachable",
              retryable: true,
              message: "No safe flee route exists",
            }))
            : Effect.succeed({}),
        ),
      );
    driver.pathResolver = () =>
      Effect.fail(new BeatGameDriverError({
        operation: "pathfind",
        code: "unreachable",
        retryable: true,
        message: "No safe escape route exists",
      }));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            driver.entityResults = [attacker];
            driver.currentObservation = observation({ health: 3 });
            while (
              driver.actions.filter((action) =>
                action.type === "attack-entity"
              ).length < 2
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(
      driver.actions.filter((action) => action.type === "attack-entity")
        .length,
    ).toBeGreaterThanOrEqual(2);
    expect(driver.actions.some((action) =>
      action.type === "set-movement" && action.forward === true
    )).toBe(false);
    expect(driver.tasks.some((task) => task.type === "attack-nearest"))
      .toBe(false);
  });

  it("replans when a defensive target becomes unreachable", async () => {
    const driver = new FakeBeatGameDriver();
    const attacker = {
      connectionEpoch: "epoch-1",
      networkId: 25,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        driver.taskObserver(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
            ? Effect.never
            : task.type === "attack-nearest"
            ? Effect.sync(() => {
              driver.entityResults = [];
            }).pipe(
              Effect.zipRight(Effect.fail(new BeatGameDriverError({
                operation: "task.attack-nearest",
                code: "unreachable",
                retryable: true,
                message: "Unable to reach the target entity",
              }))),
            )
            : Effect.succeed({}),
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              driver.tasks.filter((task) =>
                task.type === "collect-blocks"
              ).length < 1
            ) {
              yield* Effect.sleep(1);
            }
            driver.entityResults = [attacker];
            while (
              driver.tasks.filter((task) =>
                task.type === "collect-blocks"
              ).length < 2
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-nearest",
      selector: {
        categories: [2],
        alive: true,
      },
      sprinting: true,
    }));
    expect(driver.tasks.filter((task) =>
      task.type === "collect-blocks"
    )).toHaveLength(2);
  });

  it("surfaces before recovering after an escape ends underwater", async () => {
    const driver = new FakeBeatGameDriver();
    const skeleton = {
      connectionEpoch: "epoch-1",
      networkId: 251,
      entityType: "minecraft:skeleton",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    const recoveryTrace: string[] = [];
    driver.currentObservation = observation({
      counts: {
        "minecraft:cooked_beef": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
          || query.selector.networkId === skeleton.networkId
        ? driver.entityResults
        : [];
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
          && driver.currentObservation.player.position.y < 63
        ? [blockObservation({
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
        })]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        recoveryTrace.push(`task:${task.type}`);
        if (task.type === "flee") {
          driver.entityResults = [];
          driver.currentObservation = observation({
            air: 199,
            food: 19,
            health: 10,
            position: { x: 12, y: 56, z: 0 },
            counts: {
              "minecraft:cooked_beef": 1,
              "minecraft:stone_sword": 1,
            },
          });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" ? Effect.never : Effect.void,
        ),
      );
    driver.actionObserver = (action) => {
      if (action.type === "look") {
        driver.currentObservation = {
          ...driver.currentObservation,
          player: {
            ...driver.currentObservation.player,
            rotation: { yaw: action.yaw, pitch: action.pitch },
          },
        };
        if (action.pitch === -90) {
          recoveryTrace.push("ascend");
        }
        return;
      }
      if (
        action.type === "set-movement"
        && action.forward === true
        && action.jump === true
        && driver.currentObservation.player.rotation.pitch === -90
      ) {
        driver.currentObservation = observation({
          air: 300,
          food: 19,
          health: 10,
          position: { x: 12, y: 64, z: 0 },
          counts: {
            "minecraft:cooked_beef": 1,
            "minecraft:stone_sword": 1,
          },
        });
      }
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "collect-blocks")) {
        yield* Effect.sleep(1);
      }
      driver.entityResults = [skeleton];
      driver.currentObservation = observation({
        health: 10,
        counts: {
          "minecraft:cooked_beef": 1,
          "minecraft:stone_sword": 1,
        },
      });
      while (!recoveryTrace.includes("ascend")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    const fleeIndex = recoveryTrace.indexOf("task:flee");
    const ascentIndex = recoveryTrace.indexOf("ascend");
    const eatIndex = recoveryTrace.indexOf("task:auto-eat");
    expect(fleeIndex).toBeGreaterThanOrEqual(0);
    expect(ascentIndex).toBeGreaterThan(fleeIndex);
    expect(eatIndex === -1 || eatIndex > ascentIndex).toBe(true);
  }, 10_000);

  it("interrupts work and swims upward before running out of air", async () => {
    const driver = new FakeBeatGameDriver();
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
        ? [blockObservation({
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
        })]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" ? Effect.never : Effect.succeed({}),
        ),
      );
    driver.actionObserver = (action) => {
      if (action.type === "set-movement" && action.jump === true) {
        driver.currentObservation = observation({ air: 300 });
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({ air: 100 });
            while (
              !driver.actions.some((action) =>
                action.type === "set-movement" && action.jump === true
              )
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions).toContainEqual({
      type: "look",
      yaw: 0,
      pitch: -90,
    });
    expect(driver.actions).toContainEqual({
      type: "set-movement",
      forward: true,
      jump: true,
      sprint: true,
    });
    expect(driver.actions).toContainEqual({ type: "reset-movement" });
  });

  it("swims directly to shore when an obstructed ascent stalls", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = [-1, 0, 1].map((z) => ({
      x: 4,
      z,
      loaded: true,
      surfaceY: 64,
      blockId: "minecraft:grass_block",
      skyLight: 15,
      blockLight: 0,
    }));
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
          && driver.currentObservation.player.position.x < 4
        ? [blockObservation({
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
        })]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" ? Effect.never : Effect.void,
        ),
      );
    let resolveReachedShore!: () => void;
    const reachedShore = new Promise<void>((resolve) => {
      resolveReachedShore = resolve;
    });
    driver.actionObserver = (action) => {
      const current = driver.currentObservation;
      if (action.type === "look") {
        driver.currentObservation = {
          ...current,
          player: {
            ...current.player,
            rotation: {
              yaw: action.yaw,
              pitch: action.pitch,
            },
          },
        };
        return;
      }
      if (
        action.type === "set-movement"
        && action.forward === true
        && action.jump === true
        && current.player.rotation.pitch !== -90
      ) {
        driver.currentObservation = observation({
          air: 300,
          position: { x: 4.5, y: 65, z: 0.5 },
        });
        return;
      }
      if (
        action.type === "reset-movement"
        && driver.currentObservation.player.position.x >= 4
      ) {
        resolveReachedShore();
      }
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "collect-blocks")) {
        yield* Effect.sleep(1);
      }
      driver.currentObservation = observation({
        air: 100,
        position: { x: 0, y: 63, z: 0 },
      });
      yield* Effect.promise(() => reachedShore).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.actions).toContainEqual(expect.objectContaining({
      type: "look",
      pitch: -90,
    }));
    expect(driver.actions).toContainEqual(expect.objectContaining({
      type: "look",
      pitch: -20,
    }));
    expect(driver.paths).toEqual([]);
    expect(driver.currentObservation.player.position).toMatchObject({
      x: 4.5,
      y: 65,
    });
  });

  it("stops swimming when a failed shore route already reached dry ground", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = [-1, 0, 1].map((z) => ({
      x: 4,
      z,
      loaded: true,
      surfaceY: 64,
      blockId: "minecraft:grass_block",
      skyLight: 15,
      blockLight: 0,
    }));
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
          && driver.currentObservation.player.position.x < 4
        ? [blockObservation({
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
        })]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" ? Effect.never : Effect.void,
        ),
      );
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        driver.currentObservation = observation({
          air: 300,
          position,
        });
      }).pipe(
        Effect.zipRight(Effect.fail(new BeatGameDriverError({
          operation: "pathfind",
          code: "timeout",
          retryable: true,
          message: "The route timed out after reaching shore",
        }))),
      );
    driver.actionObserver = (action) => {
      const current = driver.currentObservation;
      if (action.type === "look") {
        driver.currentObservation = {
          ...current,
          player: {
            ...current.player,
            rotation: { yaw: action.yaw, pitch: action.pitch },
          },
        };
        return;
      }
      if (
        action.type === "set-movement"
        && action.jump === true
        && current.player.rotation.pitch === -90
      ) {
        driver.currentObservation = observation({
          air: 300,
          position: { x: 0, y: 63.95, z: 0 },
        });
      }
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "collect-blocks")) {
        yield* Effect.sleep(1);
      }
      driver.currentObservation = observation({
        air: 100,
        position: { x: 0, y: 61, z: 0 },
      });
      while (driver.paths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* Effect.sleep(10);
      yield* run.stop;
    })));

    expect(driver.currentObservation.player.position).toMatchObject({
      x: 4.5,
      y: 65,
      z: 0.5,
    });
    expect(driver.actions).not.toContainEqual(expect.objectContaining({
      type: "look",
      pitch: -20,
    }));
  });

  it("keeps ascending before responding to an underwater threat", async () => {
    const driver = new FakeBeatGameDriver();
    const creeper = {
      connectionEpoch: "epoch-1",
      networkId: 54,
      entityType: "minecraft:creeper",
      position: {
        x: 2,
        y: 51,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } satisfies BeatGameEntityObservation;
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
        ? [blockObservation({
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
        })]
        : [];
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true ? [creeper] : [];
    let ascending = false;
    let responseAir: number | undefined;
    driver.actionObserver = (action) => {
      if (
        action.type === "set-movement"
        && action.forward === true
        && action.jump === true
      ) {
        ascending = true;
      } else if (action.type === "reset-movement") {
        ascending = false;
      } else if (action.type === "attack-entity") {
        responseAir ??= driver.currentObservation.player.air;
      }
    };
    driver.observationResolver = () =>
      Effect.sync(() => {
        if (!ascending) {
          return driver.currentObservation;
        }
        driver.currentObservation = {
          ...driver.currentObservation,
          player: {
            ...driver.currentObservation.player,
            air: Math.min(
              driver.currentObservation.player.maxAir,
              driver.currentObservation.player.air + 40,
            ),
            position: {
              ...driver.currentObservation.player.position,
              y: driver.currentObservation.player.position.y + 0.75,
            },
          },
        };
        return driver.currentObservation;
      });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          responseAir ??= driver.currentObservation.player.air;
        }
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            driver.currentObservation = observation({
              air: 100,
              health: 3,
              position: { x: 0, y: 51, z: 0 },
            });
            while (responseAir === undefined) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(responseAir).toBeGreaterThan(200);
    expect(driver.actions).toContainEqual({
      type: "set-movement",
      forward: true,
      jump: true,
      sprint: true,
    });
    expect(driver.actions).toContainEqual({ type: "reset-movement" });
  });

  it("widens the shore search after replenishing air in open water", async () => {
    const driver = new FakeBeatGameDriver();
    const distantSurfaceColumns = [
      {
        x: 1,
        z: -1,
        loaded: true,
        surfaceY: 62,
        blockId: "minecraft:tall_seagrass",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: 1,
        z: 0,
        loaded: true,
        surfaceY: 63,
        blockId: "minecraft:tall_seagrass",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: 1,
        z: 1,
        loaded: true,
        surfaceY: 62,
        blockId: "minecraft:tall_seagrass",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: 4,
        z: 0,
        loaded: true,
        surfaceY: 64,
        blockId: "minecraft:grass_block",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: 4,
        z: 1,
        loaded: true,
        surfaceY: 64,
        blockId: "minecraft:grass_block",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: 4,
        z: -1,
        loaded: true,
        surfaceY: 64,
        blockId: "minecraft:grass_block",
        skyLight: 15,
        blockLight: 0,
      },
    ];
    driver.surfaceQueryResolver = (_center, radius) =>
      radius > 16 ? distantSurfaceColumns : [];
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
          && driver.currentObservation.player.position.x < 4
        ? [blockObservation({
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
        })]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" ? Effect.never : Effect.void,
        ),
      );
    let swimmingUpward = false;
    let swimmingToShore = false;
    let ascentObservations = 0;
    let resolveReachedShore!: () => void;
    const reachedShore = new Promise<void>((resolve) => {
      resolveReachedShore = resolve;
    });
    driver.actionObserver = (action) => {
      const current = driver.currentObservation;
      if (action.type === "look") {
        driver.currentObservation = {
          ...current,
          player: {
            ...current.player,
            rotation: {
              yaw: action.yaw,
              pitch: action.pitch,
            },
          },
        };
        return;
      }
      if (
        action.type === "set-movement"
        && action.forward === true
        && action.jump === true
      ) {
        const swimmingVertically =
          driver.currentObservation.player.rotation.pitch === -90;
        swimmingUpward = swimmingVertically;
        swimmingToShore = !swimmingVertically;
        driver.currentObservation = {
          ...driver.currentObservation,
          player: {
            ...driver.currentObservation.player,
            air: swimmingVertically ? 250 : 300,
            position: swimmingVertically
              ? {
                x: 0,
                y: 63.95,
                z: 0,
                dimension: "minecraft:overworld",
              }
              : {
                x: 4.5,
                y: 65,
                z: 0.5,
                dimension: "minecraft:overworld",
              },
          },
        };
        return;
      }
      if (action.type === "reset-movement") {
        if (swimmingToShore) {
          resolveReachedShore();
        }
        swimmingUpward = false;
        swimmingToShore = false;
      }
    };
    driver.observationResolver = () =>
      Effect.sync(() => {
        if (swimmingUpward) {
          ascentObservations += 1;
          if (ascentObservations >= 3) {
            driver.currentObservation = {
              ...driver.currentObservation,
              player: {
                ...driver.currentObservation.player,
                air: 300,
              },
            };
          }
        }
        return driver.currentObservation;
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        !driver.tasks.some((task) => task.type === "collect-blocks")
      ) {
        yield* Effect.sleep(1);
      }
      driver.currentObservation = observation({
        air: 100,
        food: 5,
        position: { x: 0, y: 61, z: 0 },
      });
      yield* Effect.promise(() => reachedShore).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(ascentObservations).toBeGreaterThanOrEqual(3);
    expect(driver.surfaceQueries).toContainEqual(expect.objectContaining({
      radius: 16,
      sampleStep: 1,
    }));
    expect(driver.surfaceQueries).toContainEqual(expect.objectContaining({
      radius: 96,
      sampleStep: 4,
    }));
    expect(driver.actions).toContainEqual(expect.objectContaining({
      type: "look",
      pitch: -20,
    }));
    expect(driver.actions).toContainEqual({
      type: "set-movement",
      forward: true,
      jump: true,
      sprint: false,
    });
    expect(driver.paths[0]).toEqual({
      position: {
        x: 4.5,
        y: 65,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 0.75,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        avoidFluids: false,
        maxFallDistance: 3,
        maxSearchTimeMs: 5_000,
        sprint: false,
      }),
    });
    expect(driver.currentObservation.player.position).toMatchObject({
      x: 4.5,
      y: 65,
      z: 0.5,
    });
  });

  it("interrupts a shore crossing to defend against a nearby hostile", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = [-1, 0, 1].map((z) => ({
      x: 4,
      z,
      loaded: true,
      surfaceY: 64,
      blockId: "minecraft:grass_block",
      skyLight: 15,
      blockLight: 0,
    }));
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
          && driver.currentObservation.player.position.x < 4
        ? [blockObservation({
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
        })]
        : [];
    const zombie = {
      connectionEpoch: "epoch-1",
      networkId: 52,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:01.000Z",
    } satisfies BeatGameEntityObservation;
    let swimmingToShore = false;
    let hostileAppeared = false;
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-nearest") {
          driver.entityResults = [];
          driver.currentObservation = observation({
            air: 300,
            position: { x: 4.5, y: 65, z: 0.5 },
          });
        }
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" ? Effect.never : Effect.void,
        ),
      );
    driver.actionObserver = (action) => {
      const current = driver.currentObservation;
      if (action.type === "look") {
        driver.currentObservation = {
          ...current,
          player: {
            ...current.player,
            rotation: {
              yaw: action.yaw,
              pitch: action.pitch,
            },
          },
        };
        return;
      }
      if (
        action.type === "set-movement"
        && action.forward === true
        && action.jump === true
      ) {
        const swimmingUpward = current.player.rotation.pitch === -90;
        swimmingToShore = !swimmingUpward;
        driver.currentObservation = observation({
          air: 300,
          position: swimmingUpward
            ? { x: 0, y: 63.95, z: 0 }
            : current.player.position,
        });
        return;
      }
      if (action.type === "reset-movement") {
        swimmingToShore = false;
      }
    };
    driver.observationResolver = () =>
      Effect.sync(() => {
        if (swimmingToShore && !hostileAppeared) {
          hostileAppeared = true;
          driver.entityResults = [zombie];
        }
        return driver.currentObservation;
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        !driver.tasks.some((task) => task.type === "collect-blocks")
      ) {
        yield* Effect.sleep(1);
      }
      driver.currentObservation = observation({
        air: 100,
        position: { x: 0, y: 61, z: 0 },
      });
      while (
        !driver.tasks.some((task) => task.type === "attack-nearest")
        || driver.tasks.filter((task) =>
            task.type === "collect-blocks"
          ).length < 2
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-nearest",
      selector: {
        categories: [2],
        alive: true,
      },
    }));
    expect(driver.actions).toContainEqual({ type: "reset-movement" });
    expect(driver.currentObservation.player.position).toMatchObject({
      x: 4.5,
      y: 65,
      z: 0.5,
    });
  });

  it("releases swimming control before evading a low-health hostile", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = [-1, 0, 1].map((z) => ({
      x: 4,
      z,
      loaded: true,
      surfaceY: 64,
      blockId: "minecraft:grass_block",
      skyLight: 15,
      blockLight: 0,
    }));
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
          && driver.currentObservation.player.position.x < 4
        ? [blockObservation({
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
        })]
        : [];
    const spider = {
      connectionEpoch: "epoch-1",
      networkId: 53,
      entityType: "minecraft:spider",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 16,
      observedAt: "2026-01-01T00:00:01.000Z",
    } satisfies BeatGameEntityObservation;
    let swimmingToShore = false;
    let hostileAppeared = false;
    driver.entityQueryResolver = (query) =>
      query.selector.categories?.includes(2) === true
        ? driver.entityResults
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" ? Effect.never : Effect.void,
        ),
      );
    driver.actionObserver = (action) => {
      const current = driver.currentObservation;
      if (action.type === "look") {
        driver.currentObservation = {
          ...current,
          player: {
            ...current.player,
            rotation: {
              yaw: action.yaw,
              pitch: action.pitch,
            },
          },
        };
        return;
      }
      if (
        action.type === "set-movement"
        && action.forward === true
        && action.jump === true
      ) {
        const swimmingUpward = current.player.rotation.pitch === -90;
        swimmingToShore = !swimmingUpward;
        if (swimmingUpward) {
          driver.currentObservation = {
            ...current,
            player: {
              ...current.player,
              air: 300,
              position: {
                x: 0,
                y: 63.95,
                z: 0,
                dimension: "minecraft:overworld",
              },
            },
          };
        }
        return;
      }
      if (action.type === "reset-movement") {
        swimmingToShore = false;
      }
    };
    driver.observationResolver = () =>
      Effect.sync(() => {
        if (swimmingToShore && !hostileAppeared) {
          hostileAppeared = true;
          driver.entityResults = [spider];
        }
        return driver.currentObservation;
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        !driver.tasks.some((task) => task.type === "collect-blocks")
      ) {
        yield* Effect.sleep(1);
      }
      driver.currentObservation = observation({
        air: 100,
        health: 3,
        position: { x: 0, y: 61, z: 0 },
      });
      while (
        !driver.actions.some((action) =>
          action.type === "attack-entity"
          && action.networkId === spider.networkId
        )
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.maximumActiveControlScopes).toBe(1);
    expect(driver.actions).toContainEqual({
      type: "attack-entity",
      connectionEpoch: spider.connectionEpoch,
      networkId: spider.networkId,
      sprinting: true,
    });
  });

  it("refreshes air during a long shore crossing before resuming work", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = [-1, 0, 1].map((z) => ({
      x: 8,
      z,
      loaded: true,
      surfaceY: 64,
      blockId: "minecraft:grass_block",
      skyLight: 15,
      blockLight: 0,
    }));
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" ? Effect.never : Effect.void,
        ),
      );
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
          && driver.currentObservation.player.position.x < 8
        ? [blockObservation({
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
        })]
        : [];
    let movementActive = false;
    let resolveReachedShore!: () => void;
    const reachedShore = new Promise<void>((resolve) => {
      resolveReachedShore = resolve;
    });
    driver.actionObserver = (action) => {
      const current = driver.currentObservation;
      if (action.type === "look") {
        driver.currentObservation = {
          ...current,
          player: {
            ...current.player,
            rotation: {
              yaw: action.yaw,
              pitch: action.pitch,
            },
          },
        };
        return;
      }
      if (action.type === "set-movement") {
        movementActive = true;
        return;
      }
      if (action.type === "reset-movement") {
        movementActive = false;
        if (driver.currentObservation.player.position.x >= 8) {
          resolveReachedShore();
        }
      }
    };
    driver.observationResolver = () =>
      Effect.sync(() => {
        if (!movementActive) {
          return driver.currentObservation;
        }
        const current = driver.currentObservation;
        const swimmingUpward = current.player.rotation.pitch === -90;
        const nextX = swimmingUpward
          ? current.player.position.x
          : Math.min(8.25, current.player.position.x + 0.75);
        driver.currentObservation = {
          ...current,
          player: {
            ...current.player,
            air: swimmingUpward
              ? Math.min(current.player.maxAir, current.player.air + 100)
              : Math.max(0, current.player.air - 45),
            position: {
              ...current.player.position,
              x: nextX,
              y: nextX >= 8 ? 65 : 63.95,
            },
          },
        };
        return driver.currentObservation;
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        !driver.tasks.some((task) => task.type === "collect-blocks")
      ) {
        yield* Effect.sleep(1);
      }
      driver.currentObservation = observation({
        air: 100,
        position: { x: 0, y: 61, z: 0 },
      });
      yield* Effect.promise(() => reachedShore).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.actions.filter((action) =>
      action.type === "look" && action.pitch === -90
    ).length).toBeGreaterThanOrEqual(3);
    expect(driver.tasks.filter((task) =>
      task.type === "collect-blocks"
    )).toHaveLength(1);
    expect(driver.currentObservation.player.position).toMatchObject({
      x: 8.25,
      y: 65,
    });
  });

  it("swims out from under a shoreline block before trying to mine it", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceQueryResolver = () => [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(Effect.zipRight(Effect.never));
    driver.blockQueryResolver = (query) => {
      const position = {
        x: Math.floor(query.center.x),
        y: Math.floor(query.center.y),
        z: Math.floor(query.center.z),
        dimension: query.center.dimension,
      };
      if (query.selector.blockIds?.includes("minecraft:water") === true) {
        return driver.currentObservation.player.position.x < 1
          ? [blockObservation(position, {
            blockId: "minecraft:water",
            diggable: false,
            replaceable: true,
          })]
          : [];
      }
      if (query.selector.blockIds !== undefined) {
        return [];
      }
      const blockId = position.y === 63 && position.x === 1
        ? "minecraft:air"
        : position.y <= 62 && position.x === 1
        ? "minecraft:water"
        : position.y === 63
        ? "minecraft:dirt"
        : "minecraft:water";
      return [blockObservation(position, {
        blockId,
        diggable: blockId === "minecraft:dirt",
        replaceable: blockId !== "minecraft:dirt",
      })];
    };
    let swimmingTowardAir = false;
    let resolveEscaped!: () => void;
    const escaped = new Promise<void>((resolve) => {
      resolveEscaped = resolve;
    });
    driver.actionObserver = (action) => {
      const current = driver.currentObservation;
      if (action.type === "look") {
        driver.currentObservation = {
          ...current,
          player: {
            ...current.player,
            rotation: { yaw: action.yaw, pitch: action.pitch },
          },
        };
        return;
      }
      if (
        action.type === "set-movement"
        && action.forward === true
        && current.player.rotation.pitch === -20
      ) {
        swimmingTowardAir = true;
        return;
      }
      if (action.type === "reset-movement") {
        swimmingTowardAir = false;
      }
    };
    driver.observationResolver = () =>
      Effect.sync(() => {
        if (!swimmingTowardAir) {
          return driver.currentObservation;
        }
        const current = driver.currentObservation;
        driver.currentObservation = {
          ...current,
          player: {
            ...current.player,
            air: 300,
            position: {
              ...current.player.position,
              x: 1.5,
            },
          },
        };
        resolveEscaped();
        return driver.currentObservation;
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "collect-blocks")) {
        yield* Effect.sleep(1);
      }
      driver.currentObservation = observation({
        air: 100,
        food: 12,
        position: { x: 0.5, y: 61, z: 0.5 },
      });
      yield* Effect.promise(() => escaped).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.currentObservation.player.position.x).toBe(1.5);
    expect(driver.currentObservation.player.air).toBe(300);
    expect(driver.actions.some((action) => action.type === "dig-block"))
      .toBe(false);
  });

  it("retreats to a nearby breathing pocket in a submerged cavity", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceQueryResolver = () => [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(Effect.zipRight(Effect.never));
    driver.blockQueryResolver = (query) => {
      const position = {
        x: Math.floor(query.center.x),
        y: Math.floor(query.center.y),
        z: Math.floor(query.center.z),
        dimension: query.center.dimension,
      };
      if (
        query.selector.blockIds?.some((blockId) =>
          blockId === "minecraft:air"
          || blockId === "minecraft:cave_air"
          || blockId === "minecraft:void_air"
        ) === true
      ) {
        return [blockObservation({
          x: 0,
          y: 29,
          z: 0,
          dimension: "minecraft:overworld",
        }, {
          blockId: "minecraft:air",
          diggable: false,
          replaceable: true,
        })];
      }
      if (query.selector.blockIds?.includes("minecraft:water") === true) {
        return position.y === 28 || position.y >= 31
          ? [blockObservation(position, {
            blockId: "minecraft:water",
            diggable: false,
            replaceable: true,
          })]
          : [];
      }
      if (query.selector.blockIds === undefined) {
        const blockId = position.y === 29
          ? "minecraft:air"
          : "minecraft:water";
        return [blockObservation(position, {
          blockId,
          diggable: false,
          replaceable: true,
        })];
      }
      return [];
    };
    let resolveEscaped!: () => void;
    const escaped = new Promise<void>((resolve) => {
      resolveEscaped = resolve;
    });
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (position.y === 28) {
          driver.currentObservation = observation({
            air: 300,
            position,
          });
          resolveEscaped();
        }
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "collect-blocks")) {
        yield* Effect.sleep(1);
      }
      driver.currentObservation = observation({
        air: 100,
        position: { x: 0.5, y: 31, z: 0.5 },
      });
      yield* Effect.promise(() => escaped).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.paths).toContainEqual({
      position: {
        x: 0.5,
        y: 28,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 0.75,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        avoidFluids: false,
        maxSearchTimeMs: 4_000,
      }),
    });
    expect(driver.currentObservation.player.air).toBe(300);
    expect(driver.actions.some((action) => action.type === "dig-block"))
      .toBe(false);
  });

  it("abandons a blocked shore and clears the immediate swimming ceiling", async () => {
    const driver = new FakeBeatGameDriver();
    const preparedItems = {
      "minecraft:oak_log": 8,
      "minecraft:cobblestone": 20,
      "minecraft:stone_sword": 1,
      "minecraft:wooden_pickaxe": 1,
      "minecraft:beef": 8,
    };
    driver.surfaceQueryResolver = () =>
      [-1, 0, 1].map((z) => ({
        x: 1,
        z,
        loaded: true,
        surfaceY: 63,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      }));
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(Effect.zipRight(Effect.never));
    let overheadCleared = false;
    let swimmingTowardShore = false;
    let escapedFromFluid = false;
    let resolveEscaped!: () => void;
    const escaped = new Promise<void>((resolve) => {
      resolveEscaped = resolve;
    });
    driver.blockQueryResolver = (query) => {
      const blockX = Math.floor(query.center.x);
      const blockY = Math.floor(query.center.y);
      const blockZ = Math.floor(query.center.z);
      const blockIds = query.selector.blockIds;
      if (
        blockIds?.includes("minecraft:water") === true
        && !escapedFromFluid
      ) {
        return [blockObservation({
          x: blockX,
          y: blockY,
          z: blockZ,
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
        })];
      }
      if (blockIds === undefined) {
        const immediateCeiling = blockX === 0
          && blockY === 63
          && blockZ === 0;
        return immediateCeiling && overheadCleared
          ? [blockObservation({
            x: 0,
            y: 63,
            z: 0,
            dimension: "minecraft:overworld",
          }, {
            blockId: "minecraft:air",
            diggable: false,
            replaceable: true,
          })]
          : [blockObservation({
            x: blockX,
            y: blockY,
            z: blockZ,
            dimension: query.center.dimension,
          })];
      }
      return [];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.flatMap(() =>
          overheadCleared
            ? Effect.void
            : Effect.fail(new BeatGameDriverError({
              operation: "pathfind",
              code: "unreachable",
              retryable: true,
              message: "The submerged cavity has no navigable exit",
            }))
        ),
      );
    driver.actionObserver = (action) => {
      const current = driver.currentObservation;
      if (action.type === "look") {
        driver.currentObservation = {
          ...current,
          player: {
            ...current.player,
            rotation: {
              yaw: action.yaw,
              pitch: action.pitch,
            },
          },
        };
        return;
      }
      if (action.type === "dig-block") {
        overheadCleared = true;
        return;
      }
      if (action.type === "reset-movement") {
        swimmingTowardShore = false;
        return;
      }
      if (action.type !== "set-movement" || action.jump !== true) {
        return;
      }
      if (
        action.forward === true
        && current.player.rotation.pitch !== -90
      ) {
        swimmingTowardShore = true;
        return;
      }
      const verticalEscape = action.forward === undefined && overheadCleared;
      if (!verticalEscape) {
        return;
      }
      driver.currentObservation = {
        ...current,
        player: {
          ...current.player,
          air: 300,
          position: {
            ...current.player.position,
            y: 64,
          },
        },
      };
      escapedFromFluid = true;
      resolveEscaped();
    };
    driver.observationResolver = () =>
      Effect.sync(() => {
        if (!swimmingTowardShore) {
          return driver.currentObservation;
        }
        const current = driver.currentObservation;
        driver.currentObservation = {
          ...current,
          player: {
            ...current.player,
            air: current.player.air - 5,
          },
        };
        return driver.currentObservation;
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        !driver.tasks.some((task) => task.type === "collect-blocks")
      ) {
        yield* Effect.sleep(1);
      }
      driver.currentObservation = observation({
        air: 190,
        food: 12,
        counts: preparedItems,
        position: { x: 0.5, y: 62.4, z: 0.5 },
      });
      yield* Effect.promise(() => escaped).pipe(
        Effect.timeout("10 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.actions).toContainEqual({
      type: "select-item",
      selector: {
        itemIds: [
          "minecraft:netherite_pickaxe",
          "minecraft:diamond_pickaxe",
          "minecraft:iron_pickaxe",
          "minecraft:stone_pickaxe",
          "minecraft:wooden_pickaxe",
          "minecraft:golden_pickaxe",
        ],
      },
    });
    expect(driver.actions).toContainEqual({
      type: "dig-block",
      position: {
        x: 0,
        y: 63,
        z: 0,
        dimension: "minecraft:overworld",
      },
    });
    expect(driver.actions).toContainEqual({
      type: "set-movement",
      jump: true,
    });
    const digIndex = driver.actions.findIndex((action) =>
      action.type === "dig-block"
    );
    const heldAscentIndex = driver.actions.findIndex((action, index) =>
      index < digIndex
      && action.type === "set-movement"
      && action.forward === undefined
      && action.jump === true
    );
    const releaseIndex = driver.actions.findIndex((action, index) =>
      index > digIndex && action.type === "reset-movement"
    );
    expect(heldAscentIndex).toBeGreaterThanOrEqual(0);
    expect(releaseIndex).toBeGreaterThan(digIndex);
    expect(driver.paths).toHaveLength(0);
    expect(driver.currentObservation.player.position.y).toBe(64);
  }, 15_000);

  it("keeps climbing a deep aquifer after surface pathfinding fails", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = [{
      x: 0,
      z: 0,
      loaded: true,
      surfaceY: 63,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(Effect.zipRight(Effect.never));
    driver.blockQueryResolver = (query) => {
      const position = {
        x: Math.floor(query.center.x),
        y: Math.floor(query.center.y),
        z: Math.floor(query.center.z),
        dimension: query.center.dimension,
      };
      const submerged = driver.currentObservation.player.position.y < 64;
      if (query.selector.blockIds?.includes("minecraft:water") === true) {
        return submerged
          ? [blockObservation(position, {
            blockId: "minecraft:water",
            diggable: false,
            replaceable: true,
          })]
          : [];
      }
      if (query.selector.blockIds === undefined) {
        return [blockObservation(position, {
          blockId: submerged ? "minecraft:water" : "minecraft:air",
          diggable: false,
          replaceable: true,
        })];
      }
      return [];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.fail(new BeatGameDriverError({
        operation: "pathfind",
        code: "unreachable",
        retryable: true,
        message: "The deep aquifer has no navigable route to its surface",
      }))));
    let ascending = false;
    let resolveEscaped!: () => void;
    const escaped = new Promise<void>((resolve) => {
      resolveEscaped = resolve;
    });
    driver.actionObserver = (action) => {
      const current = driver.currentObservation;
      if (action.type === "look") {
        driver.currentObservation = {
          ...current,
          player: {
            ...current.player,
            rotation: { yaw: action.yaw, pitch: action.pitch },
          },
        };
        return;
      }
      if (action.type === "set-movement" && action.jump === true) {
        if (action.forward === true) {
          driver.currentObservation = {
            ...current,
            player: {
              ...current.player,
              air: 300,
              position: { ...current.player.position, y: 30 },
            },
          };
          return;
        }
        ascending = true;
        return;
      }
      if (action.type === "reset-movement") {
        ascending = false;
      }
    };
    driver.observationResolver = () =>
      Effect.sync(() => {
        if (!ascending) {
          return driver.currentObservation;
        }
        const current = driver.currentObservation;
        const y = Math.min(64, current.player.position.y + 1);
        driver.currentObservation = {
          ...current,
          player: {
            ...current.player,
            air: 300,
            position: { ...current.player.position, y },
          },
        };
        if (y >= 64) {
          resolveEscaped();
        }
        return driver.currentObservation;
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "collect-blocks")) {
        yield* Effect.sleep(1);
      }
      driver.currentObservation = observation({
        air: 100,
        position: { x: 0.5, y: 28, z: 0.5 },
      });
      yield* Effect.promise(() => escaped).pipe(
        Effect.timeout("10 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.paths).toHaveLength(1);
    expect(driver.paths[0]?.policy.avoidFluids).toBe(false);
    expect(driver.currentObservation.player.position.y).toBe(64);
  }, 15_000);

  it("keeps recovering after a short water column opens into a deep cave", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = [{
      x: 0,
      z: 0,
      loaded: true,
      surfaceY: 63,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.currentObservation = observation({
      air: 300,
      counts: {
        "minecraft:oak_log": 3,
        "minecraft:stone_pickaxe": 1,
        "minecraft:wooden_sword": 1,
      },
      position: { x: 0.5, y: 28, z: 0.5 },
    });
    let deepSurfaceCollectionCount = 0;
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (
          task.type === "collect-blocks"
          && driver.currentObservation.player.position.y < 60
        ) {
          deepSurfaceCollectionCount += 1;
        }
      }).pipe(Effect.zipRight(Effect.never));
    driver.blockQueryResolver = (query) => {
      const position = {
        x: Math.floor(query.center.x),
        y: Math.floor(query.center.y),
        z: Math.floor(query.center.z),
        dimension: query.center.dimension,
      };
      const submerged = driver.currentObservation.player.position.y < 29;
      if (query.selector.blockIds?.includes("minecraft:water") === true) {
        return submerged
          ? [blockObservation(position, {
            blockId: "minecraft:water",
            diggable: false,
            replaceable: true,
          })]
          : [];
      }
      if (query.selector.blockIds === undefined) {
        return [blockObservation(position, {
          blockId: submerged ? "minecraft:water" : "minecraft:air",
          diggable: false,
          replaceable: true,
        })];
      }
      return [];
    };
    let resolveEscaped!: () => void;
    const escaped = new Promise<void>((resolve) => {
      resolveEscaped = resolve;
    });
    driver.pathResolver = (position, radius, policy) => {
      driver.paths.push({ position, radius, policy });
      if (driver.paths.length === 1) {
        return Effect.fail(new BeatGameDriverError({
          operation: "pathfind",
          code: "unreachable",
          retryable: true,
          message: "The water blocks the first surface route",
        }));
      }
      return Effect.sync(() => {
        driver.currentObservation = {
          ...driver.currentObservation,
          player: {
            ...driver.currentObservation.player,
            position,
          },
        };
        resolveEscaped();
      });
    };
    driver.actionObserver = (action) => {
      if (action.type === "look") {
        driver.currentObservation = {
          ...driver.currentObservation,
          player: {
            ...driver.currentObservation.player,
            rotation: { yaw: action.yaw, pitch: action.pitch },
          },
        };
        return;
      }
      if (action.type === "set-movement" && action.jump === true) {
        driver.currentObservation = {
          ...driver.currentObservation,
          player: {
            ...driver.currentObservation.player,
            air: 300,
            position: {
              ...driver.currentObservation.player.position,
              y: 29,
            },
          },
        };
      }
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => escaped).pipe(
        Effect.timeout("10 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.paths).toHaveLength(2);
    expect(driver.paths[0]?.policy.avoidFluids).toBe(false);
    expect(driver.paths[1]).toEqual(expect.objectContaining({
      position: {
        x: 0.5,
        y: 64,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      policy: expect.objectContaining({ avoidFluids: true }),
    }));
    expect(driver.currentObservation.player.position.y).toBe(64);
    expect(deepSurfaceCollectionCount).toBe(0);
  }, 15_000);

  it("mines iron before crafting a missing portal bucket", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    driver.currentObservation = observation({
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:cooked_beef": 8,
        "minecraft:oak_log": 4,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.some((blockId) =>
          blockId === "minecraft:iron_ore"
          || blockId === "minecraft:deepslate_iron_ore"
        )
        ? [blockObservation({
          x: 2,
          y: 63,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:iron_ore" })]
        : [];
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "missing-portal-bucket-run",
        teamId: "missing-portal-bucket-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "missing-portal-bucket-run",
        team: { teamId: "missing-portal-bucket-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "collect-blocks",
      blockIds: [
        "minecraft:iron_ore",
        "minecraft:deepslate_iron_ore",
      ],
    }));
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "craft",
      recipeId: expect.stringContaining("bucket"),
    }));
  });

  it("returns to the surface before searching for portal water", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const runId = "deep-portal-water-run";
    const teamId = "deep-portal-water-team";
    driver.currentObservation = observation({
      position: {
        x: 0.5,
        y: -53,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      counts: {
        "minecraft:bucket": 1,
        "minecraft:cobblestone": 20,
        "minecraft:cooked_beef": 8,
        "minecraft:flint_and_steel": 1,
        "minecraft:lava_bucket": 1,
        "minecraft:oak_log": 4,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.surfaceColumns = [{
      x: 0,
      z: 0,
      loaded: true,
      surfaceY: 64,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      { runId, teamId },
    ), undefined));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId,
        team: { teamId },
        checkpointStore: store,
        strategy: {
          observationPollMs: 1,
          portalStrategy: "CAST",
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.paths.some(({ position }) => position.y >= 65)) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
        Effect.timeout("5 seconds"),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: expect.objectContaining({ y: 65 }),
      policy: expect.objectContaining({
        allowMining: true,
        allowPlacing: true,
        avoidFluids: true,
      }),
    }));
    expect(driver.tasks).toHaveLength(0);
  });

  it("replaces a pickaxe broken on approach before exposing a fluid source", async () => {
    const driver = new FakeBeatGameDriver();
    const source = {
      x: 18,
      y: 66,
      z: 156,
      dimension: "minecraft:overworld",
    } as const;
    const playerPosition = {
      x: 19.5,
      y: 64,
      z: 158.5,
      dimension: "minecraft:overworld",
    } as const;
    const obstruction = {
      x: 18,
      y: 66,
      z: 157,
      dimension: "minecraft:overworld",
    } as const;
    const craftingTable = {
      x: 20,
      y: 64,
      z: 158,
      dimension: "minecraft:overworld",
    } as const;
    let sourceExposed = false;
    let approachBrokePickaxe = false;
    driver.currentObservation = observation({
      position: playerPosition,
      counts: {
        "minecraft:cooked_beef": 8,
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:stone_pickaxe": 1,
        "minecraft:bucket": 1,
        "minecraft:shield": 1,
      },
    });
    driver.blockQueryResolver = ({ radius, selector }) => {
      if (radius === 0.25 && Object.keys(selector).length === 0) {
        return [blockObservation(source, {
          blockId: "minecraft:water",
          properties: { level: "0" },
          replaceable: true,
        })];
      }
      if (
        selector.blockIds?.includes("minecraft:water") === true
        && selector.properties?.level === "0"
      ) {
        return [blockObservation(source, {
          blockId: "minecraft:water",
          properties: { level: "0" },
          replaceable: true,
        })];
      }
      if (
        selector.blockIds?.includes("minecraft:crafting_table") === true
      ) {
        return [blockObservation(craftingTable, {
          blockId: "minecraft:crafting_table",
        })];
      }
      return [];
    };
    driver.recipeResolver = (resultItemId) => [{
      recipeId: resultItemId,
      recipeType: "minecraft:crafting",
      resultItemId,
      resultCount: 1,
      ingredients: [],
    }];
    driver.craftabilityResolver = () => ({
      canCraft: true,
      maximumCraftCount: 1,
      requiredStation: "minecraft:crafting_table",
      missing: [],
    });
    const resolvePath = driver.pathResolver;
    driver.pathResolver = (position, radius, policy) =>
      resolvePath(position, radius, policy).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            if (
              !approachBrokePickaxe
              && position.x === source.x
              && position.y === source.y
              && position.z === source.z
            ) {
              approachBrokePickaxe = true;
              const counts = {
                ...driver.currentObservation.inventory.counts,
              };
              delete counts["minecraft:stone_pickaxe"];
              driver.currentObservation = observation({
                position: playerPosition,
                counts,
              });
            }
          })
        ),
      );
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (
          task.type === "craft"
          && task.recipeId === "minecraft:stone_pickaxe"
        ) {
          driver.currentObservation = observation({
            position: playerPosition,
            counts: {
              ...driver.currentObservation.inventory.counts,
              "minecraft:stone_pickaxe": 1,
            },
          });
        }
      });
    driver.raycastResolver = ({ includeFluids }) => {
      if (sourceExposed) {
        return includeFluids === true
          ? {
            block: blockObservation(source, {
              blockId: "minecraft:water",
              properties: { level: "0" },
              replaceable: true,
            }),
            distance: 2.4,
          }
          : { distance: 2.4 };
      }
      return {
        block: blockObservation(obstruction),
        distance: 1.4,
      };
    };
    driver.actionResolver = (action) => {
      if (action.type === "look") {
        driver.currentObservation = observation({
          position: playerPosition,
          counts: driver.currentObservation.inventory.counts,
          rotation: { yaw: action.yaw, pitch: action.pitch },
        });
      }
      if (
        action.type === "dig-block"
        && action.position.x === obstruction.x
        && action.position.y === obstruction.y
        && action.position.z === obstruction.z
      ) {
        sourceExposed = true;
      }
      return action.type === "use-item"
        ? Effect.never
        : Effect.succeed({});
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.actions.some((action) => action.type === "use-item")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: source,
      radius: 3,
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "craft",
      recipeId: "minecraft:stone_pickaxe",
    }));
    expect(driver.raycasts).toHaveLength(2);
    expect(driver.actions).toContainEqual({
      type: "dig-block",
      position: obstruction,
    });
    expect(driver.actions.slice(-2)).toEqual([
      {
        type: "select-item",
        selector: { itemIds: ["minecraft:bucket"] },
      },
      { type: "use-item", hand: "main" },
    ]);
    expect(driver.actions).not.toContainEqual(expect.objectContaining({
      type: "interact-block",
    }));
  });

  it("approaches lava from a dry ledge while standing in shallow water", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const source = {
      x: 0,
      y: -52,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const safeStand = {
      x: 2,
      y: -50,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const borderlineStand = {
      x: 3,
      y: -50,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const start = {
      x: 4.5,
      y: -51,
      z: 0.5,
      dimension: "minecraft:overworld",
    } as const;
    driver.currentObservation = observation({
      position: start,
      counts: {
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:cooked_beef": 8,
        "minecraft:iron_ingot": 7,
        "minecraft:bucket": 1,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_pickaxe": 1,
        "minecraft:shield": 1,
        "minecraft:water_bucket": 1,
      },
    });
    driver.blockQueryResolver = ({ center, radius, selector }) => {
      if (
        selector.blockIds?.includes("minecraft:water") === true
        && selector.blockIds.length > 1
        && Math.floor(center.x) === Math.floor(start.x)
        && Math.floor(center.y) === Math.floor(start.y)
        && Math.floor(center.z) === Math.floor(start.z)
      ) {
        return [blockObservation({
          x: Math.floor(start.x),
          y: Math.floor(start.y),
          z: Math.floor(start.z),
          dimension: start.dimension,
        }, {
          blockId: "minecraft:water",
          properties: { level: "0" },
          replaceable: true,
        })];
      }
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === "0"
      ) {
        return [blockObservation(source, {
          blockId: "minecraft:lava",
          properties: { level: "0" },
          replaceable: true,
        })];
      }
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === undefined
      ) {
        return [];
      }
      if (radius === 4.9 && Object.keys(selector).length === 0) {
        return [
          blockObservation(safeStand, {
            blockId: "minecraft:air",
            replaceable: true,
          }),
          blockObservation({ ...safeStand, y: safeStand.y + 1 }, {
            blockId: "minecraft:air",
            replaceable: true,
          }),
          blockObservation({ ...safeStand, y: safeStand.y - 1 }),
          blockObservation(borderlineStand, {
            blockId: "minecraft:air",
            replaceable: true,
          }),
          blockObservation({ ...borderlineStand, y: borderlineStand.y + 1 }, {
            blockId: "minecraft:air",
            replaceable: true,
          }),
          blockObservation({ ...borderlineStand, y: borderlineStand.y - 1 }),
        ];
      }
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      if (
        position.x === safeStand.x
        && position.z === safeStand.z
        && (position.y === safeStand.y || position.y === safeStand.y + 1)
      ) {
        return [blockObservation(position, {
          blockId: "minecraft:air",
          replaceable: true,
        })];
      }
      if (
        position.x === safeStand.x
        && position.y === safeStand.y - 1
        && position.z === safeStand.z
      ) {
        return [blockObservation(position)];
      }
      return [blockObservation(position, {
        blockId: "minecraft:lava",
        replaceable: true,
      })];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (radius === 0.75) {
          driver.currentObservation = observation({
            position,
            counts: driver.currentObservation.inventory.counts,
          });
        }
      });
    driver.raycastResolver = ({ includeFluids }) =>
      includeFluids === true
        ? {
          block: blockObservation(source, {
            blockId: "minecraft:lava",
            properties: { level: "0" },
            replaceable: true,
          }),
          distance: 3,
        }
        : { distance: 3 };
    let resolveUseItemStarted!: () => void;
    const useItemStarted = new Promise<void>((resolve) => {
      resolveUseItemStarted = resolve;
    });
    let resolveUseItemInterrupted!: () => void;
    const useItemInterrupted = new Promise<void>((resolve) => {
      resolveUseItemInterrupted = resolve;
    });
    driver.actionResolver = (action) => {
      if (action.type === "look") {
        driver.currentObservation = observation({
          position: driver.currentObservation.player.position,
          counts: driver.currentObservation.inventory.counts,
          rotation: { yaw: action.yaw, pitch: action.pitch },
        });
      }
      return action.type === "use-item"
        ? Effect.sync(resolveUseItemStarted).pipe(
          Effect.zipRight(Effect.never),
          Effect.onInterrupt(() =>
            Effect.sync(resolveUseItemInterrupted)
          ),
        )
        : Effect.succeed({});
    };
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "safe-lava-approach-run",
        teamId: "safe-lava-approach-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "safe-lava-approach-run",
        team: { teamId: "safe-lava-approach-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* Effect.promise(() => useItemStarted).pipe(
              Effect.timeout("5 seconds"),
            );
            driver.currentObservation = observation({
              position: driver.currentObservation.player.position,
              counts: {
                ...driver.currentObservation.inventory.counts,
                "minecraft:bucket": 0,
                "minecraft:lava_bucket": 1,
              },
              rotation: driver.currentObservation.player.rotation,
            });
            yield* Effect.promise(() => useItemInterrupted).pipe(
              Effect.timeout("5 seconds"),
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual({
      position: {
        x: 2.5,
        y: -50,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 0.75,
      policy: expect.objectContaining({
        avoidFluids: true,
        maxFallDistance: 1,
      }),
    });
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: source,
      radius: 3,
    }));
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: {
        x: 3.5,
        y: -50,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
    }));
    expect(driver.actions.some((action) => action.type === "dig-block"))
      .toBe(false);
    expect(driver.blockQueries).toContainEqual(expect.objectContaining({
      center: {
        x: 0.5,
        y: -51.5,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 4.9,
      maximumResults: 500,
    }));
    expect(driver.blockQueries).toContainEqual({
      center: {
        x: 0.5,
        y: -51.5,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 0.25,
      selector: {
        blockIds: ["minecraft:lava"],
        properties: { level: "0" },
      },
      maximumResults: 1,
    });
    expect(driver.actions).toContainEqual({
      type: "use-item",
      hand: "main",
    });
  });

  it("prefers a source-rich lava pool over a nearer lone source", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const start = {
      x: 0.5,
      y: -50,
      z: 0.5,
      dimension: "minecraft:overworld",
    } as const;
    const loneSource = blockObservation({
      x: 4,
      y: -52,
      z: 0,
      dimension: start.dimension,
    }, {
      blockId: "minecraft:lava",
      properties: { level: "0" },
      replaceable: true,
    });
    const poolSources = [
      { x: 20, z: 0 },
      { x: 20, z: 1 },
      { x: 21, z: 0 },
      { x: 21, z: 1 },
    ].map(({ x, z }) => blockObservation({
      x,
      y: -52,
      z,
      dimension: start.dimension,
    }, {
      blockId: "minecraft:lava",
      properties: { level: "0" },
      replaceable: true,
    }));
    const loneStand = {
      x: 2,
      y: -50,
      z: 0,
      dimension: start.dimension,
    } as const;
    const poolStand = {
      x: 18,
      y: -50,
      z: 0,
      dimension: start.dimension,
    } as const;
    const standVolume = (stand: BeatGameBlockPosition) => [
      blockObservation(stand, {
        blockId: "minecraft:air",
        replaceable: true,
      }),
      blockObservation({ ...stand, y: stand.y + 1 }, {
        blockId: "minecraft:air",
        replaceable: true,
      }),
      blockObservation({ ...stand, y: stand.y - 1 }),
    ];
    const sources = [loneSource, ...poolSources];
    driver.currentObservation = observation({
      position: start,
      counts: {
        "minecraft:bucket": 1,
        "minecraft:cobblestone": 20,
        "minecraft:cooked_beef": 8,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:water_bucket": 1,
      },
    });
    driver.blockQueryResolver = ({ center, radius, selector }) => {
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === "0"
      ) {
        if (radius > 0.25) {
          return sources;
        }
        return sources.filter(({ position }) =>
          position.x === Math.floor(center.x)
          && position.y === Math.floor(center.y)
          && position.z === Math.floor(center.z)
        );
      }
      if (radius === 4.9 && Object.keys(selector).length === 0) {
        return standVolume(center.x < 10 ? loneStand : poolStand);
      }
      return [];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (radius === 0.75) {
          driver.currentObservation = observation({
            position,
            counts: driver.currentObservation.inventory.counts,
          });
        }
      });
    driver.raycastResolver = ({ includeFluids }) => {
      if (includeFluids !== true) {
        return { distance: 2 };
      }
      const source = driver.currentObservation.player.position.x >= 10
        ? poolSources[0]!
        : loneSource;
      return { block: source, distance: 2 };
    };
    driver.actionResolver = (action) => {
      if (action.type === "look") {
        driver.currentObservation = observation({
          position: driver.currentObservation.player.position,
          counts: driver.currentObservation.inventory.counts,
          rotation: { yaw: action.yaw, pitch: action.pitch },
        });
      }
      return action.type === "use-item" ? Effect.never : Effect.succeed({});
    };
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "clustered-lava-source-run",
        teamId: "clustered-lava-source-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "clustered-lava-source-run",
        team: { teamId: "clustered-lava-source-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      while (!driver.actions.some((action) => action.type === "use-item")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    }).pipe(Effect.timeout("5 seconds"))));

    expect(driver.paths.find(({ radius }) => radius === 0.75)).toEqual(
      expect.objectContaining({
        position: {
          x: poolStand.x + 0.5,
          y: poolStand.y,
          z: poolStand.z + 0.5,
          dimension: poolStand.dimension,
        },
      }),
    );
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: {
        x: loneStand.x + 0.5,
        y: loneStand.y,
        z: loneStand.z + 0.5,
        dimension: loneStand.dimension,
      },
    }));
  });

  it("prefers a clear lava sightline over a closer blocked stand", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const source = {
      x: 0,
      y: -52,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const blockedStand = {
      x: 2,
      y: -50,
      z: 0,
      dimension: source.dimension,
    } as const;
    const clearStand = {
      x: -2,
      y: -50,
      z: 0,
      dimension: source.dimension,
    } as const;
    const craftingTable = {
      x: 4,
      y: -50,
      z: 1,
      dimension: source.dimension,
    } as const;
    const standVolume = (stand: BeatGameBlockPosition) => [
      blockObservation(stand, {
        blockId: "minecraft:air",
        replaceable: true,
      }),
      blockObservation({ ...stand, y: stand.y + 1 }, {
        blockId: "minecraft:air",
        replaceable: true,
      }),
      blockObservation({ ...stand, y: stand.y - 1 }),
    ];
    const sightlineWall = Array.from({ length: 5 }, (_, index) =>
      blockObservation({
        x: 1,
        y: -52 + index,
        z: 0,
        dimension: source.dimension,
      })
    );
    driver.currentObservation = observation({
      position: {
        x: 4.5,
        y: -50,
        z: 0.5,
        dimension: source.dimension,
      },
      counts: {
        "minecraft:bucket": 1,
        "minecraft:cobblestone": 20,
        "minecraft:cooked_beef": 8,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:water_bucket": 1,
      },
      remainingDurability: { "minecraft:iron_pickaxe": 1 },
    });
    driver.blockQueryResolver = ({ radius, selector }) => {
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === "0"
      ) {
        return [blockObservation(source, {
          blockId: "minecraft:lava",
          properties: { level: "0" },
          replaceable: true,
        })];
      }
      if (
        selector.blockIds?.includes("minecraft:crafting_table") === true
      ) {
        return [blockObservation(craftingTable, {
          blockId: "minecraft:crafting_table",
        })];
      }
      return radius === 4.9 && Object.keys(selector).length === 0
        ? [
          ...standVolume(blockedStand),
          ...standVolume(clearStand),
          ...sightlineWall,
        ]
        : [];
    };
    driver.recipeResolver = (resultItemId) => [{
      recipeId: resultItemId,
      recipeType: "minecraft:crafting",
      resultItemId,
      resultCount: 1,
      ingredients: [],
    }];
    driver.craftabilityResolver = () => ({
      canCraft: true,
      maximumCraftCount: 1,
      requiredStation: "minecraft:crafting_table",
      missing: [],
    });
    let replacementCrafted = false;
    let pathStartedBeforeReplacement = false;
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (
          task.type === "craft"
          && task.recipeId === "minecraft:iron_pickaxe"
        ) {
          replacementCrafted = true;
          driver.currentObservation = observation({
            position: driver.currentObservation.player.position,
            counts: {
              ...driver.currentObservation.inventory.counts,
              "minecraft:iron_pickaxe": 2,
            },
            remainingDurability: { "minecraft:iron_pickaxe": 251 },
          });
        }
      });
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (radius === 0.75) {
          pathStartedBeforeReplacement ||= !replacementCrafted;
          driver.currentObservation = observation({
            position,
            counts: driver.currentObservation.inventory.counts,
          });
        }
      });
    driver.raycastResolver = ({ includeFluids }) =>
      includeFluids === true
        ? {
          block: blockObservation(source, {
            blockId: "minecraft:lava",
            properties: { level: "0" },
            replaceable: true,
          }),
          distance: 3,
        }
        : { distance: 3 };
    driver.actionResolver = (action) => {
      if (action.type === "look") {
        driver.currentObservation = observation({
          position: driver.currentObservation.player.position,
          counts: driver.currentObservation.inventory.counts,
          rotation: { yaw: action.yaw, pitch: action.pitch },
        });
      }
      return action.type === "use-item" ? Effect.never : Effect.succeed({});
    };
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "clear-lava-sightline-run",
        teamId: "clear-lava-sightline-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "clear-lava-sightline-run",
        team: { teamId: "clear-lava-sightline-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      while (!driver.actions.some((action) => action.type === "use-item")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    }).pipe(Effect.timeout("5 seconds"))));

    expect(driver.paths.find(({ radius }) => radius === 0.75)).toEqual(
      expect.objectContaining({
        position: {
          x: clearStand.x + 0.5,
          y: clearStand.y,
          z: clearStand.z + 0.5,
          dimension: clearStand.dimension,
        },
      }),
    );
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: {
        x: blockedStand.x + 0.5,
        y: blockedStand.y,
        z: blockedStand.z + 0.5,
        dimension: blockedStand.dimension,
      },
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "craft",
      recipeId: "minecraft:iron_pickaxe",
    }));
    expect(pathStartedBeforeReplacement).toBe(false);
  });

  it("clears a safe upper-rim obstruction after approaching lava", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const source = blockObservation({
      x: 0,
      y: -52,
      z: 0,
      dimension: "minecraft:overworld",
    }, {
      blockId: "minecraft:lava",
      properties: { level: "0" },
      replaceable: true,
    });
    const stand = {
      x: 2,
      y: -50,
      z: 0,
      dimension: source.position.dimension,
    } as const;
    const obstruction = blockObservation({
      x: 1,
      y: -51,
      z: 0,
      dimension: source.position.dimension,
    }, {
      blockId: "minecraft:deepslate",
      diggable: true,
    });
    const standVolume = [
      blockObservation(stand, {
        blockId: "minecraft:air",
        replaceable: true,
      }),
      blockObservation({ ...stand, y: stand.y + 1 }, {
        blockId: "minecraft:air",
        replaceable: true,
      }),
      blockObservation({ ...stand, y: stand.y - 1 }),
    ];
    driver.currentObservation = observation({
      position: {
        x: 8.5,
        y: -50,
        z: 0.5,
        dimension: source.position.dimension,
      },
      counts: {
        "minecraft:bucket": 1,
        "minecraft:cobblestone": 20,
        "minecraft:cooked_beef": 8,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:water_bucket": 1,
      },
      remainingDurability: { "minecraft:iron_pickaxe": 250 },
    });
    driver.blockQueryResolver = ({ center, radius, selector }) => {
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === "0"
      ) {
        return [source];
      }
      if (radius === 4.9 && Object.keys(selector).length === 0) {
        return standVolume;
      }
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
      };
      return standVolume.filter((block) =>
        block.position.x === position.x
        && block.position.y === position.y
        && block.position.z === position.z
      );
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (radius === 0.75) {
          driver.currentObservation = observation({
            position,
            counts: driver.currentObservation.inventory.counts,
            remainingDurability: { "minecraft:iron_pickaxe": 250 },
          });
        }
      });
    let obstructionCleared = false;
    driver.raycastResolver = ({ includeFluids }) =>
      includeFluids === true
        ? { block: source, distance: 2 }
        : obstructionCleared
        ? { distance: 2 }
        : { block: obstruction, distance: 1 };
    driver.actionResolver = (action) => {
      if (action.type === "look") {
        driver.currentObservation = observation({
          position: driver.currentObservation.player.position,
          counts: driver.currentObservation.inventory.counts,
          remainingDurability: { "minecraft:iron_pickaxe": 250 },
          rotation: { yaw: action.yaw, pitch: action.pitch },
        });
      }
      if (
        action.type === "dig-block"
        && action.position.x === obstruction.position.x
        && action.position.y === obstruction.position.y
        && action.position.z === obstruction.position.z
      ) {
        obstructionCleared = true;
      }
      return action.type === "use-item"
        ? Effect.never
        : Effect.succeed({});
    };
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "upper-rim-lava-source-run",
        teamId: "upper-rim-lava-source-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "upper-rim-lava-source-run",
        team: { teamId: "upper-rim-lava-source-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      for (
        let poll = 0;
        poll < 1_000
          && !driver.actions.some((action) => action.type === "use-item");
        poll += 1
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.actions).toContainEqual({
      type: "dig-block",
      position: obstruction.position,
    });
    expect(driver.actions).toContainEqual({
      type: "use-item",
      hand: "main",
    });
  });

  it("skips lava sources that require unsafe sightline mining", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const blockedSource = blockObservation({
      x: 0,
      y: -52,
      z: 0,
      dimension: "minecraft:overworld",
    }, {
      blockId: "minecraft:lava",
      properties: { level: "0" },
      replaceable: true,
    });
    const openSource = blockObservation({
      x: 8,
      y: -52,
      z: 0,
      dimension: "minecraft:overworld",
    }, {
      blockId: "minecraft:lava",
      properties: { level: "0" },
      replaceable: true,
    });
    const blockedStand = {
      x: 2,
      y: -50,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const openStand = {
      x: 6,
      y: -50,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    driver.currentObservation = observation({
      position: {
        x: 3.5,
        y: -50,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      counts: {
        "minecraft:bucket": 1,
        "minecraft:cobblestone": 20,
        "minecraft:cooked_beef": 8,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:water_bucket": 1,
      },
    });
    const standVolume = (stand: BeatGameBlockPosition) => [
      blockObservation(stand, {
        blockId: "minecraft:air",
        replaceable: true,
      }),
      blockObservation({ ...stand, y: stand.y + 1 }, {
        blockId: "minecraft:air",
        replaceable: true,
      }),
      blockObservation({ ...stand, y: stand.y - 1 }),
    ];
    driver.blockQueryResolver = ({ center, radius, selector }) => {
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === "0"
      ) {
        return [blockedSource, openSource];
      }
      if (radius === 4.9 && Object.keys(selector).length === 0) {
        return Math.floor(center.x) === blockedSource.position.x
          ? standVolume(blockedStand)
          : standVolume(openStand);
      }
      return [];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (radius === 0.75) {
          driver.currentObservation = observation({
            position,
            counts: driver.currentObservation.inventory.counts,
          });
        }
      });
    driver.raycastResolver = ({ direction, includeFluids }) =>
      direction.x < 0
        ? {
          block: blockObservation({
            x: 1,
            y: -52,
            z: 0,
            dimension: "minecraft:overworld",
          }, {
            blockId: "minecraft:deepslate",
            diggable: true,
          }),
          distance: 1,
        }
        : includeFluids === true
        ? { block: openSource, distance: 2 }
        : { distance: 2 };
    driver.actionResolver = (action) => {
      if (action.type === "look") {
        driver.currentObservation = observation({
          position: driver.currentObservation.player.position,
          counts: driver.currentObservation.inventory.counts,
          rotation: { yaw: action.yaw, pitch: action.pitch },
        });
      }
      return action.type === "use-item"
        ? Effect.never
        : Effect.succeed({});
    };
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "blocked-lava-source-run",
        teamId: "blocked-lava-source-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "blocked-lava-source-run",
        team: { teamId: "blocked-lava-source-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      while (!driver.actions.some((action) => action.type === "use-item")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    }).pipe(Effect.timeout("5 seconds"))));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: {
        x: blockedStand.x + 0.5,
        y: blockedStand.y,
        z: blockedStand.z + 0.5,
        dimension: blockedStand.dimension,
      },
      radius: 0.75,
    }));
    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: {
        x: openStand.x + 0.5,
        y: openStand.y,
        z: openStand.z + 0.5,
        dimension: openStand.dimension,
      },
      radius: 0.75,
    }));
    expect(driver.actions).not.toContainEqual(expect.objectContaining({
      type: "dig-block",
    }));
    expect(driver.actions).toContainEqual({
      type: "use-item",
      hand: "main",
    });
  });

  it("deduplicates shared lava interaction stands", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const source = blockObservation({
      x: 0,
      y: -52,
      z: 0,
      dimension: "minecraft:overworld",
    }, {
      blockId: "minecraft:lava",
      properties: { level: "0" },
      replaceable: true,
    });
    const stand = {
      x: 2.5,
      y: -50,
      z: 0.5,
      dimension: "minecraft:overworld",
    } as const;
    const standBlocks = [
      blockObservation({
        x: 2,
        y: -50,
        z: 0,
        dimension: stand.dimension,
      }, { blockId: "minecraft:air", replaceable: true }),
      blockObservation({
        x: 2,
        y: -49,
        z: 0,
        dimension: stand.dimension,
      }, { blockId: "minecraft:air", replaceable: true }),
      blockObservation({
        x: 2,
        y: -51,
        z: 0,
        dimension: stand.dimension,
      }),
    ];
    driver.currentObservation = observation({
      position: {
        x: 4.5,
        y: -50,
        z: 0.5,
        dimension: stand.dimension,
      },
      counts: {
        "minecraft:bucket": 1,
        "minecraft:cobblestone": 20,
        "minecraft:cooked_beef": 8,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:oak_log": 4,
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:water_bucket": 1,
      },
    });
    driver.blockQueryResolver = ({ radius, selector }) => {
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === "0"
      ) {
        return [source, source];
      }
      return radius === 4.9 && Object.keys(selector).length === 0
        ? standBlocks
        : [];
    };
    let resolveExcavationAttempted!: () => void;
    const excavationAttempted = new Promise<void>((resolve) => {
      resolveExcavationAttempted = resolve;
    });
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (policy.allowMining === true) {
          resolveExcavationAttempted();
        }
      }).pipe(
        Effect.zipRight(
          policy.allowMining === true
            ? Effect.never
            : Effect.fail(new BeatGameDriverError({
              operation: "pathfind",
              code: "unreachable",
              retryable: true,
              message: "No route found to the goal",
            })),
        ),
      );
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "deduplicate-lava-stand-run",
        teamId: "deduplicate-lava-stand-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "deduplicate-lava-stand-run",
        team: { teamId: "deduplicate-lava-stand-team" },
        checkpointStore: store,
        strategy: {
          observationPollMs: 1,
          portalStrategy: "CAST",
        },
      });
      yield* Effect.promise(() => excavationAttempted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.paths.filter(({ policy }) =>
      policy.allowMining === false
    )).toEqual([
      expect.objectContaining({ position: stand, radius: 0.75 }),
      expect.objectContaining({ position: stand, radius: 1.1 }),
    ]);
    expect(driver.paths.filter(({ policy }) =>
      policy.allowMining === true
    )).toEqual([expect.objectContaining({ position: stand })]);
  });

  it("excavates a dry side stand when lava has no open ledge", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const source = {
      x: 0,
      y: -52,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const excavatedStand = {
      x: 2,
      y: -52,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    driver.currentObservation = observation({
      position: {
        x: 4.5,
        y: -52,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      counts: {
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:cooked_beef": 8,
        "minecraft:iron_ingot": 7,
        "minecraft:bucket": 1,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_pickaxe": 1,
        "minecraft:shield": 1,
        "minecraft:water_bucket": 1,
      },
    });
    driver.blockQueryResolver = ({ selector }) => {
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === "0"
      ) {
        return [blockObservation(source, {
          blockId: "minecraft:lava",
          properties: { level: "0" },
          replaceable: true,
        })];
      }
      if (Object.keys(selector).length === 0) {
        return [
          blockObservation(excavatedStand),
          blockObservation({ ...excavatedStand, y: excavatedStand.y + 1 }),
          blockObservation({ ...excavatedStand, y: excavatedStand.y - 1 }),
        ];
      }
      return [];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (radius === 0.75) {
          driver.currentObservation = observation({
            position,
            counts: driver.currentObservation.inventory.counts,
          });
        }
      });
    driver.actionResolver = (action) => {
      if (action.type === "look") {
        driver.currentObservation = observation({
          position: driver.currentObservation.player.position,
          counts: driver.currentObservation.inventory.counts,
          rotation: { yaw: action.yaw, pitch: action.pitch },
        });
      }
      return action.type === "use-item"
        ? Effect.never
        : Effect.succeed({});
    };
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "excavate-lava-approach-run",
        teamId: "excavate-lava-approach-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "excavate-lava-approach-run",
        team: { teamId: "excavate-lava-approach-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            for (
              let attempt = 0;
              attempt < 1_000
              && !driver.actions.some((action) => action.type === "use-item");
              attempt += 1
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual({
      position: {
        x: 2.5,
        y: -52,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 0.75,
      policy: expect.objectContaining({
        allowMining: true,
        avoidFluids: true,
        maxFallDistance: 1,
      }),
    });
    expect(driver.actions).toContainEqual({
      type: "use-item",
      hand: "main",
    });
  });

  it("descends past sparse shallow lava when preparing a cast portal", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    driver.currentObservation = observation({
      counts: {
        "minecraft:bucket": 1,
        "minecraft:cobblestone": 120,
        "minecraft:cooked_beef": 12,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:water_bucket": 1,
      },
    });
    driver.blockQueryResolver = ({ center, selector }) => {
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === "0"
      ) {
        return [blockObservation({
          x: 4,
          y: 62,
          z: 0,
          dimension: "minecraft:overworld",
        }, {
          blockId: "minecraft:lava",
          properties: { level: "0" },
          replaceable: true,
        })];
      }
      if (
        selector.blockIds === undefined
        && selector.replaceable === undefined
      ) {
        return [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        })];
      }
      if (selector.replaceable === false) {
        return [blockObservation({
          x: 1,
          y: Math.floor(center.y) - 1,
          z: 0,
          dimension: center.dimension,
        })];
      }
      return selector.replaceable === true
        ? [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        }, {
          blockId: "minecraft:air",
          diggable: false,
          replaceable: true,
        })]
        : [];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.zipRight(position.y < 64 ? Effect.never : Effect.void),
      );
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "sparse-shallow-lava-run",
        teamId: "sparse-shallow-lava-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "sparse-shallow-lava-run",
        team: { teamId: "sparse-shallow-lava-team" },
        checkpointStore: store,
        strategy: {
          observationPollMs: 1,
          portalStrategy: "CAST",
        },
      });
      while (!driver.paths.some(({ position }) => position.y < 64)) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: expect.objectContaining({ y: 63 }),
    }));
    expect(driver.paths.some(({ radius }) => radius === 0.75)).toBe(false);
    expect(driver.actions.some((action) => action.type === "use-item")).toBe(
      false,
    );
  });

  it("upgrades its pickaxe and rescans for lava after descending", async () => {
    const driver = new FakeBeatGameDriver();
    const counts = {
      "minecraft:bucket": 1,
      "minecraft:cobblestone": 120,
      "minecraft:flint_and_steel": 1,
      "minecraft:iron_ingot": 8,
      "minecraft:cooked_beef": 12,
      "minecraft:oak_log": 12,
      "minecraft:shield": 1,
      "minecraft:stick": 3,
      "minecraft:stone_pickaxe": 1,
      "minecraft:stone_sword": 1,
      "minecraft:water_bucket": 1,
    };
    driver.currentObservation = observation({ counts });
    const surfaceTable = blockObservation({
      x: 1,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:crafting_table" });
    const deepTable = blockObservation({
      x: 1,
      y: -52,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:crafting_table" });
    let deepTablePlaced = false;
    let resolveDeepLavaRescan!: () => void;
    const deepLavaRescanned = new Promise<void>((resolve) => {
      resolveDeepLavaRescan = resolve;
    });
    driver.blockQueryResolver = ({ center, selector }) => {
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === "0"
        && center.y <= 52
      ) {
        resolveDeepLavaRescan();
        return [];
      }
      if (selector.blockIds?.includes("minecraft:crafting_table") === true) {
        return deepTablePlaced ? [surfaceTable, deepTable] : [surfaceTable];
      }
      if (
        selector.blockIds === undefined
        && selector.replaceable === undefined
      ) {
        return [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        }, { blockId: "minecraft:stone" })];
      }
      if (selector.replaceable === false) {
        return [blockObservation({
          x: 1,
          y: Math.floor(center.y) - 1,
          z: 0,
          dimension: center.dimension,
        })];
      }
      if (selector.replaceable === true) {
        return [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        }, {
          blockId: "minecraft:air",
          diggable: false,
          replaceable: true,
        })];
      }
      return [];
    };
    driver.recipeResolver = (resultItemId) => [{
      recipeId: resultItemId,
      recipeType: "minecraft:crafting",
      resultItemId,
      resultCount: 1,
      ingredients: [],
    }];
    driver.craftabilityResolver = (recipeId) => ({
      canCraft: true,
      maximumCraftCount: 1,
      ...(recipeId === "minecraft:crafting_table"
        ? {}
        : { requiredStation: "minecraft:crafting_table" }),
      missing: [],
    });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "build") {
          deepTablePlaced = true;
        }
        if (
          task.type === "craft"
          && task.recipeId === "minecraft:iron_pickaxe"
        ) {
          driver.currentObservation = observation({
            counts: {
              ...driver.currentObservation.inventory.counts,
              "minecraft:iron_ingot":
                (driver.currentObservation.inventory.counts[
                  "minecraft:iron_ingot"
              ] ?? 0) - 3,
              "minecraft:iron_pickaxe": 1,
            },
            position: driver.currentObservation.player.position,
          });
        }
      });
    driver.pathResolver = (position, radius, policy) => {
      driver.paths.push({ position, radius, policy });
      if (position.y < driver.currentObservation.player.position.y) {
        driver.currentObservation = observation({
          counts: driver.currentObservation.inventory.counts,
          position,
        });
        return Effect.void;
      }
      return Effect.void;
    };
    const store = new InMemoryBeatGameCheckpointStore();
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "lava-tool-run",
        teamId: "lava-tool-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "lava-tool-run",
        team: { teamId: "lava-tool-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => deepLavaRescanned).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks.map((task) => task.type === "craft"
      ? `${task.type}:${task.recipeId}`
      : task.type)).toEqual([
      "craft:minecraft:iron_pickaxe",
    ]);
    expect(driver.paths.filter(({ position }) => position.y < 64).map(
      ({ position }) => position.y,
    )).toEqual([63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52]);
    expect(driver.paths.at(-1)?.policy).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: true,
      maxFallDistance: 1,
    });
    expect(driver.blockQueries).toContainEqual(expect.objectContaining({
      center: expect.objectContaining({ y: 52 }),
      selector: {
        blockIds: ["minecraft:lava"],
        properties: { level: "0" },
      },
      maximumResults: 32,
    }));
  });

  it("replaces a worn stone pickaxe before a deep lava descent", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    driver.currentObservation = observation({
      counts: {
        "minecraft:bucket": 1,
        "minecraft:cobblestone": 20,
        "minecraft:cooked_beef": 8,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_ingot": 2,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
        "minecraft:water_bucket": 1,
      },
      remainingDurability: { "minecraft:stone_pickaxe": 1 },
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:crafting_table") === true
        ? [blockObservation({
          x: 1,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:crafting_table" })]
        : [];
    driver.recipeResolver = (resultItemId) => [{
      recipeId: resultItemId,
      recipeType: "minecraft:crafting",
      resultItemId,
      resultCount: 1,
      ingredients: [],
    }];
    driver.craftabilityResolver = () => ({
      canCraft: true,
      maximumCraftCount: 1,
      requiredStation: "minecraft:crafting_table",
      missing: [],
    });
    let resolveReplacementCrafted!: () => void;
    const replacementCrafted = new Promise<void>((resolve) => {
      resolveReplacementCrafted = resolve;
    });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (
          task.type === "craft"
          && task.recipeId === "minecraft:stone_pickaxe"
        ) {
          resolveReplacementCrafted();
        }
      });
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "deep-lava-pickaxe-run",
        teamId: "deep-lava-pickaxe-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "deep-lava-pickaxe-run",
        team: { teamId: "deep-lava-pickaxe-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => replacementCrafted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "craft",
      recipeId: "minecraft:stone_pickaxe",
    }));
  });

  it("descends before probing stands around substantially deeper lava", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const start = {
      x: 4.5,
      y: -34,
      z: 0.5,
      dimension: "minecraft:overworld",
    } as const;
    const source = blockObservation({
      x: 0,
      y: -60,
      z: 0,
      dimension: "minecraft:overworld",
    }, {
      blockId: "minecraft:lava",
      properties: { level: "0" },
      replaceable: true,
    });
    const dryStand = {
      x: 2,
      y: -58,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    driver.currentObservation = observation({
      position: start,
      counts: {
        "minecraft:bucket": 1,
        "minecraft:cobblestone": 120,
        "minecraft:cooked_beef": 8,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:water_bucket": 1,
      },
    });
    const dugBlocks = new Set<string>();
    let resolveDescentStarted!: () => void;
    const descentStarted = new Promise<void>((resolve) => {
      resolveDescentStarted = resolve;
    });
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        if (action.type === "dig-block") {
          dugBlocks.add(
            `${action.position.x}:${action.position.y}:${action.position.z}`,
          );
          resolveDescentStarted();
        }
        return {};
      });
    driver.blockQueryResolver = ({ center, radius, selector }) => {
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === "0"
      ) {
        return [source];
      }
      if (radius === 4.9 && Object.keys(selector).length === 0) {
        return [
          blockObservation(dryStand, {
            blockId: "minecraft:air",
            replaceable: true,
          }),
          blockObservation({ ...dryStand, y: dryStand.y + 1 }, {
            blockId: "minecraft:air",
            replaceable: true,
          }),
          blockObservation({ ...dryStand, y: dryStand.y - 1 }),
        ];
      }
      if (
        (radius === 0.25 || radius === 0.5)
        && Object.keys(selector).length === 0
      ) {
        const position = {
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        };
        const dug = dugBlocks.has(
          `${position.x}:${position.y}:${position.z}`,
        );
        return [blockObservation(position, dug
          ? {
            blockId: "minecraft:air",
            diggable: false,
            replaceable: true,
          }
          : { blockId: "minecraft:stone" })];
      }
      return [];
    };
    driver.pathResolver = (position, radius, policy) => {
      driver.paths.push({ position, radius, policy });
      return radius === 0.75
        ? Effect.fail(new BeatGameDriverError({
          operation: "pathfind",
          code: "unreachable",
          retryable: true,
          message: "The visible lava ledge is not connected yet",
        }))
        : Effect.void;
    };
    installStaircaseMovementSimulation(driver, {
      x: Math.floor(start.x),
      y: start.y,
      z: Math.floor(start.z),
      dimension: start.dimension,
    });
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "visible-deep-lava-run",
        teamId: "visible-deep-lava-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "visible-deep-lava-run",
        team: { teamId: "visible-deep-lava-team" },
        checkpointStore: store,
        strategy: {
          observationPollMs: 1,
          portalStrategy: "CAST",
        },
      });
      yield* Effect.promise(() => descentStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      radius: 0.75,
    }));
    expect(driver.actions).toContainEqual(expect.objectContaining({
      type: "dig-block",
    }));
  }, 15_000);

  it("returns to dry surface before retrying lava search from an aquifer", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const aquiferPosition = {
      x: 12.5,
      y: 54,
      z: -8.5,
      dimension: "minecraft:overworld",
    } as const;
    driver.currentObservation = observation({
      position: aquiferPosition,
      air: 195,
      counts: {
        "minecraft:bucket": 1,
        "minecraft:cobblestone": 120,
        "minecraft:cooked_beef": 12,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_ingot": 10,
        "minecraft:iron_pickaxe": 1,
        "minecraft:oak_log": 12,
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:water_bucket": 1,
      },
    });
    driver.surfaceColumns = [-1, 0, 1].flatMap((deltaX) =>
      [-1, 0, 1].map((deltaZ) => ({
        x: 12 + deltaX,
        z: -9 + deltaZ,
        loaded: true,
        surfaceY: 63,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      }))
    );
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds !== undefined) {
        return [];
      }
      if (selector.replaceable === false) {
        return [];
      }
      return [blockObservation({
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      }, {
        blockId: "minecraft:water",
        replaceable: true,
      })];
    };
    let resolveSurfaceRecovery!: () => void;
    const surfaceRecovered = new Promise<void>((resolve) => {
      resolveSurfaceRecovery = resolve;
    });
    let resolveRelocation!: () => void;
    const relocated = new Promise<void>((resolve) => {
      resolveRelocation = resolve;
    });
    driver.pathResolver = (position, radius, policy) =>
      Effect.sleep(50).pipe(
        Effect.zipRight(Effect.sync(() => {
          driver.paths.push({ position, radius, policy });
          if (position.y >= 64) {
            driver.currentObservation = observation({
              position,
              counts: driver.currentObservation.inventory.counts,
            });
            resolveSurfaceRecovery();
          }
        })),
      );
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
        resolveRelocation();
      });
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "aquifer-lava-recovery-run",
        teamId: "aquifer-lava-recovery-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "aquifer-lava-recovery-run",
        team: { teamId: "aquifer-lava-recovery-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => surfaceRecovered).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* Effect.promise(() => relocated).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: expect.objectContaining({ y: 64 }),
      policy: expect.objectContaining({
        allowMining: true,
        allowPlacing: true,
      }),
    }));
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: expect.objectContaining({ y: 53 }),
    }));
    expect(driver.xzPaths).toContainEqual(expect.objectContaining({
      dimension: "minecraft:overworld",
      policy: expect.objectContaining({
        avoidFluids: true,
      }),
    }));
  });

  it("continues lava search after relocating a flooded surface descent", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const start = {
      x: 0.5,
      y: 64,
      z: 0.5,
      dimension: "minecraft:overworld",
    } as const;
    driver.currentObservation = observation({
      position: start,
      counts: {
        "minecraft:bucket": 1,
        "minecraft:cobblestone": 120,
        "minecraft:cooked_beef": 12,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_ingot": 10,
        "minecraft:iron_pickaxe": 1,
        "minecraft:oak_log": 12,
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:water_bucket": 1,
      },
    });
    driver.surfaceColumns = [-1, 0, 1].flatMap((x) =>
      [-1, 0, 1].map((z) => ({
        x,
        z,
        loaded: true,
        surfaceY: 63,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      }))
    );
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds !== undefined) {
        return [];
      }
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      if (position.x === 0 && position.y === 63 && position.z === 0) {
        return [blockObservation(position)];
      }
      return [blockObservation(position, {
        blockId: "minecraft:water",
        replaceable: true,
        solid: false,
      })];
    };
    let resolveRelocation!: () => void;
    const relocated = new Promise<void>((resolve) => {
      resolveRelocation = resolve;
    });
    let relocationCount = 0;
    driver.xzPathResolver = (x, z, dimension, radius, policy) => {
      relocationCount += 1;
      driver.xzPaths.push({ x, z, dimension, radius, policy });
      if (relocationCount > 1) {
        return Effect.never;
      }
      return Effect.sync(() => {
        driver.currentObservation = observation({
          position: {
            ...driver.currentObservation.player.position,
            x,
            z,
            dimension,
          },
          counts: driver.currentObservation.inventory.counts,
        });
        resolveRelocation();
      });
    };
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "surface-lava-relocation-run",
        teamId: "surface-lava-relocation-team",
      },
    ), undefined));
    const actionEvents: string[] = [];
    let resolveSearchContinued!: () => void;
    const searchContinued = new Promise<void>((resolve) => {
      resolveSearchContinued = resolve;
    });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "surface-lava-relocation-run",
        team: { teamId: "surface-lava-relocation-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      yield* run.events.pipe(
        Stream.runForEach((event) =>
          "action" in event && event.action === "satisfy:lava-bucket"
            ? Effect.sync(() => {
              actionEvents.push(
                `${event.type}:${"detail" in event ? event.detail ?? "" : ""}`,
              );
              if (event.type === "action-succeeded") {
                resolveSearchContinued();
              }
            })
            : Effect.void
        ),
        Effect.forkScoped,
      );
      yield* Effect.promise(() => relocated).pipe(
        Effect.timeoutFail({
          duration: "5 seconds",
          onTimeout: () => new Error("Timed out waiting for relocation"),
        }),
      );
      yield* Effect.promise(() => searchContinued).pipe(
        Effect.timeoutFail({
          duration: "5 seconds",
          onTimeout: () =>
            new Error("Timed out waiting for lava search continuation"),
        }),
      );
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.xzPaths).toContainEqual(expect.objectContaining({
      dimension: "minecraft:overworld",
      policy: expect.objectContaining({ avoidFluids: true }),
    }));
    expect(actionEvents).toContain("action-succeeded:");
  }, 15_000);

  it("searches for a lava pool before casting with a lone source", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const start = {
      x: 12.5,
      y: 54,
      z: -8.5,
      dimension: "minecraft:overworld",
    } as const;
    driver.currentObservation = observation({
      position: start,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:cooked_beef": 8,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:lava_bucket": 1,
        "minecraft:oak_log": 4,
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:water_bucket": 1,
      },
    });
    driver.blockQueryResolver = ({ center, selector }) => {
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === "0"
      ) {
        return [blockObservation({
          x: 14,
          y: 38,
          z: -8,
          dimension: "minecraft:overworld",
        }, {
          blockId: "minecraft:lava",
          properties: { level: "0" },
          replaceable: true,
        })];
      }
      if (selector.replaceable === true) {
        return [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        }, { blockId: "minecraft:air", replaceable: true })];
      }
      if (
        selector.blockIds === undefined
        && selector.replaceable === undefined
      ) {
        if (
          Math.floor(center.x) === 13
          && Math.floor(center.y) === 53
          && Math.floor(center.z) === -9
        ) {
          return [blockObservation({
            x: 13,
            y: 53,
            z: -9,
            dimension: center.dimension,
          }, {
            blockId: "minecraft:water",
            replaceable: true,
          })];
        }
        return [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        }, { blockId: "minecraft:stone" })];
      }
      return [];
    };
    let resolvePoolSearch!: () => void;
    const poolSearchStarted = new Promise<void>((resolve) => {
      resolvePoolSearch = resolve;
    });
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        driver.currentObservation = observation({
          position,
          counts: driver.currentObservation.inventory.counts,
        });
        if (position.y === 42) {
          resolvePoolSearch();
        }
      });
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "portal-lava-pool-run",
        teamId: "portal-lava-pool-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "portal-lava-pool-run",
        team: { teamId: "portal-lava-pool-team" },
        checkpointStore: store,
        strategy: {
          observationPollMs: 1,
          portalStrategy: "CAST",
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* Effect.promise(() => poolSearchStarted).pipe(
              Effect.timeout("5 seconds"),
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: {
        x: 0.5,
        y: 42,
        z: -8.5,
        dimension: "minecraft:overworld",
      },
      radius: 0.5,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        avoidFluids: true,
        maxFallDistance: 1,
      }),
    }));
    expect(driver.actions).not.toContainEqual(expect.objectContaining({
      type: "use-item",
    }));
  });

  it("builds a cast portal beside a discovered lava pool", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const start = {
      x: 4.5,
      y: 70,
      z: 0.5,
      dimension: "minecraft:overworld",
    } as const;
    const source = blockObservation({
      x: 0,
      y: 38,
      z: 0,
      dimension: "minecraft:overworld",
    }, {
      blockId: "minecraft:lava",
      properties: { level: "0" },
      replaceable: true,
    });
    const safeStand = {
      x: 2.5,
      y: 40,
      z: 0.5,
      dimension: "minecraft:overworld",
    } as const;
    driver.currentObservation = observation({
      position: start,
      counts: {
        "minecraft:bucket": 1,
        "minecraft:cobblestone": 20,
        "minecraft:cooked_beef": 8,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:lava_bucket": 1,
        "minecraft:oak_log": 4,
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:water_bucket": 1,
      },
    });
    const floorQueries: Array<Readonly<{
      x: number;
      y: number;
      z: number;
    }>> = [];
    let resolvePortalFloorQueried!: () => void;
    const portalFloorQueried = new Promise<void>((resolve) => {
      resolvePortalFloorQueried = resolve;
    });
    driver.blockQueryResolver = ({ center, radius, selector }) => {
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === "0"
      ) {
        return Array.from({ length: 9 }, () => source);
      }
      if (radius === 4.9 && Object.keys(selector).length === 0) {
        return [
          blockObservation({
            x: 2,
            y: 40,
            z: 0,
            dimension: safeStand.dimension,
          }, { blockId: "minecraft:air", replaceable: true }),
          blockObservation({
            x: 2,
            y: 41,
            z: 0,
            dimension: safeStand.dimension,
          }, { blockId: "minecraft:air", replaceable: true }),
          blockObservation({
            x: 2,
            y: 39,
            z: 0,
            dimension: safeStand.dimension,
          }),
        ];
      }
      if (radius === 0.25 && selector.replaceable === false) {
        floorQueries.push({ x: center.x, y: center.y, z: center.z });
        if (center.x === 1.5) {
          resolvePortalFloorQueried();
        }
        return [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        })];
      }
      if (radius === 0.25 && Object.keys(selector).length === 0) {
        const position = {
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        };
        if (
          position.x === Math.floor(safeStand.x)
          && position.z === Math.floor(safeStand.z)
          && position.y >= safeStand.y - 1
          && position.y <= safeStand.y + 1
        ) {
          return [blockObservation(position, position.y === safeStand.y - 1
            ? {}
            : {
              blockId: "minecraft:air",
              replaceable: true,
            })];
        }
        return [blockObservation({
          ...position,
        }, {
          ...(position.x === 2 && position.y === 42 && position.z === 2
            ? {
              blockId: "minecraft:bedrock",
              diggable: false,
              replaceable: false,
            }
            : {
              blockId: "minecraft:air",
              replaceable: true,
            }),
        })];
      }
      return [];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (radius === 0.75) {
          driver.currentObservation = observation({
            position,
            counts: driver.currentObservation.inventory.counts,
          });
        }
      });
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "portal-beside-lava-run",
        teamId: "portal-beside-lava-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "portal-beside-lava-run",
        team: { teamId: "portal-beside-lava-team" },
        checkpointStore: store,
        strategy: {
          observationPollMs: 1,
          portalStrategy: "CAST",
        },
      });
      yield* Effect.promise(() => portalFloorQueried).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.paths).toContainEqual({
      position: safeStand,
      radius: 0.75,
      policy: expect.objectContaining({
        avoidFluids: true,
        maxFallDistance: 1,
      }),
    });
    expect(floorQueries.length).toBeGreaterThan(1);
    expect(new Set(floorQueries.map(({ y }) => y))).toEqual(new Set([40.5]));
    expect(floorQueries.slice(0, 2)).toEqual([
      { x: 2.5, y: 40.5, z: 2.5 },
      { x: 1.5, y: 40.5, z: 2.5 },
    ]);
  });

  it("replaces a pickaxe consumed while approaching portal lava", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const start = {
      x: 4.5,
      y: 70,
      z: 0.5,
      dimension: "minecraft:overworld",
    } as const;
    const source = blockObservation({
      x: 0,
      y: 38,
      z: 0,
      dimension: "minecraft:overworld",
    }, {
      blockId: "minecraft:lava",
      properties: { level: "0" },
      replaceable: true,
    });
    const safeStand = {
      x: 2.5,
      y: 40,
      z: 0.5,
      dimension: "minecraft:overworld",
    } as const;
    driver.currentObservation = observation({
      position: start,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:cooked_beef": 8,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:lava_bucket": 1,
        "minecraft:oak_log": 4,
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:water_bucket": 1,
      },
      remainingDurability: { "minecraft:iron_pickaxe": 48 },
    });
    driver.blockQueryResolver = ({ radius, selector }) => {
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === "0"
      ) {
        return Array.from({ length: 9 }, () => source);
      }
      if (
        selector.blockIds?.includes("minecraft:crafting_table") === true
      ) {
        return [blockObservation({
          x: 3,
          y: 40,
          z: 0,
          dimension: safeStand.dimension,
        }, { blockId: "minecraft:crafting_table" })];
      }
      if (radius === 4.9 && Object.keys(selector).length === 0) {
        return [
          blockObservation({
            x: 2,
            y: 40,
            z: 0,
            dimension: safeStand.dimension,
          }, { blockId: "minecraft:air", replaceable: true }),
          blockObservation({
            x: 2,
            y: 41,
            z: 0,
            dimension: safeStand.dimension,
          }, { blockId: "minecraft:air", replaceable: true }),
          blockObservation({
            x: 2,
            y: 39,
            z: 0,
            dimension: safeStand.dimension,
          }),
        ];
      }
      return [];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (
          radius === 0.75
          && position.x === safeStand.x
          && position.y === safeStand.y
          && position.z === safeStand.z
        ) {
          driver.currentObservation = observation({
            position,
            counts: Object.fromEntries(
              Object.entries(driver.currentObservation.inventory.counts)
                .filter(([itemId]) =>
                  itemId !== "minecraft:iron_pickaxe"
                ),
            ),
            remainingDurability: {},
          });
        }
      });
    driver.recipeResolver = (resultItemId) => [{
      recipeId: resultItemId,
      recipeType: "minecraft:crafting",
      resultItemId,
      resultCount: 1,
      ingredients: [],
    }];
    driver.craftabilityResolver = () => ({
      canCraft: true,
      maximumCraftCount: 1,
      requiredStation: "minecraft:crafting_table",
      missing: [],
    });
    let resolveReplacementCrafted!: () => void;
    const replacementCrafted = new Promise<void>((resolve) => {
      resolveReplacementCrafted = resolve;
    });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (
          task.type === "craft"
          && task.recipeId === "minecraft:iron_pickaxe"
        ) {
          driver.currentObservation = observation({
            position: driver.currentObservation.player.position,
            counts: {
              ...driver.currentObservation.inventory.counts,
              "minecraft:iron_pickaxe": 1,
            },
            remainingDurability: { "minecraft:iron_pickaxe": 251 },
          });
          resolveReplacementCrafted();
        }
      });
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "portal-approach-pickaxe-run",
        teamId: "portal-approach-pickaxe-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "portal-approach-pickaxe-run",
        team: { teamId: "portal-approach-pickaxe-team" },
        checkpointStore: store,
        strategy: {
          observationPollMs: 1,
          portalStrategy: "CAST",
        },
      });
      yield* Effect.promise(() => replacementCrafted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "craft",
      recipeId: "minecraft:iron_pickaxe",
    }));
  });

  it("replaces a worn pickaxe before descending for portal lava", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const start = {
      x: 12.5,
      y: 54,
      z: -8.5,
      dimension: "minecraft:overworld",
    } as const;
    driver.currentObservation = observation({
      position: start,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:cooked_beef": 8,
        "minecraft:flint_and_steel": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:lava_bucket": 1,
        "minecraft:oak_log": 4,
        "minecraft:shield": 1,
        "minecraft:stone_sword": 1,
        "minecraft:water_bucket": 1,
      },
      remainingDurability: { "minecraft:iron_pickaxe": 1 },
    });
    driver.blockQueryResolver = ({ selector }) => {
      if (selector.blockIds?.includes("minecraft:crafting_table") === true) {
        return [blockObservation({
          x: 11,
          y: 54,
          z: -8,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:crafting_table" })];
      }
      if (
        selector.blockIds?.includes("minecraft:lava") === true
        && selector.properties?.level === "0"
      ) {
        return [blockObservation({
          x: 14,
          y: 38,
          z: -8,
          dimension: "minecraft:overworld",
        }, {
          blockId: "minecraft:lava",
          properties: { level: "0" },
          replaceable: true,
        })];
      }
      return [];
    };
    driver.recipeResolver = (resultItemId) => [{
      recipeId: resultItemId,
      recipeType: "minecraft:crafting",
      resultItemId,
      resultCount: 1,
      ingredients: [],
    }];
    driver.craftabilityResolver = () => ({
      canCraft: true,
      maximumCraftCount: 1,
      requiredStation: "minecraft:crafting_table",
      missing: [],
    });
    let resolveReplacementCrafted!: () => void;
    const replacementCrafted = new Promise<void>((resolve) => {
      resolveReplacementCrafted = resolve;
    });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (
          task.type === "craft"
          && task.recipeId === "minecraft:iron_pickaxe"
        ) {
          driver.currentObservation = observation({
            position: driver.currentObservation.player.position,
            counts: {
              ...driver.currentObservation.inventory.counts,
              "minecraft:iron_pickaxe": 2,
            },
            remainingDurability: { "minecraft:iron_pickaxe": 251 },
          });
          resolveReplacementCrafted();
        }
      });
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "portal-lava-pickaxe-run",
        teamId: "portal-lava-pickaxe-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "portal-lava-pickaxe-run",
        team: { teamId: "portal-lava-pickaxe-team" },
        checkpointStore: store,
        strategy: {
          observationPollMs: 1,
          portalStrategy: "CAST",
        },
      });
      yield* Effect.promise(() => replacementCrafted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "craft",
      recipeId: "minecraft:iron_pickaxe",
    }));
  });

  it("recycles placed gravel until it produces flint", async () => {
    const driver = new FakeBeatGameDriver();
    const wetSupport = {
      x: 1,
      y: 63,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const firstSupport = {
      x: 2,
      y: 63,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const secondSupport = { ...firstSupport, x: 3 };
    const supports = [wetSupport, firstSupport, secondSupport] as const;
    let gravelPlaced = false;
    let placedTarget: BeatGameBlockPosition = {
      ...firstSupport,
      y: firstSupport.y + 1,
    };
    let digs = 0;
    driver.currentObservation = observation({
      counts: {
        "minecraft:cooked_beef": 8,
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:stone_pickaxe": 1,
        "minecraft:water_bucket": 1,
        "minecraft:shield": 1,
        "minecraft:gravel": 1,
      },
    });
    driver.blockQueryResolver = (query) => {
      if (
        query.selector.blockIds?.includes("minecraft:gravel")
        && gravelPlaced
      ) {
        return [blockObservation(placedTarget, {
          blockId: "minecraft:gravel",
        })];
      }
      if (
        query.selector.blockIds?.includes("minecraft:water")
        && Math.floor(query.center.x) === wetSupport.x
        && Math.floor(query.center.y) === wetSupport.y + 1
        && Math.floor(query.center.z) === wetSupport.z
      ) {
        return [blockObservation({
          ...wetSupport,
          y: wetSupport.y + 1,
        }, {
          blockId: "minecraft:water",
          replaceable: true,
        })];
      }
      if (query.selector.replaceable === false) {
        return supports.map((support) => blockObservation(support));
      }
      if (query.selector.replaceable === true) {
        const candidate = {
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        };
        return [blockObservation(candidate, {
          blockId: "minecraft:air",
          diggable: false,
          replaceable: true,
        })];
      }
      return [];
    };
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        if (action.type === "place-block") {
          gravelPlaced = true;
          placedTarget = {
            ...action.against,
            y: action.against.y + 1,
          };
        }
        if (action.type === "dig-block") {
          digs += 1;
          gravelPlaced = false;
          driver.currentObservation = observation({
            position: {
              x: placedTarget.x + 0.5,
              y: placedTarget.y,
              z: placedTarget.z + 0.5,
            },
            counts: {
              ...driver.currentObservation.inventory.counts,
              "minecraft:gravel": digs === 1 ? 1 : 0,
              ...(digs === 1 ? {} : { "minecraft:flint": 1 }),
            },
          });
        }
        return {};
      });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              driver.actions.filter((action) => action.type === "dig-block")
                  .length < 2
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions).toContainEqual({
      type: "select-item",
      selector: { itemIds: ["minecraft:gravel"] },
    });
    expect(driver.actions).toContainEqual({
      type: "place-block",
      against: firstSupport,
      face: "up",
      hand: "main",
    });
    expect(driver.actions).toContainEqual({
      type: "dig-block",
      position: { ...firstSupport, y: firstSupport.y + 1 },
    });
    expect(driver.actions).toContainEqual({
      type: "place-block",
      against: secondSupport,
      face: "up",
      hand: "main",
    });
    expect(driver.actions).toContainEqual({
      type: "dig-block",
      position: { ...secondSupport, y: secondSupport.y + 1 },
    });
    expect(driver.actions).not.toContainEqual({
      type: "place-block",
      against: wetSupport,
      face: "up",
      hand: "main",
    });
    expect(driver.paths.filter(({ radius }) => radius === 3).every(
      ({ policy }) => policy.avoidFluids === true,
    )).toBe(true);
  });

  it("collects replacement gravel without entering fluid", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:cooked_beef": 8,
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:stone_pickaxe": 1,
        "minecraft:water_bucket": 1,
        "minecraft:shield": 1,
      },
    });
    let resolveGravelCollection!: () => void;
    const gravelCollectionStarted = new Promise<void>((resolve) => {
      resolveGravelCollection = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (
        task.type === "collect-blocks"
        && task.blockIds.includes("minecraft:gravel")
      ) {
        resolveGravelCollection();
        return Effect.never;
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => gravelCollectionStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks.at(-1)).toMatchObject({
      type: "collect-blocks",
      blockIds: ["minecraft:gravel"],
      count: 8,
      avoidSubmergedTargets: true,
    });
    expect(driver.taskPolicies.at(-1)?.avoidFluids).toBe(true);
  });

  it("relocates over dry terrain when nearby gravel makes no progress", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:cooked_beef": 8,
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:stone_pickaxe": 1,
        "minecraft:water_bucket": 1,
        "minecraft:shield": 1,
      },
    });
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (driver.xzPaths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "collect-blocks",
      blockIds: ["minecraft:gravel"],
      avoidSubmergedTargets: true,
    }));
    expect(driver.xzPaths[0]).toMatchObject({
      x: 24,
      z: 0,
      dimension: "minecraft:overworld",
      radius: 2,
      policy: {
        allowMining: false,
        allowPlacing: true,
        avoidFluids: true,
      },
    });
  });

  it("uses a distinct idempotency key for repeated task invocations", async () => {
    const driver = new FakeBeatGameDriver();
    const task = {
      type: "collect-blocks" as const,
      blockIds: ["minecraft:oak_log"],
      count: 1,
      searchRadius: 32,
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "task-invocation-run",
        team: { teamId: "task-invocation-team" },
        strategy: { observationPollMs: 1 },
        hooks: {
          satisfyRequirement: ({ driver: actionDriver, strategy }) =>
            Effect.gen(function* () {
              yield* actionDriver.runTask(task, strategy.path);
              yield* actionDriver.runTask(task, strategy.path);
              return yield* Effect.never;
            }),
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.taskExecutions.length < 2) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const keys = driver.taskExecutions.map(({ idempotencyKey }) =>
      idempotencyKey
    );
    expect(keys).toHaveLength(2);
    expect(keys[0]).toMatch(
      /^beat-game:[0-9a-f-]{36}:[0-9a-f]{16}:1:[0-9a-f]{16}$/u,
    );
    expect(keys[1]).toMatch(
      /^beat-game:[0-9a-f-]{36}:[0-9a-f]{16}:2:[0-9a-f]{16}$/u,
    );
    expect(keys[0]).not.toBe(keys[1]);
  });

  it("explores for resources without tunneling and may bridge terrain", async () => {
    const driver = new FakeBeatGameDriver();

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const collectionIndex = driver.tasks.findIndex((task) =>
      task.type === "collect-blocks"
    );
    expect(collectionIndex).toBeGreaterThanOrEqual(0);
    expect(driver.taskPolicies[collectionIndex]).toMatchObject({
      allowMining: true,
      allowPlacing: true,
    });
    expect(driver.xzPaths[0]).toMatchObject({
      x: 24,
      z: 0,
      dimension: "minecraft:overworld",
      radius: 2,
      policy: {
        allowMining: false,
        allowPlacing: true,
      },
    });
    expect(driver.tasks.some((task) => task.type === "explore")).toBe(false);
  });

  it("keeps Overworld exploration on a sampled surface", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = [{
      x: 24,
      z: 0,
      loaded: true,
      surfaceY: 64,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.paths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths[0]).toEqual({
      position: {
        x: 24.5,
        y: 65,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 2,
      policy: {
        allowMining: false,
        allowPlacing: true,
        maxFallDistance: 3,
        maxSearchTimeMs: 30_000,
      },
    });
    expect(driver.xzPaths).toHaveLength(0);
  });

  it("explores horizontally instead of pillaring to a high overhang", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 0.5,
        y: 78,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
    });
    driver.surfaceColumns = [{
      x: 24,
      z: 0,
      loaded: true,
      surfaceY: 108,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:windswept_hills",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toHaveLength(0);
    expect(driver.xzPaths[0]).toEqual(expect.objectContaining({
      x: 24.5,
      z: 0.5,
      dimension: "minecraft:overworld",
      radius: 2,
    }));
  });

  it("pursues fish through water after critical-hunger exploration", async () => {
    const driver = new FakeBeatGameDriver();
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 40,
      entityType: "minecraft:salmon",
      position: {
        x: 3,
        y: 61,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    const deepSalmon = {
      ...salmon,
      networkId: 41,
      position: {
        ...salmon.position,
        x: 2,
        y: 44,
      },
    } as const;
    const distantSalmon = {
      ...salmon,
      networkId: 42,
      position: {
        ...salmon.position,
        x: 12,
      },
    } as const;
    driver.currentObservation = observation({ food: 5, health: 8 });
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
        driver.entityResults = [deepSalmon, distantSalmon, salmon];
      }).pipe(
        Effect.zipRight(Effect.fail(new BeatGameDriverError({
          operation: "pathfindXZ",
          code: "unreachable",
          retryable: true,
          message: "The dry route is blocked by water",
        }))),
      );
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        driver.currentObservation = observation({
          position,
          food: 5,
          health: 8,
        });
      });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.entityResults = [];
        }
      });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.xzPaths).toHaveLength(1);
    expect(driver.xzPaths[0]).toMatchObject({
      x: 16,
      z: 0,
      policy: { avoidFluids: false },
    });
    expect(driver.xzPaths[0]?.policy.maxFallDistance).toBe(3);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      sprinting: true,
      target: expect.objectContaining({
        connectionEpoch: salmon.connectionEpoch,
        networkId: salmon.networkId,
      }),
    }));
    const attackIndex = driver.tasks.findIndex(
      (task) => task.type === "attack-entity",
    );
    expect(driver.taskPolicies[attackIndex]).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: false,
      sprint: true,
    });
    expect(driver.entityQueries.find(({ selector }) =>
      selector.entityTypes?.includes("minecraft:chicken") === true
    )?.selector.entityTypes).toEqual([
      "minecraft:cow",
      "minecraft:mooshroom",
      "minecraft:pig",
      "minecraft:rabbit",
      "minecraft:sheep",
      "minecraft:chicken",
      "minecraft:cod",
      "minecraft:salmon",
    ]);
  });

  it("resumes a critical aquatic food hunt after replenishing air", async () => {
    const driver = new FakeBeatGameDriver();
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 48,
      entityType: "minecraft:salmon",
      position: {
        x: 20,
        y: 61,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      food: 5,
      health: 8,
      counts: { "minecraft:wooden_sword": 1 },
    });
    driver.entityResults = [salmon];
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
          && driver.currentObservation.player.position.x >= 2
        ? [blockObservation({
          x: Math.floor(query.center.x),
          y: Math.floor(query.center.y),
          z: Math.floor(query.center.z),
          dimension: query.center.dimension,
        }, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
        })]
        : [];
    let pursuits = 0;
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type !== "attack-entity") {
          return false;
        }
        pursuits += 1;
        if (pursuits === 1) {
          driver.currentObservation = observation({
            food: 5,
            health: 8,
            air: 100,
            position: {
              x: salmon.position.x,
              y: 59,
              z: salmon.position.z,
              dimension: salmon.position.dimension,
            },
            counts: { "minecraft:wooden_sword": 1 },
          });
          return true;
        }
        driver.entityResults = [];
        return false;
      }).pipe(
        Effect.flatMap((awaitAirRecovery) =>
          awaitAirRecovery ? Effect.never : Effect.void
        ),
      );
    driver.actionObserver = (action) => {
      if (
        action.type !== "set-movement"
        || action.forward !== true
        || action.jump !== true
      ) {
        return;
      }
      driver.currentObservation = observation({
        food: 5,
        health: 8,
        air: 300,
        position: {
          x: salmon.position.x,
          y: 62,
          z: salmon.position.z,
          dimension: salmon.position.dimension,
        },
        counts: { "minecraft:wooden_sword": 1 },
      });
    };
    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        driver.tasks.filter((task) => task.type === "attack-entity").length
          < 2
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.actions).toContainEqual(expect.objectContaining({
      type: "look",
      pitch: -90,
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: salmon.networkId }),
    }));
    expect(driver.paths).toHaveLength(0);
    expect(driver.surfaceQueries.every(({ radius }) => radius === 4)).toBe(
      true,
    );
  }, 10_000);

  it("crosses water when a healthy food search has no dry route", async () => {
    const driver = new FakeBeatGameDriver();
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:salmon",
      position: {
        x: 3,
        y: 61,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      food: 12,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [salmon];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(
        Effect.zipRight(
          policy.avoidFluids === true
            ? Effect.fail(new BeatGameDriverError({
              operation: "pathfindXZ",
              code: "unreachable",
              retryable: true,
              message: "The bot is stranded by water",
            }))
            : Effect.never,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length < 2) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
    expect(driver.xzPaths[0]?.policy.avoidFluids).toBe(true);
    expect(driver.xzPaths[1]?.policy.avoidFluids).toBe(false);
  }, 10_000);

  it("prefers a shallow fish during a critical aquatic hunt", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 20,
      food: 6,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    const deepSalmon = {
      connectionEpoch: "epoch-1",
      networkId: 47,
      entityType: "minecraft:salmon",
      position: {
        x: 3,
        y: 57,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    const shallowSalmon = {
      ...deepSalmon,
      networkId: 48,
      position: {
        ...deepSalmon.position,
        x: 10,
        y: 62,
      },
    } as const;
    driver.entityResults = [deepSalmon, shallowSalmon];
    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "attack-entity")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: shallowSalmon.networkId }),
    }));
    expect(driver.paths).toHaveLength(0);
    const attackIndex = driver.tasks.findIndex(
      (task) => task.type === "attack-entity",
    );
    expect(driver.taskPolicies[attackIndex]).toMatchObject({
      avoidFluids: false,
      sprint: true,
    });
  }, 10_000);

  it("finishes a nearby wounded fish during a critical aquatic hunt", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 20,
      food: 6,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    const healthyCod = {
      connectionEpoch: "epoch-1",
      networkId: 49,
      entityType: "minecraft:cod",
      position: {
        x: 3,
        y: 62,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    const woundedCod = {
      ...healthyCod,
      networkId: 50,
      position: {
        ...healthyCod.position,
        x: 8,
        y: 60.5,
      },
      health: 1,
    } as const;
    driver.entityResults = [healthyCod, woundedCod];
    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "attack-entity")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: woundedCod.networkId }),
    }));
    expect(driver.paths).toHaveLength(0);
  }, 10_000);

  it("retries the same fish after a bounded aquatic chase expires", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 20,
      food: 6,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 51,
      entityType: "minecraft:salmon",
      position: {
        x: 2,
        y: 63,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 2,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityResults = [salmon];
    driver.surfaceColumns = [{
      x: 2,
      z: 0,
      loaded: true,
      surfaceY: 63,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        driver.currentObservation = observation({
          position,
          health: 20,
          food: 6,
          counts: driver.currentObservation.inventory.counts,
        });
      });
    let attacks = 0;
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          attacks += 1;
          if (attacks === 1) {
            driver.currentObservation = observation({
              position: {
                x: salmon.position.x,
                y: 60,
                z: salmon.position.z,
                dimension: salmon.position.dimension,
              },
              health: 20,
              food: 6,
              counts: driver.currentObservation.inventory.counts,
            });
          }
        }
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity"
            ? Effect.fail(new BeatGameDriverError({
              operation: "task.attack-entity",
              code: "aquatic_chase_timeout",
              retryable: true,
              message: "The fish moved out of reach",
            }))
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        driver.tasks.filter((task) => task.type === "attack-entity").length < 2
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(
      driver.tasks
        .filter((task) => task.type === "attack-entity")
        .slice(0, 2)
        .map((task) => task.type === "attack-entity"
          ? task.target.networkId
          : undefined),
    ).toEqual([salmon.networkId, salmon.networkId]);
    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: {
        x: 2.5,
        y: 64,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
    }));
  }, 10_000);

  it("surfaces and resumes the same aquatic target when air runs low", async () => {
    const driver = new FakeBeatGameDriver();
    const foodProvisioningFailures: string[] = [];
    driver.currentObservation = observation({
      health: 20,
      food: 6,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 52,
      entityType: "minecraft:salmon",
      position: {
        x: 2,
        y: 63,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityResults = [salmon];
    let attacks = 0;
    let ascending = false;
    let airAtAscentStart: number | undefined;
    let airAtAscentRelease: number | undefined;
    driver.blockQueryResolver = () =>
      driver.currentObservation.player.air < 120
        ? [blockObservation(
          {
            x: 0,
            y: 64,
            z: 0,
            dimension: "minecraft:overworld",
          },
          { blockId: "minecraft:water", replaceable: true },
        )]
        : [];
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        if (action.type === "set-movement") {
          ascending = true;
          airAtAscentStart = driver.currentObservation.player.air;
        }
        if (action.type === "reset-movement" && ascending) {
          ascending = false;
          airAtAscentRelease = driver.currentObservation.player.air;
        }
        return {};
      });
    driver.observationResolver = () =>
      Effect.sync(() => {
        if (
          ascending
          && driver.currentObservation.player.air < 300
        ) {
          driver.currentObservation = observation({
            health: 20,
            food: 6,
            air: Math.min(
              300,
              driver.currentObservation.player.air + 20,
            ),
            counts: driver.currentObservation.inventory.counts,
          });
        }
        return driver.currentObservation;
      });
    driver.taskResolver = (task) =>
      Effect.suspend(() => {
        driver.tasks.push(task);
        if (task.type !== "attack-entity") {
          return Effect.void;
        }
        attacks += 1;
        if (attacks === 1) {
          driver.currentObservation = observation({
            health: 20,
            food: 6,
            air: 195,
            counts: driver.currentObservation.inventory.counts,
          });
          return Effect.never;
        }
        driver.entityResults = [];
        return Effect.void;
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* run.events.pipe(
        Stream.runForEach((event) =>
          event.type === "action-failed"
              && event.action === "satisfy:food-supply"
            ? Effect.sync(() => {
              foodProvisioningFailures.push(event.detail ?? "");
            })
            : Effect.void
        ),
        Effect.forkScoped,
      );
      while (
        driver.tasks.filter((task) => task.type === "attack-entity").length < 1
      ) {
        yield* Effect.sleep(1);
      }
      yield* Effect.sleep(10);
      expect(
        driver.tasks.filter((task) => task.type === "attack-entity"),
      ).toHaveLength(1);
      driver.currentObservation = observation({
        health: 20,
        food: 6,
        air: 100,
        counts: driver.currentObservation.inventory.counts,
      });
      while (
        driver.tasks.filter((task) => task.type === "attack-entity").length < 2
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(
      driver.tasks
        .filter((task) => task.type === "attack-entity")
        .slice(0, 2)
        .map((task) => task.type === "attack-entity"
          ? task.target.networkId
          : undefined),
    ).toEqual([salmon.networkId, salmon.networkId]);
    expect(driver.surfaceQueries).not.toHaveLength(0);
    expect(driver.surfaceQueries.every(({ radius }) => radius === 4)).toBe(
      true,
    );
    expect(airAtAscentRelease).toBeGreaterThan(airAtAscentStart ?? 300);
    expect(airAtAscentRelease).toBeLessThan(300);
    expect(foodProvisioningFailures).not.toContain(
      "Interrupted for replanning: air fell below the safety threshold",
    );
  }, 10_000);

  it("searches on land instead of chasing fish above critical hunger", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 20,
      food: 8,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 49,
      entityType: "minecraft:salmon",
      position: {
        x: 3,
        y: 62,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (driver.xzPaths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
    expect(driver.xzPaths[0]?.policy).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: true,
      sprint: false,
    });
  });

  it("falls back to shallow fish before a wounded bot becomes hungry", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const runId = "dry-land-aquatic-fallback-run";
    const teamId = "dry-land-aquatic-fallback-team";
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId,
      teamId,
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        explorationFrontiers: {
          "minecraft:overworld:find-food-animals": {
            origin: {
              x: 0,
              y: 64,
              z: 0,
              dimension: "minecraft:overworld",
            },
            nextIndex: 13,
            lastPosition: {
              x: 0,
              y: 64,
              z: 0,
              dimension: "minecraft:overworld",
            },
          },
        },
      },
    }, undefined));
    driver.currentObservation = observation({
      health: 8,
      food: 16,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 51,
      entityType: "minecraft:salmon",
      position: {
        x: 10,
        y: 62,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityResults = [salmon];
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      return task.type === "attack-entity" ? Effect.never : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId,
        team: { teamId },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "attack-entity")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: salmon.networkId }),
    }));
    expect(driver.paths).toHaveLength(0);
  });

  it("buffers shallow fish after a healthy dry land search is exhausted", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const runId = "healthy-aquatic-buffer-run";
    const teamId = "healthy-aquatic-buffer-team";
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId,
      teamId,
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        explorationFrontiers: {
          "minecraft:overworld:find-food-animals": {
            origin: {
              x: 0,
              y: 64,
              z: 0,
              dimension: "minecraft:overworld",
            },
            nextIndex: 13,
            totalAdvances: 12,
          },
        },
      },
    }, undefined));
    driver.currentObservation = observation({
      health: 20,
      food: 18,
      counts: {
        "minecraft:oak_log": 8,
        "minecraft:wooden_sword": 1,
      },
    });
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 53,
      entityType: "minecraft:salmon",
      position: {
        x: 3,
        y: 63,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityResults = [salmon];
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      return task.type === "attack-entity" ? Effect.never : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId,
        team: { teamId },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "attack-entity")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: salmon.networkId }),
    }));
  });

  it("hunts passive food barehanded when injured", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 10,
      food: 12,
    });
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 50,
      entityType: "minecraft:cow",
      position: {
        x: 3,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityResults = [cow];
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      return task.type === "attack-entity" ? Effect.never : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "attack-entity")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: cow.networkId }),
    }));
    expect(driver.tasks.some((task) => task.type === "collect-blocks"))
      .toBe(false);
    const attackIndex = driver.tasks.findIndex(
      (task) => task.type === "attack-entity",
    );
    expect(driver.taskPolicies[attackIndex]).toMatchObject({
      maxFallDistance: 2,
    });
  });

  it("keeps searching on land after repeated dry food searches", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "escalated-aquatic-food-run",
      teamId: "escalated-aquatic-food-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      planner: {
        ...initial.planner,
        completedActions: Array.from(
          { length: 4 },
          () => "satisfy:food-supply",
        ),
      },
    }, undefined));
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 44,
      entityType: "minecraft:salmon",
      position: {
        x: 40,
        y: 63,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      food: 12,
      health: 20,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [salmon];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        runId: "escalated-aquatic-food-run",
        team: { teamId: "escalated-aquatic-food-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      });
      while (driver.xzPaths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
    expect(driver.paths).toHaveLength(0);
    expect(driver.xzPaths[0]?.policy).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: true,
      sprint: false,
    });
  });

  it("keeps a critically wounded bot on dry land when fish are nearby", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      food: 6,
      health: 1,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 45,
      entityType: "minecraft:salmon",
      position: {
        x: 3,
        y: 61,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (driver.xzPaths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
    expect(driver.xzPaths[0]?.policy).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: true,
    });
  });

  it("keeps an urgently hungry injured bot on land above critical hunger", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      food: 8,
      health: 8,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 46,
      entityType: "minecraft:salmon",
      position: {
        x: 3,
        y: 62,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityResults = [salmon];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (driver.xzPaths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
    expect(driver.xzPaths[0]?.policy).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: true,
      sprint: false,
    });
  });

  it("hunts shallow fish when a wounded bot needs health regeneration", async () => {
    const driver = new FakeBeatGameDriver();
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 46,
      entityType: "minecraft:salmon",
      position: {
        x: 3,
        y: 62,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      food: 17,
      health: 12,
    });
    driver.entityResults = [salmon];
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      return task.type === "attack-entity" ? Effect.never : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "attack-entity")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.xzPaths).toHaveLength(0);
    const attackIndex = driver.tasks.findIndex(
      (task) => task.type === "attack-entity",
    );
    expect(driver.tasks[attackIndex]).toEqual(expect.objectContaining({
      target: expect.objectContaining({
        connectionEpoch: salmon.connectionEpoch,
        networkId: salmon.networkId,
      }),
    }));
    expect(driver.taskPolicies[attackIndex]).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: false,
      sprint: true,
    });
  });

  it("hunts shallow fish after every dry recovery route fails", async () => {
    const driver = new FakeBeatGameDriver();
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 46,
      entityType: "minecraft:salmon",
      position: {
        x: 3,
        y: 62,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      food: 11,
      health: 6,
    });
    driver.entityResults = [salmon];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.fail(new BeatGameDriverError({
        operation: "pathfindXZ",
        code: "unreachable",
        retryable: true,
        message: "No dry route leaves the isolated bridge",
      }))));
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      return task.type === "attack-entity" ? Effect.never : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "attack-entity")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.xzPaths).toHaveLength(1);
    expect(driver.xzPaths[0]?.policy).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: true,
      sprint: false,
    });
    expect(driver.surfaceQueries.length).toBeGreaterThan(0);
    const attackIndex = driver.tasks.findIndex(
      (task) => task.type === "attack-entity",
    );
    expect(driver.tasks[attackIndex]).toEqual(expect.objectContaining({
      target: expect.objectContaining({
        connectionEpoch: salmon.connectionEpoch,
        networkId: salmon.networkId,
      }),
    }));
    expect(driver.taskPolicies[attackIndex]).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: false,
      sprint: true,
    });
  });

  it("enters water to pursue nearby food when hunger is critical", async () => {
    const driver = new FakeBeatGameDriver();
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 46,
      entityType: "minecraft:salmon",
      position: {
        x: 28,
        y: 61,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      food: 6,
      health: 8,
      counts: {
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [salmon];
    driver.blockQueryResolver = (query) => {
      if (query.selector.blockIds?.includes("minecraft:water") !== true) {
        return [];
      }
      const water = blockObservation({
        x: 1,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      }, {
        blockId: "minecraft:water",
        diggable: false,
        replaceable: true,
      });
      return query.radius > 1 || Math.floor(query.center.x) === 1
        ? [water]
        : [];
    };
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.fail(new BeatGameDriverError({
        operation: "pathfindXZ",
        code: "unreachable",
        retryable: true,
        message: "No dry route leaves the island",
      }))));
    let directPathAttempts = 0;
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        directPathAttempts += 1;
      }).pipe(
        Effect.flatMap(() =>
          directPathAttempts === 1
            ? Effect.fail(new BeatGameDriverError({
              operation: "pathfind",
              code: "unreachable",
              retryable: true,
              message:
                "The pathfinder cannot step from the bridge into water",
            }))
            : Effect.sync(() => {
              driver.currentObservation = observation({
                position,
                food: 6,
                health: 8,
                counts: {
                  "minecraft:iron_ingot": 7,
                  "minecraft:oak_log": 8,
                  "minecraft:shield": 1,
                  "minecraft:stone_pickaxe": 1,
                  "minecraft:stone_sword": 1,
                },
              });
            })
        ),
      );
    driver.actionObserver = (action) => {
      if (
        action.type !== "set-movement"
        || action.forward !== true
        || action.jump !== true
      ) {
        return;
      }
      driver.currentObservation = observation({
        position: {
          x: 1.5,
          y: 64,
          z: 0.5,
          dimension: "minecraft:overworld",
        },
        food: 6,
        health: 8,
        counts: driver.currentObservation.inventory.counts,
      });
    };
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          driver.entityResults = [];
        }
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "attack-entity")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.xzPaths).toHaveLength(0);
    expect(driver.paths[0]).toMatchObject({
      position: salmon.position,
      radius: 4,
      policy: {
        allowMining: false,
        allowPlacing: false,
        avoidFluids: false,
        sprint: true,
      },
    });
    expect(driver.actions).toContainEqual({
      type: "set-movement",
      forward: true,
      jump: true,
      sprint: false,
    });
    expect(driver.actions).toContainEqual({ type: "reset-movement" });
    expect(driver.paths.length).toBeGreaterThan(1);
    const attackIndex = driver.tasks.findIndex(
      (task) => task.type === "attack-entity",
    );
    expect(driver.tasks[attackIndex]).toEqual(expect.objectContaining({
      target: expect.objectContaining({
        connectionEpoch: salmon.connectionEpoch,
        networkId: salmon.networkId,
      }),
    }));
    expect(driver.taskPolicies[attackIndex]).toMatchObject({
      allowMining: false,
      allowPlacing: false,
      avoidFluids: false,
      sprint: true,
    });
  });

  it("recovers an urgent food drop from a nearby deep staircase", async () => {
    const driver = new FakeBeatGameDriver();
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 47,
      entityType: "minecraft:item",
      itemId: "minecraft:salmon",
      position: {
        x: 3,
        y: 55,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      food: 6,
      health: 8,
    });
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:item") === true
        ? [salmon]
        : [];
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
        ? [blockObservation({
          x: 3,
          y: 55,
          z: 0,
          dimension: "minecraft:overworld",
        }, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
        })]
        : [];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (driver.xzPaths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.xzPaths[0]).toMatchObject({
      x: Math.floor(salmon.position.x) + 0.5,
      z: Math.floor(salmon.position.z) + 0.5,
      dimension: salmon.position.dimension,
      policy: {
        allowPlacing: false,
        avoidFluids: false,
      },
    });
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  });

  it("retrieves log drops from shallow water", async () => {
    const driver = new FakeBeatGameDriver();
    let collectionFinished = false;
    const logDrop = {
      connectionEpoch: "epoch-1",
      networkId: 48,
      entityType: "minecraft:item",
      itemId: "minecraft:oak_log",
      position: {
        x: 8,
        y: 63,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation();
    driver.entityQueryResolver = (query) =>
      collectionFinished
        && query.selector.entityTypes?.includes("minecraft:item") === true
        ? [logDrop]
        : [];
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:water") === true
          && Math.floor(query.center.x) === 8
          && Math.floor(query.center.y) === 63
          && Math.floor(query.center.z) === 0
        ? [blockObservation({
          x: 8,
          y: 63,
          z: 0,
          dimension: "minecraft:overworld",
        }, {
          blockId: "minecraft:water",
          diggable: false,
          replaceable: true,
        })]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "collect-blocks") {
          collectionFinished = true;
        }
      });
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (driver.xzPaths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.xzPaths[0]).toMatchObject({
      x: Math.floor(logDrop.position.x) + 0.5,
      z: Math.floor(logDrop.position.z) + 0.5,
      dimension: logDrop.position.dimension,
      policy: {
        allowPlacing: false,
        avoidFluids: false,
      },
    });
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "collect-blocks",
      avoidSubmergedTargets: true,
    }));
  });

  it("backs off food searches that make no observable progress", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      food: 12,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.fail(new BeatGameDriverError({
        operation: "pathfindXZ",
        code: "unreachable",
        retryable: true,
        message: "No dry food route is reachable",
      }))));

    const [firstFailure, repeatedImmediately] = await Effect.runPromise(
      Effect.scoped(Effect.gen(function* () {
        const run = yield* beatGameWithDriver(driver, {
          strategy: { observationPollMs: 1 },
        });
        const firstFailure = yield* run.events.pipe(
          Stream.filter((event) =>
            event.type === "action-failed"
            && event.action === "satisfy:food-supply"
          ),
          Stream.runHead,
          Effect.timeout("5 seconds"),
        );
        const repeatedImmediately = yield* Effect.race(
          run.events.pipe(
            Stream.filter((event) =>
              event.type === "action-started"
              && event.action === "satisfy:food-supply"
            ),
            Stream.drop(1),
            Stream.runHead,
            Effect.as(true),
          ),
          Effect.sleep(100).pipe(Effect.as(false)),
        );
        yield* run.stop;
        return [firstFailure, repeatedImmediately] as const;
      })),
    );

    expect(Option.isSome(firstFailure)).toBe(true);
    expect(repeatedImmediately).toBe(false);
    expect(driver.xzPaths).toHaveLength(1);
  }, 10_000);

  it("does not hunt hostile emergency food while critically hurt", async () => {
    const driver = new FakeBeatGameDriver();
    const zombie = {
      connectionEpoch: "epoch-1",
      networkId: 51,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 5,
      food: 6,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:stone_pickaxe": 1,
      },
    });
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:zombie") === true
        ? [zombie]
        : [];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.sleep(100);
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    const foodQueries = driver.entityQueries.filter((query) =>
      query.selector.entityTypes?.includes("minecraft:cow") === true
    );
    expect(foodQueries.length).toBeGreaterThan(0);
    expect(foodQueries.every((query) =>
      query.selector.entityTypes?.includes("minecraft:zombie") === false
    )).toBe(true);
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
    expect(driver.xzPaths.length).toBeGreaterThan(0);
  });

  it("allows a healthy starving bot to hunt emergency food", async () => {
    const driver = new FakeBeatGameDriver();
    const zombie = {
      connectionEpoch: "epoch-1",
      networkId: 52,
      entityType: "minecraft:zombie",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 20,
      food: 6,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:stone_pickaxe": 1,
      },
    });
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:zombie") === true
        ? [zombie]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "attack-entity")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        networkId: zombie.networkId,
        entityType: zombie.entityType,
      }),
    }));
  });

  it("mines a bounded local escape after a dry food route fails", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      food: 12,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:iron_ingot": 7,
        "minecraft:oak_log": 8,
        "minecraft:shield": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
      },
    });
    driver.surfaceColumns = [
      { x: 3, z: 0 },
      { x: 3, z: 1 },
      { x: 4, z: 0 },
      { x: 13, z: 0 },
      { x: 13, z: 1 },
      { x: 14, z: 0 },
    ].map(({ x, z }) => ({
      x,
      z,
      loaded: true,
      surfaceY: 64,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }));
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
        const current = driver.currentObservation;
        driver.currentObservation = {
          ...current,
          player: {
            ...current.player,
            position: {
              ...current.player.position,
              x: 10,
            },
          },
        };
      }).pipe(Effect.zipRight(Effect.fail(new BeatGameDriverError({
        operation: "pathfindXZ",
        code: "unreachable",
        retryable: true,
        message: "The bot is boxed in",
      }))));
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (driver.paths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.xzPaths[0]?.policy.allowMining).toBe(false);
    expect(driver.paths[0]).toMatchObject({
      radius: 1.5,
      policy: {
        allowMining: true,
        allowPlacing: true,
        avoidFluids: true,
        sprint: false,
        maxSearchTimeMs: 5_000,
      },
    });
    const localTarget = driver.paths[0]?.position;
    if (localTarget === undefined) {
      throw new Error("The local recovery route was not attempted");
    }
    expect(Math.hypot(
      localTarget.x - driver.currentObservation.player.position.x,
      localTarget.z - driver.currentObservation.player.position.z,
    )).toBeGreaterThanOrEqual(3);
    expect(localTarget.x).toBeGreaterThanOrEqual(13);
  }, 10_000);

  it("keeps exploring when a hunting target only flickers into view", async () => {
    const driver = new FakeBeatGameDriver();
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:cow",
      position: {
        x: 12,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    let foodQueries = 0;
    driver.currentObservation = observation({
      health: 17,
      food: 15,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:oak_log": 8,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityQueryResolver = (query) => {
      if (query.selector.entityTypes?.includes("minecraft:cow") !== true) {
        return [];
      }
      foodQueries += 1;
      return foodQueries === 2 ? [cow] : [];
    };
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (foodQueries < 4) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.xzPaths).toHaveLength(1);
  });

  it("interrupts exploration when a distant hunting target stays visible", async () => {
    const driver = new FakeBeatGameDriver();
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 44,
      entityType: "minecraft:cow",
      position: {
        x: 0,
        y: 64,
        z: 40,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    let foodQueries = 0;
    let interruptedPaths = 0;
    driver.currentObservation = observation({
      health: 17,
      food: 15,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:oak_log": 8,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityQueryResolver = (query) => {
      if (query.selector.entityTypes?.includes("minecraft:cow") !== true) {
        return [];
      }
      foodQueries += 1;
      return foodQueries === 2 || foodQueries === 3 ? [cow] : [];
    };
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(
        Effect.zipRight(Effect.never),
        Effect.onInterrupt(() =>
          Effect.sync(() => {
            interruptedPaths += 1;
          })
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length < 2) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(interruptedPaths).toBeGreaterThanOrEqual(1);
    expect(driver.xzPaths.slice(0, 2).map(({ x, z }) => ({ x, z }))).toEqual([
      { x: 16, z: 0 },
      { x: 0, z: 12 },
    ]);
  }, 10_000);

  it("rotates resource exploration after a threat interrupts a frontier", async () => {
    const driver = new FakeBeatGameDriver();
    const creeper = {
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:creeper",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
        if (driver.xzPaths.length === 1) {
          driver.entityResults = [creeper];
        }
      }).pipe(Effect.zipRight(Effect.never));
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
          driver.entityResults = [];
      });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length < 2) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.xzPaths.slice(0, 2).map(({ x, z }) => ({ x, z }))).toEqual([
      { x: 24, z: 0 },
      { x: 24, z: 24 },
    ]);
  });

  it("continues durable exploration progress after an SDK restart", async () => {
    const store = new InMemoryBeatGameCheckpointStore();
    const runId = "durable-exploration-run";
    const teamId = "durable-exploration-team";
    const firstDriver = new FakeBeatGameDriver();
    const firstPath = await runUntilExplorationStarts({
      driver: firstDriver,
      store,
      runId,
      teamId,
    });

    const stored = await Effect.runPromise(store.load(runId));
    expect(stored?.memory.explorationFrontiers).toMatchObject({
      "minecraft:overworld:find-logs": {
        nextIndex: 2,
        lastPosition: {
          x: 0,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        },
      },
    });

    const secondDriver = new FakeBeatGameDriver();
    const secondPath = await runUntilExplorationStarts({
      driver: secondDriver,
      store,
      runId,
      teamId,
    });

    expect(firstPath).toMatchObject({ x: 24, z: 0 });
    expect(secondPath).toMatchObject({
      x: 22.62741699796952,
      z: 22.62741699796952,
    });
  }, 10_000);

  it("does not reanchor durable exploration after a recent death", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const runId = "death-displaced-exploration-run";
    const teamId = "death-displaced-exploration-team";
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId,
      teamId,
    });
    const deathPosition = {
      x: 100,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    } as const;
    const observedAt = new Date().toISOString();
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        explorationFrontiers: {
          "minecraft:overworld:find-logs": {
            origin: driver.currentObservation.player.position,
            nextIndex: 2,
            lastPosition: deathPosition,
          },
        },
        latestDeath: {
          key: `death:${observedAt}`,
          value: deathPosition,
          observedAt,
          confidence: 1,
        },
      },
    }, undefined));
    const path = await runUntilExplorationStarts({
      driver,
      store,
      runId,
      teamId,
    });

    expect(path).toMatchObject({
      x: 22.62741699796952,
      z: 22.62741699796952,
    });
  }, 10_000);

  it("preserves durable exploration expansion after an unrelated displacement", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const runId = "displaced-exploration-run";
    const teamId = "displaced-exploration-team";
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId,
      teamId,
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        explorationFrontiers: {
          "minecraft:overworld:find-logs": {
            origin: driver.currentObservation.player.position,
            nextIndex: 2,
            totalAdvances: 7,
            lastPosition: {
              x: 100,
              y: 64,
              z: 0,
              dimension: "minecraft:overworld",
            },
          },
        },
      },
    }, undefined));
    const path = await runUntilExplorationStarts({
      driver,
      store,
      runId,
      teamId,
    });

    expect(path).toMatchObject({
      x: 22.62741699796952,
      z: -22.62741699796952,
    });
    const stored = await Effect.runPromise(store.load(runId));
    expect(
      stored?.memory.explorationFrontiers?.[
        "minecraft:overworld:find-logs"
      ]?.totalAdvances,
    ).toBe(8);
  }, 10_000);

  it("reanchors resource exploration without resetting it after a defensive escape", async () => {
    const driver = new FakeBeatGameDriver();
    const creeper = {
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:creeper",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 20,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
        if (driver.xzPaths.length === 1) {
          driver.entityResults = [creeper];
        }
      }).pipe(Effect.zipRight(Effect.never));
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "flee") {
          driver.entityResults = [];
          driver.currentObservation = observation({
            position: { x: 100, y: 64, z: 0 },
          });
        }
      });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length < 2) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.xzPaths.slice(0, 2).map(({ x, z }) => ({ x, z }))).toEqual([
      { x: 24, z: 0 },
      { x: 122.62741699796952, z: 22.62741699796952 },
    ]);
  });

  it("keeps rotating resource exploration after blocked frontiers", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:oak_log": 8,
        "minecraft:stone_sword": 1,
      },
    });
    driver.xzPathResolver = (x, z, dimension, radius, policy) => {
      const dryAttempts = driver.xzPaths.filter(
        ({ policy: attemptedPolicy }) =>
          attemptedPolicy.avoidFluids === true,
      ).length;
      const shouldFail = policy.avoidFluids !== true || dryAttempts < 6;
      return Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(
        Effect.zipRight(
          shouldFail
            ? Effect.fail(new BeatGameDriverError({
              operation: "pathfindXZ",
              code: "unreachable",
              retryable: true,
              message: "The frontier route made no progress",
            }))
            : Effect.never,
        ),
      );
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              driver.xzPaths.filter(({ policy }) =>
                policy.avoidFluids === true
              ).length < 7
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const dryPaths = driver.xzPaths.filter(({ policy }) =>
      policy.avoidFluids === true
    );
    expect(dryPaths.slice(0, 7).map(({ x, z }) => ({ x, z }))).toEqual([
      { x: 24, z: 0 },
      { x: 22.62741699796952, z: 22.62741699796952 },
      { x: 0, z: 24 },
      { x: -22.62741699796952, z: 22.62741699796952 },
      { x: -24, z: 0 },
      { x: -22.62741699796952, z: -22.62741699796952 },
      { x: 0, z: -24 },
    ]);
  });

  it("segments distant exploration frontiers into loadable pathfinding legs", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:oak_log": 8,
        "minecraft:stone_sword": 1,
      },
    });
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.sleep(1)));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* Effect.gen(function* () {
              while (driver.xzPaths.length < 40) {
                yield* Effect.sleep(1);
              }
            }).pipe(Effect.timeoutFail({
              duration: "5 seconds",
              onTimeout: () =>
                new Error("Distant exploration stopped making progress"),
            }));
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const distances = driver.xzPaths.slice(0, 40).map(({ x, z }) =>
      Math.hypot(x, z)
    );
    expect(Math.max(...distances)).toBeCloseTo(32);
    expect(distances.some((distance) => distance > 31.9)).toBe(true);
  });

  it("returns to the Overworld surface before exploring for animals", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = [{
      x: 12,
      z: -8,
      loaded: true,
      surfaceY: 86,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.currentObservation = observation({
      position: {
        x: 12,
        y: 63,
        z: -8,
        dimension: "minecraft:overworld",
      },
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:water_bucket": 1,
        "minecraft:flint_and_steel": 1,
        "minecraft:shield": 1,
      },
    });
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.paths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths[0]).toEqual({
      position: {
        x: 12.5,
        y: 87,
        z: -7.5,
        dimension: "minecraft:overworld",
      },
      radius: 1.5,
      policy: expect.objectContaining({
        allowMining: true,
        allowPlacing: true,
      }),
    });
    expect(driver.tasks.some((task) => task.type === "explore")).toBe(false);
  });

  it("climbs out of a shallow cave before exploring for animals", async () => {
    const driver = new FakeBeatGameDriver();
    driver.surfaceColumns = [
      {
        x: 0,
        z: 0,
        loaded: true,
        surfaceY: 57,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:forest",
        skyLight: 0,
        blockLight: 0,
      },
      ...[-1, 0, 1].flatMap((deltaX) =>
        [-1, 0, 1].map((deltaZ) => ({
          x: 12 + deltaX,
          z: deltaZ,
          loaded: true as const,
          surfaceY: 70,
          blockId: "minecraft:grass_block",
          biomeId: "minecraft:forest",
          skyLight: 0,
          blockLight: 0,
        }))
      ),
    ];
    driver.currentObservation = observation({
      position: {
        x: 0.5,
        y: 58,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:water_bucket": 1,
        "minecraft:flint_and_steel": 1,
        "minecraft:shield": 1,
      },
    });
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.paths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths[0]).toEqual({
      position: {
        x: 11.5,
        y: 71,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 1.5,
      policy: expect.objectContaining({
        allowMining: true,
        allowPlacing: true,
      }),
    });
    expect(driver.xzPaths).toHaveLength(0);
  });

  it("crafts a durable pickaxe before mining a long route to the surface", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ENTER_NETHER,
      {
        runId: "surface-escape-pickaxe-run",
        teamId: "surface-escape-pickaxe-team",
      },
    ), undefined));
    driver.surfaceColumns = [{
      x: 12,
      z: -8,
      loaded: true,
      surfaceY: 86,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.currentObservation = observation({
      position: {
        x: 12,
        y: 20,
        z: -8,
        dimension: "minecraft:overworld",
      },
      counts: {
        "minecraft:crafting_table": 1,
        "minecraft:cobblestone": 20,
        "minecraft:oak_log": 3,
        "minecraft:stick": 2,
        "minecraft:stone_sword": 1,
        "minecraft:cooked_beef": 8,
        "minecraft:iron_ingot": 9,
        "minecraft:water_bucket": 1,
        "minecraft:flint_and_steel": 1,
        "minecraft:shield": 1,
      },
    });
    driver.recipeResolver = (resultItemId) => [{
      recipeId: resultItemId,
      recipeType: "minecraft:crafting",
      resultItemId,
      resultCount: 1,
      ingredients: [],
    }];
    driver.craftabilityResolver = () => ({
      canCraft: true,
      maximumCraftCount: 1,
      requiredStation: "minecraft:crafting_table",
      missing: [],
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:crafting_table") === true
        ? [blockObservation({
          x: 13,
          y: 20,
          z: -8,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:crafting_table" })]
        : [];
    const resolveTask = driver.taskResolver;
    driver.taskResolver = (task, execution) =>
      resolveTask(task, execution).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            if (
              task.type === "craft"
              && task.recipeId === "minecraft:iron_pickaxe"
            ) {
              driver.currentObservation = observation({
                position: driver.currentObservation.player.position,
                counts: {
                  ...driver.currentObservation.inventory.counts,
                  "minecraft:iron_pickaxe": 1,
                },
                remainingDurability: {
                  "minecraft:iron_pickaxe": 250,
                },
              });
            }
          })
        ),
      );
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.zipRight(position.y === 87 ? Effect.never : Effect.void),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "surface-escape-pickaxe-run",
        team: { teamId: "surface-escape-pickaxe-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* Effect.gen(function* () {
              while (!driver.paths.some(({ position }) => position.y === 87)) {
                yield* Effect.sleep(1);
              }
            }).pipe(Effect.timeoutFail({
              duration: "2 seconds",
              onTimeout: () => new Error(
                `Surface path did not start; tasks: ${JSON.stringify(driver.tasks)}`,
              ),
            }));
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "craft",
      recipeId: "minecraft:iron_pickaxe",
    }));
    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: {
        x: 12.5,
        y: 87,
        z: -7.5,
        dimension: "minecraft:overworld",
      },
      radius: 1.5,
      policy: expect.objectContaining({ allowMining: true }),
    }));
  });

  it("does not mistake an adjacent hillside for overhead terrain", async () => {
    const driver = new FakeBeatGameDriver();
    const preparedItems = {
      "minecraft:cobblestone": 20,
      "minecraft:oak_log": 8,
      "minecraft:stone_sword": 1,
    };
    driver.currentObservation = observation({
      counts: preparedItems,
      position: {
        x: 0.5,
        y: 64,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
    });
    driver.surfaceColumns = [
      {
        x: 0,
        z: 0,
        loaded: true,
        surfaceY: 63,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: 2,
        z: 0,
        loaded: true,
        surfaceY: 80,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
    ];
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 1,
      entityType: "minecraft:cow",
      position: {
        x: 100,
        y: 64,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: {
          observationPollMs: 1,
          entitySearchRadius: 320,
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toHaveLength(0);
    expect(driver.xzPaths[0]).toEqual(expect.objectContaining({
      x: 48.5,
      z: 0.5,
      radius: 2,
    }));
  });

  it("climbs to the sampled surface before exploring for missing blocks", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 247.5,
        y: 42,
        z: -175.5,
        dimension: "minecraft:overworld",
      },
    });
    driver.surfaceColumns = [{
      x: 247,
      z: -175,
      loaded: true,
      surfaceY: 89,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (position.y === 90) {
          driver.currentObservation = observation({
            position,
            counts: driver.currentObservation.inventory.counts,
          });
        }
      });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "collect-blocks")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.some((task) => task.type === "collect-blocks")).toBe(
      true,
    );
    expect(driver.paths[0]).toEqual({
      position: {
        x: 247.5,
        y: 90,
        z: -174.5,
        dimension: "minecraft:overworld",
      },
      radius: 1.5,
      policy: expect.objectContaining({
        allowMining: true,
        allowPlacing: true,
      }),
    });
    expect(driver.tasks.some((task) => task.type === "explore")).toBe(false);
  });

  it("climbs toward an ocean surface when no dry column is nearby", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 400.5,
        y: -53,
        z: 124.5,
        dimension: "minecraft:overworld",
      },
    });
    driver.surfaceColumns = [{
      x: 400,
      z: 124,
      loaded: true,
      surfaceY: 62,
      blockId: "minecraft:water",
      biomeId: "minecraft:cold_ocean",
      skyLight: 14,
      blockLight: 0,
    }];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.paths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths[0]).toEqual({
      position: {
        x: 400.5,
        y: 63,
        z: 124.5,
        dimension: "minecraft:overworld",
      },
      radius: 1.5,
      policy: expect.objectContaining({
        allowMining: true,
        allowPlacing: true,
        avoidFluids: false,
      }),
    });
    expect(driver.xzPaths).toHaveLength(0);
  });

  it("recovers from a shallow underground pocket above sea level before exploring", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 58.5,
        y: 66,
        z: -8.5,
        dimension: "minecraft:overworld",
      },
    });
    driver.surfaceColumns = [{
      x: 58,
      z: -8,
      loaded: true,
      surfaceY: 72,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.paths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.xzPaths).toHaveLength(0);
    expect(driver.paths[0]).toEqual({
      position: {
        x: 58.5,
        y: 73,
        z: -7.5,
        dimension: "minecraft:overworld",
      },
      radius: 1.5,
      policy: expect.objectContaining({
        allowMining: true,
        allowPlacing: true,
      }),
    });
  });

  it("climbs out of a low ravine before exploring for surface blocks", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 12.5,
        y: 52,
        z: 8.5,
        dimension: "minecraft:overworld",
      },
    });
    driver.surfaceColumns = [
      {
        x: 12,
        z: 8,
        loaded: true,
        surfaceY: 51,
        blockId: "minecraft:stone",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: 18,
        z: 8,
        loaded: true,
        surfaceY: 70,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: 18,
        z: 9,
        loaded: true,
        surfaceY: 70,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: 19,
        z: 8,
        loaded: true,
        surfaceY: 69,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
    ];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.paths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths[0]).toEqual({
      position: {
        x: 18.5,
        y: 71,
        z: 8.5,
        dimension: "minecraft:overworld",
      },
      radius: 1.5,
      policy: expect.objectContaining({
        allowMining: true,
        allowPlacing: true,
      }),
    });
    expect(driver.xzPaths).toHaveLength(0);
  });

  it("explores horizontally instead of climbing ordinary hills", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 65.5,
        y: 67,
        z: 206.5,
        dimension: "minecraft:overworld",
      },
    });
    driver.surfaceColumns = [
      {
        x: 65,
        z: 206,
        loaded: true,
        surfaceY: 66,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: 77,
        z: 195,
        loaded: true,
        surfaceY: 73,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: 77,
        z: 196,
        loaded: true,
        surfaceY: 72,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: 76,
        z: 195,
        loaded: true,
        surfaceY: 73,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
    ];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toHaveLength(0);
    expect(driver.xzPaths).toHaveLength(1);
  });

  it("ignores isolated high columns when escaping low ground", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 12.5,
        y: 52,
        z: 8.5,
        dimension: "minecraft:overworld",
      },
    });
    driver.surfaceColumns = [
      {
        x: 12,
        z: 8,
        loaded: true,
        surfaceY: 51,
        blockId: "minecraft:stone",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: 18,
        z: 8,
        loaded: true,
        surfaceY: 70,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
    ];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toHaveLength(0);
    expect(driver.xzPaths).toHaveLength(1);
  });

  it("tries another dry surface when the nearest exit is unreachable", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 0.5,
        y: 30,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
    });
    driver.surfaceColumns = [
      {
        x: 0,
        z: 0,
        loaded: true,
        surfaceY: 64,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
      {
        x: -3,
        z: 0,
        loaded: true,
        surfaceY: 62,
        blockId: "minecraft:grass_block",
        biomeId: "minecraft:plains",
        skyLight: 15,
        blockLight: 0,
      },
    ];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.zipRight(
          position.x === 0.5
            ? Effect.fail(new BeatGameDriverError({
              operation: "pathfind",
              code: "unreachable",
              retryable: true,
              message: "The nearest exit is blocked",
            }))
            : Effect.never,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.paths.length < 2) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths.slice(0, 2)).toEqual([
      expect.objectContaining({
        position: expect.objectContaining({ x: 0.5, y: 65, z: 0.5 }),
      }),
      expect.objectContaining({
        position: expect.objectContaining({ x: -2.5, y: 63, z: 0.5 }),
      }),
    ]);
  });

  it("continues exploring from natural low-elevation terrain", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 107.5,
        y: 39,
        z: 39.5,
        dimension: "minecraft:overworld",
      },
    });
    driver.surfaceColumns = [{
      x: 107,
      z: 39,
      loaded: true,
      surfaceY: 38,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toHaveLength(0);
    expect(driver.xzPaths).toHaveLength(1);
    expect(driver.xzPaths[0]).toEqual(expect.objectContaining({
      x: 131.5,
      z: 39.5,
      radius: 2,
    }));
  });

  it("moves on after an animal remains unreachable", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
      },
    });
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:cow",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.entityResults = [cow];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity"
            ? Effect.fail(new BeatGameDriverError({
              operation: "task.attack-entity",
              code: "unreachable",
              retryable: true,
              message: "Unable to reach the target entity",
            }))
            : Effect.void,
        ),
      );
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));
    let rememberedTargets: readonly string[] = [];

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: {
          observationPollMs: 1,
          entitySearchRadius: 320,
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              driver.xzPaths.length === 0
            ) {
              yield* Effect.sleep(1);
            }
            rememberedTargets = (yield* run.snapshot).checkpoint.memory
              .unreachable.map(({ key }) => key);
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const attackIndex = driver.tasks.findIndex(
      (task) => task.type === "attack-entity",
    );
    expect(driver.taskPolicies[attackIndex]).toMatchObject({
      allowPlacing: true,
    });
    expect(driver.xzPaths[0]?.policy).toMatchObject({
      allowMining: false,
      allowPlacing: true,
    });
    expect(driver.xzPaths[0]).toMatchObject({
      x: 64,
      z: 0,
    });
    expect(rememberedTargets).toContain("target:epoch-1:42");
  });

  it("retries an unreachable animal after it moves", async () => {
    const driver = new FakeBeatGameDriver();
    const preparedItems = {
      "minecraft:oak_log": 8,
      "minecraft:cobblestone": 20,
      "minecraft:stone_sword": 1,
    };
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:cow",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    const movedCow = {
      ...cow,
      position: { ...cow.position, x: 2 },
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({ counts: preparedItems });
    driver.entityResults = [cow];
    let attackAttempts = 0;
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          attackAttempts += 1;
          driver.entityResults = [movedCow];
        }
        return attackAttempts;
      }).pipe(
        Effect.flatMap((attempt) =>
          task.type !== "attack-entity"
            ? Effect.void
            : attempt === 1
            ? Effect.fail(new BeatGameDriverError({
              operation: "task.attack-entity",
              code: "unreachable",
              retryable: true,
              message: "The animal moved away from its original route",
            }))
            : Effect.never
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: {
          observationPollMs: 1,
          entitySearchRadius: 320,
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              driver.tasks.filter((task) => task.type === "attack-entity")
                .length < 2
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.filter((task) => task.type === "attack-entity"))
      .toEqual([
        expect.objectContaining({
          target: expect.objectContaining({ position: cow.position }),
        }),
        expect.objectContaining({
          target: expect.objectContaining({ position: movedCow.position }),
        }),
      ]);
  });

  it("picks up a nearby required resource before gathering more", async () => {
    const driver = new FakeBeatGameDriver();
    const preparedCounts = {
      "minecraft:oak_log": 8,
      "minecraft:cobblestone": 20,
      "minecraft:stone_sword": 1,
    };
    const droppedIron = {
      connectionEpoch: "epoch-1",
      networkId: 45,
      entityType: "minecraft:item",
      itemId: "minecraft:iron_ingot",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 5,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({ counts: preparedCounts });
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:item") === true
        && (driver.currentObservation.inventory.counts[
            "minecraft:iron_ingot"
          ] ?? 0) === 0
        ? [droppedIron]
        : [];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (
          position.x === droppedIron.position.x
          && position.z === droppedIron.position.z
        ) {
          driver.currentObservation = observation({
            position: droppedIron.position,
            counts: {
              ...preparedCounts,
              "minecraft:iron_ingot": 1,
            },
          });
        }
      });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            yield* run.events.pipe(
              Stream.filter((event) =>
                event.type === "action-succeeded"
                && event.action === "satisfy:iron"
              ),
              Stream.runHead,
            );
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: droppedIron.position,
      policy: expect.objectContaining({
        allowPlacing: false,
        avoidFluids: true,
      }),
    }));
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "collect-blocks",
    }));
  });

  it("forages mature berries before hunting while wounded", async () => {
    const driver = new FakeBeatGameDriver();
    const preparedCounts = {
      "minecraft:oak_log": 8,
      "minecraft:cobblestone": 20,
      "minecraft:stone_sword": 1,
    };
    const berryBush = blockObservation({
      x: 3,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, {
      blockId: "minecraft:sweet_berry_bush",
      properties: { age: "3" },
      diggable: true,
      interactive: true,
    });
    driver.currentObservation = observation({
      health: 8,
      food: 6,
      counts: preparedCounts,
    });
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:sweet_berry_bush") === true
        ? [berryBush]
        : [];
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        if (
          action.type === "interact-block"
          && action.position.x === berryBush.position.x
          && action.position.y === berryBush.position.y
          && action.position.z === berryBush.position.z
        ) {
          driver.currentObservation = observation({
            health: 8,
            food: 6,
            counts: {
              ...preparedCounts,
              "minecraft:sweet_berries": 2,
            },
          });
        }
        return {};
      });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.actions.some((action) =>
              action.type === "interact-block"
              && action.position.x === berryBush.position.x
              && action.position.y === berryBush.position.y
              && action.position.z === berryBush.position.z
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: berryBush.position,
      radius: 3,
      policy: expect.objectContaining({
        allowPlacing: false,
        avoidFluids: true,
      }),
    }));
    expect(driver.actions).toContainEqual({
      type: "interact-block",
      position: berryBush.position,
      face: "up",
    });
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "attack-entity",
    }));
  });

  it("picks up nearby emergency food before hunting while wounded", async () => {
    const driver = new FakeBeatGameDriver();
    const preparedCounts = {
      "minecraft:oak_log": 8,
      "minecraft:cobblestone": 20,
      "minecraft:stone_sword": 1,
    };
    const droppedRottenFlesh = {
      connectionEpoch: "epoch-1",
      networkId: 46,
      entityType: "minecraft:item",
      itemId: "minecraft:rotten_flesh",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      health: 3,
      food: 13,
      counts: preparedCounts,
    });
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:item") === true
        && (driver.currentObservation.inventory.counts[
            "minecraft:rotten_flesh"
          ] ?? 0) === 0
        ? [droppedRottenFlesh]
        : [];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (
          position.x === droppedRottenFlesh.position.x
          && position.z === droppedRottenFlesh.position.z
        ) {
          driver.currentObservation = observation({
            health: 3,
            food: 13,
            position: droppedRottenFlesh.position,
            counts: {
              ...preparedCounts,
              "minecraft:rotten_flesh": 1,
            },
          });
        }
      });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      return task.type === "auto-eat" ? Effect.never : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.tasks.some((task) => task.type === "auto-eat")) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: droppedRottenFlesh.position,
      policy: expect.objectContaining({
        allowPlacing: false,
        avoidFluids: true,
      }),
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "auto-eat",
      foodItemIds: ["minecraft:rotten_flesh"],
    }));
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  });

  it("waits for a delayed block pickup before exploring", async () => {
    const driver = new FakeBeatGameDriver();
    const droppedLog = {
      connectionEpoch: "epoch-1",
      networkId: 10,
      entityType: "minecraft:item",
      itemId: "minecraft:oak_log",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    let collectingDrop = false;
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "collect-blocks") {
          driver.entityResults = [droppedLog];
        }
        return {};
      });
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.gen(function* () {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
        if (
          x === droppedLog.position.x
          && z === droppedLog.position.z
        ) {
          collectingDrop = true;
          yield* Effect.forkDaemon(
            Effect.sleep(75).pipe(
              Effect.tap(() =>
                Effect.sync(() => {
                  driver.currentObservation = observation({
                    counts: { "minecraft:oak_log": 1 },
                  });
                })
              ),
            ),
          );
        }
      });

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: {
          observationPollMs: 1,
          targetLogCount: 1,
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!collectingDrop) {
              yield* Effect.sleep(1);
            }
            yield* Effect.sleep(200);
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.tasks.some((task) => task.type === "explore")).toBe(false);
  });

  it("honors a compact triangulation baseline", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: { "minecraft:ender_eye": 12 },
      position: {
        x: 100,
        y: 70,
        z: 200,
        dimension: "minecraft:overworld",
      },
    });
    const store = new InMemoryBeatGameCheckpointStore();
    const initial = checkpoint(BeatGamePhase.LOCATE_STRONGHOLD, {
      runId: "compact-baseline-run",
      teamId: "compact-baseline-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        eyeSamples: [{
          origin: driver.currentObservation.player.position,
          direction: { x: 1, z: 0 },
          observedAt: "2026-01-01T00:00:01.000Z",
          confidence: 1,
        }],
      },
    }, undefined));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "compact-baseline-run",
        team: { teamId: "compact-baseline-team" },
        checkpointStore: store,
        strategy: {
          explorationRadius: 16,
          observationPollMs: 1,
        },
        hooks: {
          ...postDragonHooks(driver),
          throwEye: () =>
            Effect.succeed({
              origin: {
                x: 100,
                y: 70,
                z: 232,
                dimension: "minecraft:overworld",
              },
              direction: {
                x: Math.SQRT1_2,
                z: -Math.SQRT1_2,
              },
              observedAt: "2026-01-01T00:00:02.000Z",
              confidence: 1,
            }),
          searchStronghold: () => Effect.succeed(true),
          activateEndPortal: () =>
            Effect.sync(() => {
              driver.currentObservation = observation({
                dimension: "minecraft:the_end",
                counts: driver.currentObservation.inventory.counts,
              });
            }),
        },
      }).pipe(Effect.flatMap(({ awaitCompletion }) => awaitCompletion)),
    ));

    expect(driver.paths[0]).toEqual(expect.objectContaining({
      position: {
        x: 100,
        y: 70,
        z: 232,
        dimension: "minecraft:overworld",
      },
      radius: 4,
    }));
  });

  it("resumes a stronghold staircase from an intermediate step", async () => {
    const driver = new FakeBeatGameDriver();
    const currentPosition = {
      x: 15,
      y: 10,
      z: 17,
      dimension: "minecraft:overworld",
    };
    driver.currentObservation = observation({
      counts: { "minecraft:ender_eye": 12 },
      position: currentPosition,
    });
    installStaircaseMovementSimulation(driver, currentPosition);
    const portalFrames = [
      { x: 10, z: 20 },
      { x: 14, z: 20 },
      { x: 10, z: 24 },
      { x: 14, z: 24 },
    ].map(({ x, z }) => ({
      blockId: "minecraft:end_portal_frame",
      position: {
        x,
        y: 3,
        z,
        dimension: "minecraft:overworld",
      },
      properties: { eye: "false" },
      diggable: false,
      replaceable: false,
      interactive: true,
      observedAt: "2026-01-01T00:00:01.000Z",
    }));
    driver.blockResults = portalFrames;
    driver.blockQueryResolver = ({ center, selector }) =>
      selector.blockIds?.includes("minecraft:end_portal_frame") === true
        ? portalFrames
        : [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        })];
    const store = new InMemoryBeatGameCheckpointStore();
    const initial = checkpoint(BeatGamePhase.LOCATE_STRONGHOLD, {
      runId: "staircase-resume-run",
      teamId: "staircase-resume-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        strongholdEstimate: {
          x: 12,
          y: 100,
          z: 0,
          dimension: "minecraft:overworld",
        },
      },
    }, undefined));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "staircase-resume-run",
        team: { teamId: "staircase-resume-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
        hooks: {
          ...postDragonHooks(driver),
          activateEndPortal: () =>
            Effect.sync(() => {
              driver.currentObservation = observation({
                dimension: "minecraft:the_end",
                counts: driver.currentObservation.inventory.counts,
              });
            }),
        },
      }).pipe(Effect.flatMap(({ awaitCompletion }) => awaitCompletion)),
    ));

    expect(driver.paths[0]?.position).toEqual(currentPosition);
    expect(driver.paths[0]?.radius).toBe(0.5);
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: {
        x: 15,
        y: 10,
        z: 15,
        dimension: "minecraft:overworld",
      },
    }));
  });

  it("approaches portal frames found after the underground survey", async () => {
    const driver = new FakeBeatGameDriver();
    const currentPosition = {
      x: 2,
      y: 10,
      z: -3,
      dimension: "minecraft:overworld",
    };
    driver.currentObservation = observation({
      counts: {
        "minecraft:cobblestone": 16,
        "minecraft:diamond_pickaxe": 1,
        "minecraft:ender_eye": 12,
      },
      position: currentPosition,
    });
    installStaircaseMovementSimulation(driver, currentPosition);
    const portalFrames = [
      { x: 0, z: 0 },
      { x: 4, z: 0 },
      { x: 0, z: 4 },
      { x: 4, z: 4 },
    ].map(({ x, z }) =>
      blockObservation(
        {
          x,
          y: 8,
          z,
          dimension: "minecraft:overworld",
        },
        {
          blockId: "minecraft:end_portal_frame",
          properties: { eye: "false" },
          diggable: false,
          interactive: true,
        },
      )
    );
    let portalFrameQueries = 0;
    driver.blockQueryResolver = ({ center, selector }) => {
      if (
        selector.blockIds?.includes("minecraft:end_portal_frame") === true
      ) {
        portalFrameQueries += 1;
        return portalFrameQueries >= 3 ? portalFrames : [];
      }
      return [blockObservation({
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      })];
    };
    const store = new InMemoryBeatGameCheckpointStore();
    const initial = checkpoint(BeatGamePhase.LOCATE_STRONGHOLD, {
      runId: "underground-survey-run",
      teamId: "underground-survey-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        strongholdEstimate: {
          x: 2,
          y: 34,
          z: -10,
          dimension: "minecraft:overworld",
        },
      },
    }, undefined));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "underground-survey-run",
        team: { teamId: "underground-survey-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
        hooks: {
          ...postDragonHooks(driver),
          activateEndPortal: () =>
            Effect.sync(() => {
              driver.currentObservation = observation({
                dimension: "minecraft:the_end",
                counts: driver.currentObservation.inventory.counts,
              });
            }),
        },
      }).pipe(Effect.flatMap(({ awaitCompletion }) => awaitCompletion)),
    ));

    expect(portalFrameQueries).toBeGreaterThanOrEqual(3);
    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: currentPosition,
      radius: 0.5,
    }));
    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: {
        x: 2,
        y: 9,
        z: -2,
        dimension: "minecraft:overworld",
      },
      radius: 0.5,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        maxFallDistance: 1,
      }),
    }));
  });

  it("resumes a checkpoint and completes after policy confirms the fight", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      dimension: "minecraft:the_end",
      counts: {
        "minecraft:cooked_beef": 16,
        "minecraft:bow": 1,
        "minecraft:arrow": 32,
      },
    });
    const store = new InMemoryBeatGameCheckpointStore();
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.FIGHT_ENDER_DRAGON,
      {
        runId: "resumed-run",
        teamId: "resumed-team",
        planner: {
          ...checkpoint(BeatGamePhase.FIGHT_ENDER_DRAGON).planner,
          status: BeatGameRunStatus.RECOVERING,
        },
      },
    ), undefined));

    const result = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "resumed-run",
        team: { teamId: "resumed-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
        hooks: postDragonHooks(driver),
      }).pipe(Effect.flatMap(({ awaitCompletion }) => awaitCompletion)),
    ));

    expect(result.finalCheckpoint.planner.phase).toBe(BeatGamePhase.COMPLETE);
    expect(result.finalCheckpoint.planner.status)
      .toBe(BeatGameRunStatus.COMPLETED);
    expect(result.finalCheckpoint.revision).toBeGreaterThan(1);
  });

  it("replans when a queued hunting target is no longer observable", async () => {
    const driver = new FakeBeatGameDriver();
    const allRequiredItems = {
      "minecraft:cooked_beef": 16,
      "minecraft:oak_log": 8,
      "minecraft:cobblestone": 20,
      "minecraft:stone_sword": 1,
      "minecraft:iron_ingot": 7,
      "minecraft:iron_pickaxe": 1,
      "minecraft:water_bucket": 1,
      "minecraft:lava_bucket": 1,
      "minecraft:flint_and_steel": 1,
      "minecraft:shield": 1,
      "minecraft:obsidian": 10,
      "minecraft:blaze_rod": 7,
      "minecraft:ender_pearl": 14,
      "minecraft:ender_eye": 12,
      "minecraft:bow": 1,
      "minecraft:arrow": 32,
      "minecraft:torch": 1,
    };
    driver.currentObservation = observation({
      counts: {
        ...allRequiredItems,
        "minecraft:cooked_beef": 0,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:cow",
      position: {
        x: 5,
        y: 64,
        z: 5,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    let attackAttempts = 0;
    driver.taskResolver = (task) => {
      if (task.type !== "attack-entity") {
        return Effect.succeed({});
      }
      attackAttempts += 1;
      driver.currentObservation = observation({ counts: allRequiredItems });
      return Effect.fail(new BeatGameDriverError({
        operation: "task.attack-entity",
        code: "unreachable",
        retryable: false,
        message: "Target entity is not observable",
      }));
    };
    const updateDimension = (dimension: string) =>
      Effect.sync(() => {
        driver.currentObservation = observation({
          dimension,
          counts: driver.currentObservation.inventory.counts,
        });
      });
    const store = new InMemoryBeatGameCheckpointStore();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "missing-hunt-target-run",
      teamId: "missing-hunt-target-team",
    });
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        strongholdEstimate: {
          x: 100,
          y: 32,
          z: 100,
          dimension: "minecraft:overworld",
        },
      },
    }, undefined));

    const result = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "missing-hunt-target-run",
        team: { teamId: "missing-hunt-target-team" },
        checkpointStore: store,
        strategy: {
          observationPollMs: 1,
          portalStrategy: "OBSIDIAN",
        },
        hooks: {
          buildAndEnterNether: () =>
            updateDimension("minecraft:the_nether"),
          returnThroughPortal: () =>
            updateDimension("minecraft:overworld"),
          searchStronghold: () => Effect.succeed(true),
          activateEndPortal: () => updateDimension("minecraft:the_end"),
          fightEnderDragon: () => Effect.succeed(true),
          collectDragonEgg: ({ observation: current }) =>
            Effect.sync(() => {
              driver.currentObservation = observation({
                dimension: "minecraft:the_end",
                counts: {
                  ...current.inventory.counts,
                  "minecraft:dragon_egg": 1,
                },
              });
            }),
          exitEnd: () => updateDimension("minecraft:overworld"),
        },
      }).pipe(Effect.flatMap(({ awaitCompletion }) => awaitCompletion)),
    ));

    expect(attackAttempts).toBe(1);
    expect(result.finalCheckpoint.planner.status)
      .toBe(BeatGameRunStatus.COMPLETED);
  });

  it("selects the nearest fresh hunting target after every kill", async () => {
    const driver = new FakeBeatGameDriver();
    const preparedItems = {
      "minecraft:oak_log": 2,
      "minecraft:cobblestone": 20,
      "minecraft:stone_sword": 1,
      "minecraft:iron_ingot": 7,
      "minecraft:iron_pickaxe": 1,
      "minecraft:water_bucket": 1,
      "minecraft:flint_and_steel": 1,
      "minecraft:shield": 1,
    };
    const targets = [
      {
        connectionEpoch: "epoch-1",
        networkId: 1,
        entityType: "minecraft:cow",
        position: {
          x: 10,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        },
        velocity: { x: 0, y: 0, z: 0 },
        alive: true,
        observedAt: "2026-01-01T00:00:00.000Z",
      },
      {
        connectionEpoch: "epoch-1",
        networkId: 2,
        entityType: "minecraft:cow",
        position: {
          x: -11,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        },
        velocity: { x: 0, y: 0, z: 0 },
        alive: true,
        observedAt: "2026-01-01T00:00:00.000Z",
      },
      {
        connectionEpoch: "epoch-1",
        networkId: 3,
        entityType: "minecraft:cow",
        position: {
          x: 20,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        },
        velocity: { x: 0, y: 0, z: 0 },
        alive: true,
        observedAt: "2026-01-01T00:00:00.000Z",
      },
      {
        connectionEpoch: "epoch-1",
        networkId: 4,
        entityType: "minecraft:cow",
        position: {
          x: 1,
          y: 36,
          z: 0,
          dimension: "minecraft:overworld",
        },
        velocity: { x: 0, y: 0, z: 0 },
        alive: true,
        observedAt: "2026-01-01T00:00:00.000Z",
      },
    ] as const;
    driver.currentObservation = observation({ counts: preparedItems });
    driver.entityResults = targets;
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
        driver.currentObservation = observation({
          counts: preparedItems,
          position: {
            x,
            y: 64,
            z,
            dimension,
          },
        });
      });
    const attackOrder: number[] = [];
    driver.taskObserver = (task) => {
      if (task.type !== "attack-entity") {
        return;
      }
      attackOrder.push(task.target.networkId);
      const target = targets.find(({ networkId }) =>
        networkId === task.target.networkId
      );
      if (target !== undefined) {
        driver.currentObservation = observation({
          counts: preparedItems,
          position: target.position,
        });
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (attackOrder.length < 3) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(attackOrder).toEqual([1, 3, 2]);
    const huntQueries = driver.entityQueries.filter(({ selector }) =>
      selector.entityTypes?.includes("minecraft:cow") === true
    );
    expect(huntQueries.slice(0, 3).map(({ origin }) => origin?.x))
      .toEqual([0, 10, 20]);
  });

  it("does not let ineligible aquatic mobs crowd land animals out of a hunt", async () => {
    const driver = new FakeBeatGameDriver();
    const preparedItems = {
      "minecraft:oak_log": 2,
      "minecraft:cobblestone": 20,
      "minecraft:stone_sword": 1,
      "minecraft:iron_ingot": 7,
      "minecraft:iron_pickaxe": 1,
      "minecraft:water_bucket": 1,
      "minecraft:flint_and_steel": 1,
      "minecraft:shield": 1,
    };
    const salmon = Array.from({ length: 16 }, (_, index) => ({
      connectionEpoch: "epoch-1",
      networkId: index + 1,
      entityType: "minecraft:salmon",
      position: {
        x: index + 2,
        y: 60,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    })) satisfies readonly BeatGameEntityObservation[];
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 17,
      entityType: "minecraft:cow",
      position: {
        x: 1,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    } satisfies BeatGameEntityObservation;
    const candidates = [...salmon, cow];
    driver.currentObservation = observation({
      food: 20,
      counts: preparedItems,
    });
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:cow") === true
        ? candidates.slice(0, query.maximumResults ?? candidates.length)
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        driver.taskObserver(task);
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    const firstHuntQuery = driver.entityQueries.find(({ selector }) =>
      selector.entityTypes?.includes("minecraft:cow") === true
    );
    expect(firstHuntQuery?.maximumResults).toBeGreaterThanOrEqual(
      candidates.length,
    );
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: cow.networkId }),
    }));
    expect(driver.xzPaths).toHaveLength(0);
  });

  it("crosses nearby water to collect food after a hunt", async () => {
    const driver = new FakeBeatGameDriver();
    const preparedItems = {
      "minecraft:oak_log": 2,
      "minecraft:cobblestone": 20,
      "minecraft:stone_sword": 1,
      "minecraft:iron_ingot": 7,
      "minecraft:iron_pickaxe": 1,
      "minecraft:water_bucket": 1,
      "minecraft:flint_and_steel": 1,
      "minecraft:shield": 1,
    };
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 5,
      entityType: "minecraft:cow",
      position: {
        x: 1,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    const droppedBeef = {
      connectionEpoch: "epoch-1",
      networkId: 6,
      entityType: "minecraft:item",
      itemId: "minecraft:beef",
      itemCount: 1,
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    let cowDefeated = false;
    driver.currentObservation = observation({ counts: preparedItems });
    driver.entityQueryResolver = (query) => {
      if (query.selector.entityTypes?.includes("minecraft:item")) {
        return cowDefeated ? [droppedBeef] : [];
      }
      return query.selector.entityTypes?.includes("minecraft:cow")
          && !cowDefeated
        ? [cow]
        : [];
    };
    driver.taskObserver = (task) => {
      if (task.type === "attack-entity") {
        cowDefeated = true;
      }
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.paths.some(({ position }) =>
              position.x === droppedBeef.position.x
              && position.z === droppedBeef.position.z
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: droppedBeef.position,
      policy: expect.objectContaining({
        allowPlacing: false,
        avoidFluids: false,
      }),
    }));
  });

  it("recovers surfaced food drops before choosing new prey", async () => {
    const driver = new FakeBeatGameDriver();
    const preparedItems = {
      "minecraft:oak_log": 8,
      "minecraft:cobblestone": 20,
      "minecraft:stone_sword": 1,
      "minecraft:iron_ingot": 7,
      "minecraft:iron_pickaxe": 1,
      "minecraft:water_bucket": 1,
      "minecraft:flint_and_steel": 1,
      "minecraft:shield": 1,
    };
    const surfacedSalmon = {
      connectionEpoch: "epoch-1",
      networkId: 7,
      entityType: "minecraft:item",
      itemId: "minecraft:salmon",
      itemCount: 1,
      position: {
        x: 24,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 8,
      entityType: "minecraft:cow",
      position: {
        x: 1,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.currentObservation = observation({ counts: preparedItems });
    driver.entityQueryResolver = (query) =>
      query.selector.entityTypes?.includes("minecraft:item") === true
        ? [surfacedSalmon]
        : query.selector.entityTypes?.includes("minecraft:cow") === true
        ? [cow]
        : [];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (!driver.paths.some(({ position }) =>
              position.x === surfacedSalmon.position.x
              && position.z === surfacedSalmon.position.z
            )) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: surfacedSalmon.position,
      policy: expect.objectContaining({
        allowPlacing: false,
        avoidFluids: false,
      }),
    }));
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  });

  it("refreshes a distant animal between bounded approach segments", async () => {
    const driver = new FakeBeatGameDriver();
    const preparedItems = {
      "minecraft:cobblestone": 20,
      "minecraft:oak_log": 8,
      "minecraft:stone_sword": 1,
    };
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 1,
      entityType: "minecraft:cow",
      position: {
        x: 100,
        y: 64,
        z: 100,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({ counts: preparedItems });
    driver.entityResults = [cow];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
        driver.currentObservation = observation({
          counts: preparedItems,
          position: {
            x,
            y: 64,
            z,
            dimension,
          },
        });
      });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "attack-entity" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: {
          observationPollMs: 1,
          entitySearchRadius: 320,
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.xzPaths).toHaveLength(3);
    expect(driver.xzPaths[0]).toEqual(expect.objectContaining({
      radius: 2,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        avoidFluids: true,
      }),
    }));
    expect(driver.xzPaths[0]?.x).toBeCloseTo(33.941);
    expect(driver.xzPaths[0]?.z).toBeCloseTo(33.941);
    expect(driver.xzPaths[1]).toEqual(expect.objectContaining({
      radius: 2,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        avoidFluids: true,
      }),
    }));
    expect(driver.xzPaths[1]?.x).toBeCloseTo(67.882);
    expect(driver.xzPaths[1]?.z).toBeCloseTo(67.882);
    expect(driver.xzPaths[2]).toEqual(expect.objectContaining({
      radius: 2,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        avoidFluids: true,
      }),
    }));
    expect(driver.xzPaths[2]?.x).toBeCloseTo(85.858);
    expect(driver.xzPaths[2]?.z).toBeCloseTo(85.858);
    const huntQueries = driver.entityQueries.filter(({ selector }) =>
      selector.entityTypes?.includes("minecraft:cow") === true
    );
    expect(huntQueries.slice(0, 4).map(({ origin }) => origin?.x))
      .toEqual([
        0,
        expect.closeTo(33.941),
        expect.closeTo(67.882),
        expect.closeTo(85.858),
      ]);
    expect(huntQueries.slice(0, 4).map(({ origin }) => origin?.z))
      .toEqual([
        0,
        expect.closeTo(33.941),
        expect.closeTo(67.882),
        expect.closeTo(85.858),
      ]);
  });

  it("uses short approach segments toward food while wounded", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      food: 17,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:oak_log": 8,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 1,
      entityType: "minecraft:cow",
      position: {
        x: 100,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: {
          observationPollMs: 1,
          entitySearchRadius: 320,
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.xzPaths[0]).toEqual(expect.objectContaining({
      x: 12,
      z: 0,
      radius: 2,
      policy: expect.objectContaining({
        allowMining: false,
        allowPlacing: false,
        avoidFluids: true,
        maxFallDistance: 2,
        sprint: false,
      }),
    }));
  });

  it("retries a distant animal from a new approach after a cooldown", async () => {
    const driver = new FakeBeatGameDriver();
    const store = new InMemoryBeatGameCheckpointStore();
    const initial = checkpoint(BeatGamePhase.PREPARE_OVERWORLD, {
      runId: "distant-animal-retry-run",
      teamId: "distant-animal-retry-team",
    });
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 1,
      entityType: "minecraft:cow",
      position: {
        x: 100,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    await Effect.runPromise(store.save({
      ...initial,
      memory: {
        ...initial.memory,
        unreachable: [{
          key: `target:${cow.connectionEpoch}:${cow.networkId}`,
          value: cow.position,
          observedAt: new Date(Date.now() - 30_000).toISOString(),
          expiresAt: "2030-01-01T00:00:00.000Z",
          confidence: 1,
        }],
      },
    }, undefined));
    driver.currentObservation = observation({
      health: 8,
      food: 17,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:oak_log": 8,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [cow];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "distant-animal-retry-run",
        team: { teamId: "distant-animal-retry-team" },
        checkpointStore: store,
        strategy: {
          observationPollMs: 1,
          entitySearchRadius: 320,
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.xzPaths[0]).toEqual(expect.objectContaining({
      x: 12,
      z: 0,
      radius: 2,
    }));
  });

  it("moves inside attack range instead of repeating a satisfied approach", async () => {
    const driver = new FakeBeatGameDriver();
    const preparedItems = {
      "minecraft:cobblestone": 20,
      "minecraft:oak_log": 8,
      "minecraft:stone_sword": 1,
    };
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 2,
      entityType: "minecraft:cow",
      position: {
        x: 25.5,
        y: 64,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({
      counts: preparedItems,
      position: {
        x: 0.5,
        y: 64,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
    });
    driver.entityResults = [cow];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
        driver.currentObservation = observation({
          counts: preparedItems,
          position: { x, y: 64, z, dimension },
        });
      });
    driver.taskObserver = (task) => {
      if (task.type === "attack-entity") {
        driver.entityResults = [];
      }
    };

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: {
          observationPollMs: 1,
          entitySearchRadius: 64,
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (
              !driver.tasks.some((task) => task.type === "attack-entity")
            ) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.xzPaths).toHaveLength(1);
    expect(driver.xzPaths[0]).toEqual(expect.objectContaining({
      x: 5.5,
      z: 0.5,
      dimension: "minecraft:overworld",
      radius: 2,
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        connectionEpoch: cow.connectionEpoch,
        networkId: cow.networkId,
      }),
    }));
    expect(driver.taskPolicies.at(-1)?.avoidFluids).toBe(true);
  });

  it("recovers toward the surface when a distant hunt route is blocked", async () => {
    const driver = new FakeBeatGameDriver();
    const preparedItems = {
      "minecraft:cobblestone": 20,
      "minecraft:oak_log": 8,
      "minecraft:stone_sword": 1,
    };
    driver.currentObservation = observation({ counts: preparedItems });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 1,
      entityType: "minecraft:cow",
      position: {
        x: 100,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.surfaceColumns = [{
      x: 12,
      z: 0,
      loaded: true,
      surfaceY: 64,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
        driver.currentObservation = observation({
          counts: preparedItems,
          position: {
            x: 12,
            y: 30,
            z: 0,
            dimension,
          },
        });
      }).pipe(
        Effect.zipRight(Effect.fail(new BeatGameDriverError({
          operation: "pathfindXZ",
          code: "unreachable",
          retryable: true,
          message: "The distant route made no progress",
        }))),
      );
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: {
          observationPollMs: 1,
          entitySearchRadius: 320,
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.paths.length === 0) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.xzPaths).toHaveLength(1);
    expect(driver.paths[0]).toEqual({
      position: {
        x: 12.5,
        y: 65,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 1.5,
      policy: expect.objectContaining({
        allowMining: true,
        allowPlacing: true,
      }),
    });
  });

  it("does not invoke swimming recovery for a failed route on dry ground", async () => {
    const driver = new FakeBeatGameDriver();
    const preparedItems = {
      "minecraft:cobblestone": 20,
      "minecraft:oak_log": 8,
      "minecraft:stone_sword": 1,
    };
    driver.currentObservation = observation({ counts: preparedItems });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 1,
      entityType: "minecraft:cow",
      position: {
        x: 100,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.surfaceColumns = [{
      x: 0,
      z: 0,
      loaded: true,
      surfaceY: 63,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(
        Effect.zipRight(Effect.fail(new BeatGameDriverError({
          operation: "pathfindXZ",
          code: "unreachable",
          retryable: true,
          message: "The distant route made no progress",
        }))),
      );

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        strategy: {
          observationPollMs: 1,
          entitySearchRadius: 320,
        },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.gen(function* () {
            while (driver.xzPaths.length < 2) {
              yield* Effect.sleep(1);
            }
            yield* run.stop;
            yield* run.awaitCompletion.pipe(Effect.either);
          })
        ),
      ),
    ));

    expect(driver.actions).not.toContainEqual(expect.objectContaining({
      type: "set-movement",
      forward: true,
      jump: true,
      sprint: true,
    }));
  });

  it("returns to the surface before collecting logs", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 0.5,
        y: 21,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      counts: {
        "minecraft:oak_log": 3,
        "minecraft:stone_pickaxe": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.surfaceColumns = [{
      x: 0,
      z: 0,
      loaded: true,
      surfaceY: 63,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.gen(function* () {
        while (driver.paths.length === 0) {
          yield* Effect.sleep(1);
        }
      }).pipe(Effect.timeout("5 seconds"));
      yield* run.stop;
    })));

    expect(driver.paths[0]).toEqual(expect.objectContaining({
      position: {
        x: 0.5,
        y: 64,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
    }));
    expect(driver.tasks.some((task) =>
      task.type === "collect-blocks"
      && task.blockIds.includes("minecraft:oak_log")
    )).toBe(false);
  });

  it("opens a shallow vertical shaft before resuming exploration", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 0.5,
        y: 60,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      counts: {
        "minecraft:oak_log": 3,
        "minecraft:stone_pickaxe": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.surfaceColumns = [{
      x: 0,
      z: 0,
      loaded: true,
      surfaceY: 62,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds?.includes("minecraft:water") === true) {
        return [];
      }
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      return [blockObservation(position, position.y === 62
        ? { blockId: "minecraft:grass_block" }
        : {
          blockId: "minecraft:air",
          diggable: false,
          replaceable: true,
          solid: false,
        })];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (driver.paths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.actions).toContainEqual(expect.objectContaining({
      type: "dig-block",
      position: {
        x: 0,
        y: 62,
        z: 0,
        dimension: "minecraft:overworld",
      },
    }));
    expect(driver.paths[0]).toMatchObject({
      position: {
        x: 0.5,
        y: 63,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 1,
      policy: {
        allowMining: true,
        allowPlacing: true,
        avoidFluids: true,
      },
    });
  }, 10_000);

  it("climbs a two-block-deep sealed pocket by a bounded staircase", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 0.5,
        y: 60,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      counts: {
        "minecraft:oak_log": 3,
        "minecraft:stone_pickaxe": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.surfaceColumns = [{
      x: 0,
      z: 0,
      loaded: true,
      surfaceY: 62,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    const blocks = new Map<string, ReturnType<typeof blockObservation>>();
    const setBlock = (
      position: BeatGameBlockPosition,
      overrides: Parameters<typeof blockObservation>[1] = {},
    ) => {
      blocks.set(
        `${position.x}:${position.y}:${position.z}`,
        blockObservation(position, overrides),
      );
    };
    for (let rise = 1; rise <= 3; rise += 1) {
      setBlock({
        x: rise,
        y: 60 + rise - 1,
        z: 0,
        dimension: "minecraft:overworld",
      });
      for (const y of [60 + rise, 61 + rise]) {
        setBlock({
          x: rise,
          y,
          z: 0,
          dimension: "minecraft:overworld",
        });
      }
    }
    driver.blockQueryResolver = ({ center, radius, selector }) => {
      if (selector.blockIds?.includes("minecraft:water") === true) {
        return [];
      }
      if (radius > 0.25 || Object.keys(selector).length > 0) {
        return [];
      }
      const block = blocks.get(
        `${Math.floor(center.x)}:${Math.floor(center.y)}:${
          Math.floor(center.z)
        }`,
      );
      return block === undefined ? [] : [block];
    };
    driver.actionObserver = (action) => {
      if (action.type !== "dig-block") {
        return;
      }
      setBlock(action.position, {
        blockId: "minecraft:air",
        diggable: false,
        replaceable: true,
        solid: false,
      });
    };
    driver.pathResolver = (position, radius, policy) => {
      const record = Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      });
      if (radius !== 0.35) {
        return record.pipe(Effect.zipRight(Effect.never));
      }
      return record.pipe(Effect.tap(() => Effect.sync(() => {
        driver.currentObservation = {
          ...driver.currentObservation,
          player: {
            ...driver.currentObservation.player,
            position,
          },
        };
      })));
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.gen(function* () {
        while (driver.currentObservation.player.position.y < 63) {
          yield* Effect.sleep(1);
        }
      }).pipe(Effect.timeout("5 seconds"));
      yield* run.stop;
    })));

    expect(driver.paths.map(({ position, radius, policy }) => ({
      position,
      radius,
      policy,
    }))).toEqual([
      expect.objectContaining({
        position: expect.objectContaining({ x: 1.5, y: 61, z: 0.5 }),
        radius: 0.35,
        policy: expect.objectContaining({
          allowMining: false,
          allowPlacing: false,
        }),
      }),
      expect.objectContaining({
        position: expect.objectContaining({ x: 2.5, y: 62, z: 0.5 }),
        radius: 0.35,
      }),
      expect.objectContaining({
        position: expect.objectContaining({ x: 3.5, y: 63, z: 0.5 }),
        radius: 0.35,
      }),
    ]);
    expect(driver.tasks.some((task) =>
      task.type === "collect-blocks"
      && task.blockIds.includes("minecraft:oak_log")
    )).toBe(false);
  });

  it("allows a surface recovery route to leave flowing water", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 0.5,
        y: 21,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      counts: {
        "minecraft:oak_log": 3,
        "minecraft:stone_pickaxe": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.surfaceColumns = [{
      x: 0,
      z: 0,
      loaded: true,
      surfaceY: 63,
      blockId: "minecraft:grass_block",
      biomeId: "minecraft:plains",
      skyLight: 15,
      blockLight: 0,
    }];
    driver.blockQueryResolver = ({ center, selector }) =>
      selector.blockIds?.includes("minecraft:water") === true
          && Math.floor(center.x) === 0
          && Math.floor(center.y) === 21
          && Math.floor(center.z) === 0
        ? [blockObservation({
          x: 0,
          y: 21,
          z: 0,
          dimension: "minecraft:overworld",
        }, {
          blockId: "minecraft:water",
          replaceable: true,
          solid: false,
          properties: { level: "3" },
        })]
        : [];
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.gen(function* () {
        while (driver.paths.length === 0) {
          yield* Effect.sleep(1);
        }
      }).pipe(Effect.timeout("5 seconds"));
      yield* run.stop;
    })));

    expect(driver.paths[0]).toEqual(expect.objectContaining({
      position: {
        x: 0.5,
        y: 64,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      policy: expect.objectContaining({ avoidFluids: false }),
    }));
  });

  it("keeps log collection dry while allowing frontier water crossings", async () => {
    const driver = new FakeBeatGameDriver();
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (driver.xzPaths.length === 0) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    const logCollectionIndex = driver.tasks.findIndex((task) =>
      task.type === "collect-blocks"
      && task.blockIds.includes("minecraft:oak_log")
    );
    expect(logCollectionIndex).toBeGreaterThanOrEqual(0);
    expect(driver.tasks[logCollectionIndex]).toEqual(expect.objectContaining({
      type: "collect-blocks",
      avoidSubmergedTargets: true,
      requireLineOfSight: false,
    }));
    expect(driver.taskPolicies[logCollectionIndex]?.avoidFluids).toBe(true);
    expect(driver.xzPaths[0]?.policy.allowMining).toBe(false);
    expect(driver.xzPaths[0]?.policy.avoidFluids).not.toBe(true);
  });

  it("allows a collection route to leave fluid for a dry log target", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 0.5,
        y: 63,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
    });
    driver.blockQueryResolver = ({ center, selector }) =>
      selector.blockIds?.includes("minecraft:water") === true
          && Math.floor(center.x) === 0
          && Math.floor(center.y) === 63
          && Math.floor(center.z) === 0
        ? [blockObservation({
          x: 0,
          y: 63,
          z: 0,
          dimension: "minecraft:overworld",
        }, {
          blockId: "minecraft:water",
          replaceable: true,
        })]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks" ? Effect.never : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) =>
        task.type === "collect-blocks"
        && task.blockIds.includes("minecraft:oak_log")
      )) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    const logCollectionIndex = driver.tasks.findIndex((task) =>
      task.type === "collect-blocks"
      && task.blockIds.includes("minecraft:oak_log")
    );
    expect(logCollectionIndex).toBeGreaterThanOrEqual(0);
    expect(driver.tasks[logCollectionIndex]).toEqual(expect.objectContaining({
      type: "collect-blocks",
      avoidSubmergedTargets: true,
    }));
    expect(driver.taskPolicies[logCollectionIndex]?.avoidFluids).toBe(false);
  });

  it("crafts a basic sword and pickaxe before mining cobblestone", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:cooked_beef": 16,
        "minecraft:oak_log": 8,
      },
    });
    let craftingTablePlaced = false;
    let resolveCollection!: () => void;
    const collectionStarted = new Promise<void>((resolve) => {
      resolveCollection = resolve;
    });
    driver.recipeResolver = (resultItemId) => [{
      recipeId: resultItemId,
      recipeType: "minecraft:crafting",
      resultItemId,
      resultCount: 1,
      ingredients: [],
    }];
    driver.craftabilityResolver = (recipeId) => ({
      canCraft: true,
      maximumCraftCount: 1,
      ...(
        recipeId === "minecraft:wooden_pickaxe"
          || recipeId === "minecraft:wooden_sword"
        ? { requiredStation: "minecraft:crafting_table" }
        : {}
      ),
      missing: [],
    });
    driver.blockQueryResolver = ({ center, selector }) => {
      if (
        craftingTablePlaced
        && selector.blockIds?.includes("minecraft:crafting_table") === true
      ) {
        return [blockObservation({
          x: 2,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:crafting_table" })];
      }
      if (selector.replaceable === false) {
        return [blockObservation({
          x: 2,
          y: 63,
          z: 0,
          dimension: "minecraft:overworld",
        })];
      }
      if (
        selector.diggable === true
        && selector.interactive === false
      ) {
        return [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        }, {
          blockId: "minecraft:stone",
          replaceable: false,
        })];
      }
      return [];
    };
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "build") {
          craftingTablePlaced = true;
        }
        if (task.type === "craft" && (
          task.recipeId === "minecraft:wooden_pickaxe"
          || task.recipeId === "minecraft:wooden_sword"
        )) {
          driver.currentObservation = observation({
            counts: {
              ...driver.currentObservation.inventory.counts,
              [task.recipeId]: 1,
            },
          });
        }
        if (task.type === "collect-blocks") {
          expect(task.blockIds).toEqual(["minecraft:stone"]);
          expect(task.count).toBe(32);
          expect(task.avoidSubmergedTargets).toBe(true);
          expect(driver.taskPolicies.at(-1)?.avoidFluids).toBe(true);
          expect(
            driver.currentObservation.inventory.counts[
              "minecraft:wooden_pickaxe"
            ],
          ).toBe(1);
          resolveCollection();
        }
        return {};
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => collectionStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks.map((task) => task.type === "craft"
      ? `${task.type}:${task.recipeId}`
      : task.type)).toEqual([
      "craft:minecraft:crafting_table",
      "build",
      "craft:minecraft:wooden_sword",
      "craft:minecraft:wooden_pickaxe",
      "collect-blocks",
    ]);
    expect(driver.blockQueries).toContainEqual(expect.objectContaining({
      radius: 32,
      selector: { blockIds: ["minecraft:crafting_table"] },
    }));
    expect(driver.blockQueries).toContainEqual(expect.objectContaining({
      selector: { diggable: true, interactive: false },
    }));
  });

  it("replaces a pickaxe that breaks during buffered cobblestone collection", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:cooked_beef": 16,
        "minecraft:oak_log": 8,
        "minecraft:wooden_sword": 1,
        "minecraft:wooden_pickaxe": 1,
        "minecraft:cobblestone": 14,
        "minecraft:raw_copper": 26,
      },
    });
    driver.recipeResolver = (resultItemId) => [{
      recipeId: resultItemId,
      recipeType: "minecraft:crafting",
      resultItemId,
      resultCount: 1,
      ingredients: [],
    }];
    driver.craftabilityResolver = () => ({
      canCraft: true,
      maximumCraftCount: 1,
      requiredStation: "minecraft:crafting_table",
      missing: [],
    });
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds?.includes("minecraft:crafting_table") === true) {
        return [blockObservation({
          x: 1,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:crafting_table" })];
      }
      return selector.diggable === true
        ? [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        })]
        : [];
    };
    const discardTimeline: string[] = [];
    const resolvePath = driver.pathResolver;
    driver.pathResolver = (position, radius, policy) =>
      resolvePath(position, radius, policy).pipe(
        Effect.tap(() =>
          Effect.sync(() => {
            if (radius === 0.75) {
              if (
                position.x < -5.9
                && Math.abs(position.z) < 0.01
              ) {
                discardTimeline.push(
                  policy.allowMining
                    ? "path:discard-site"
                    : "path:pocket-return",
                );
              } else if (
                Math.abs(position.x) < 0.01
                && Math.abs(position.z) < 0.01
              ) {
                discardTimeline.push("path:return");
              }
            }
            const currentPosition =
              driver.currentObservation.player.position;
            const emptyPlayerSlots =
              driver.currentObservation.inventory.emptyPlayerSlots;
            const deltaX = position.x - currentPosition.x;
            const deltaZ = position.z - currentPosition.z;
            const yaw = Math.hypot(deltaX, deltaZ) < 0.001
              ? driver.currentObservation.player.rotation.yaw
              : Math.atan2(-deltaX, deltaZ) * 180 / Math.PI;
            driver.currentObservation = observation({
              counts: driver.currentObservation.inventory.counts,
              ...(emptyPlayerSlots === undefined
                ? {}
                : { emptyPlayerSlots }),
              position,
              rotation: {
                yaw,
                pitch: driver.currentObservation.player.rotation.pitch,
              },
            });
          })
        ),
        Effect.flatMap(() =>
          radius === 0.75
            && policy.allowMining === false
            ? Effect.fail(new BeatGameDriverError({
              operation: "pathfind",
              retryable: false,
              message: "The discard escape direction is blocked",
            }))
            : Effect.void
        ),
      );
    let collectionAttempts = 0;
    let resolveReplacementCollection!: () => void;
    const replacementCollectionStarted = new Promise<void>((resolve) => {
      resolveReplacementCollection = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (task.type === "collect-blocks") {
        collectionAttempts += 1;
        if (collectionAttempts === 1) {
          const counts: Record<string, number> = {
            ...driver.currentObservation.inventory.counts,
            "minecraft:cobblestone": 18,
          };
          delete counts["minecraft:wooden_pickaxe"];
          driver.currentObservation = observation({
            counts,
            emptyPlayerSlots: 0,
          });
          return Effect.void;
        }
        resolveReplacementCollection();
        return Effect.never;
      }
      if (
        task.type === "craft"
        && task.recipeId === "minecraft:wooden_pickaxe"
      ) {
        driver.currentObservation = observation({
          counts: {
            ...driver.currentObservation.inventory.counts,
            "minecraft:wooden_pickaxe": 1,
          },
        });
      }
      return Effect.void;
    };
    let pendingInventoryObservations = 0;
    let tossActions = 0;
    driver.observationResolver = () =>
      Effect.sync(() => {
        if (pendingInventoryObservations > 0) {
          pendingInventoryObservations -= 1;
          if (pendingInventoryObservations === 0) {
            driver.currentObservation = observation({
              counts: driver.currentObservation.inventory.counts,
              emptyPlayerSlots: tossActions === 1 ? 1 : 3,
              position: driver.currentObservation.player.position,
              rotation: driver.currentObservation.player.rotation,
            });
          }
        }
        return driver.currentObservation;
      });
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        if (action.type === "look") {
          const emptyPlayerSlots =
            driver.currentObservation.inventory.emptyPlayerSlots;
          driver.currentObservation = observation({
            counts: driver.currentObservation.inventory.counts,
            ...(emptyPlayerSlots === undefined
              ? {}
              : { emptyPlayerSlots }),
            position: driver.currentObservation.player.position,
            rotation: {
              yaw: action.yaw,
              pitch: action.pitch,
            },
          });
        }
        if (action.type === "dig-block") {
          discardTimeline.push(
            `dig:${action.position.x}:${action.position.y}:${action.position.z}`,
          );
        }
        if (action.type === "toss-items") {
          tossActions += 1;
          const itemId = action.selector.itemIds?.[0];
          if (itemId !== undefined) {
            discardTimeline.push(`toss:${itemId}`);
            const counts = {
              ...driver.currentObservation.inventory.counts,
            };
            delete counts[itemId];
            driver.currentObservation = observation({
              counts,
              emptyPlayerSlots: 0,
              position: driver.currentObservation.player.position,
              rotation: driver.currentObservation.player.rotation,
            });
          }
          pendingInventoryObservations = 2;
        }
        return {};
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => replacementCollectionStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks.map((task) =>
      task.type === "craft"
        ? `${task.type}:${task.recipeId}`
        : task.type
    )).toEqual([
      "collect-blocks",
      "craft:minecraft:wooden_pickaxe",
      "collect-blocks",
    ]);
    expect(driver.actions.filter((action) =>
      action.type === "toss-items"
      && action.selector.itemIds?.includes("minecraft:cobblestone") === true
      && action.count === 18
    )).toHaveLength(1);
    expect(driver.actions.filter((action) =>
      action.type === "toss-items"
      && action.selector.itemIds?.includes("minecraft:raw_copper") === true
      && action.count === 26
    )).toHaveLength(1);
    expect(driver.actions.filter((action) =>
      action.type === "look"
      && action.pitch === 0
    )).toHaveLength(1);
    expect(driver.actions.filter((action) =>
      action.type === "look"
      && Math.abs(Math.abs(action.yaw) - 180) < 0.001
    )).toHaveLength(1);
    expect(discardTimeline.slice(0, 8)).toEqual([
      "path:discard-site",
      "dig:-6:65:-1",
      "dig:-6:64:-1",
      "dig:-6:65:-2",
      "dig:-6:64:-2",
      "toss:minecraft:raw_copper",
      "toss:minecraft:cobblestone",
      "path:return",
    ]);
    expect(driver.paths.filter(({ position, radius, policy }) =>
      radius === 0.75
      && Math.abs(position.x + 6) < 0.001
      && Math.abs(position.z) < 0.001
      && policy.allowMining === true
      && policy.allowPlacing === false
      && policy.avoidFluids === true
    )).toHaveLength(1);
    expect(driver.paths.filter(({ position, radius, policy }) =>
      radius === 0.75
      && Math.abs(position.x) < 0.001
      && Math.abs(position.z) < 0.001
      && policy.allowMining === false
      && policy.allowPlacing === false
      && policy.avoidFluids === true
    )).toHaveLength(1);
  });

  it("stops an in-flight collection once external inventory gains meet its buffered target", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: { y: 24 },
      counts: {
        "minecraft:cooked_beef": 12,
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 30,
        "minecraft:stone_sword": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:water_bucket": 1,
      },
    });
    let resolveIronCollection!: () => void;
    const ironCollectionStarted = new Promise<void>((resolve) => {
      resolveIronCollection = resolve;
    });
    let collectionInterrupted = false;
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (
        task.type === "collect-blocks"
        && task.blockIds.includes("minecraft:iron_ore")
      ) {
        resolveIronCollection();
        return Effect.never.pipe(
          Effect.onInterrupt(() =>
            Effect.sync(() => {
              collectionInterrupted = true;
            })
          ),
        );
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => ironCollectionStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      driver.currentObservation = observation({
        counts: {
          ...driver.currentObservation.inventory.counts,
          "minecraft:raw_iron": 10,
        },
      });
      while (!collectionInterrupted) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(collectionInterrupted).toBe(true);
    expect(driver.tasks.filter((task) =>
      task.type === "collect-blocks"
      && task.blockIds.includes("minecraft:iron_ore")
    )).toHaveLength(1);
  });

  it("descends toward iron-rich depth before exploring laterally", async () => {
    const driver = new FakeBeatGameDriver();
    const surfacePosition = {
      x: 24.5,
      y: 64,
      z: -12.5,
      dimension: "minecraft:overworld",
    } as const;
    driver.currentObservation = observation({
      position: surfacePosition,
      counts: {
        "minecraft:cooked_beef": 12,
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 30,
        "minecraft:stone_sword": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:water_bucket": 1,
      },
    });
    const dugBlocks = new Set<string>();
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        if (action.type === "dig-block") {
          dugBlocks.add(
            `${action.position.x}:${action.position.y}:${action.position.z}`,
          );
        }
        return {};
      });
    installStaircaseMovementSimulation(driver, {
      x: Math.floor(surfacePosition.x),
      y: surfacePosition.y,
      z: Math.floor(surfacePosition.z),
      dimension: surfacePosition.dimension,
    });
    driver.blockQueryResolver = ({ center }) => {
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      const dug = dugBlocks.has(`${position.x}:${position.y}:${position.z}`);
      return [blockObservation(position, dug
        ? {
          blockId: "minecraft:air",
          diggable: false,
          replaceable: true,
        }
        : { blockId: "minecraft:stone" })];
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (driver.currentObservation.player.position.y > 52) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.currentObservation.player.position.y).toBeLessThanOrEqual(
      52,
    );
    expect(driver.tasks.filter((task) =>
      task.type === "collect-blocks"
      && task.blockIds.includes("minecraft:iron_ore")
    )).toHaveLength(0);
  });

  it("mines loaded iron before descending past it", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: {
        x: 24.5,
        y: 64,
        z: -12.5,
        dimension: "minecraft:overworld",
      },
      counts: {
        "minecraft:cooked_beef": 5,
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 30,
        "minecraft:stone_sword": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:water_bucket": 1,
      },
    });
    const nearbyIron = blockObservation({
      x: 24,
      y: 55,
      z: -12,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:iron_ore" });
    driver.blockQueryResolver = (query) =>
      query.selector.blockIds?.includes("minecraft:iron_ore") === true
        ? [nearbyIron]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(
        Effect.zipRight(
          task.type === "collect-blocks"
              && task.blockIds.includes("minecraft:iron_ore")
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) =>
        task.type === "collect-blocks"
        && task.blockIds.includes("minecraft:iron_ore")
      )) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks.some((task) =>
      task.type === "collect-blocks"
      && task.blockIds.includes("minecraft:iron_ore")
    )).toBe(true);
    expect(driver.actions.some((action) => action.type === "dig-block"))
      .toBe(false);
  });

  it("does not treat submerged kelp as staircase footing", async () => {
    const driver = new FakeBeatGameDriver();
    const surfacePosition = {
      x: 0.5,
      y: 64,
      z: 0.5,
      dimension: "minecraft:overworld",
    } as const;
    driver.currentObservation = observation({
      position: surfacePosition,
      counts: {
        "minecraft:cooked_beef": 12,
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 30,
        "minecraft:stone_sword": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:water_bucket": 1,
      },
    });
    const kelp = blockObservation({
      x: 1,
      y: 63,
      z: 0,
      dimension: surfacePosition.dimension,
    }, {
      blockId: "minecraft:kelp",
      replaceable: false,
      solid: false,
    });
    const stone = blockObservation({
      x: 2,
      y: 63,
      z: 0,
      dimension: surfacePosition.dimension,
    });
    driver.blockQueryResolver = ({ center, radius, selector }) => {
      if (radius === 12 && selector.solid === true) {
        return [kelp, stone];
      }
      const position = {
        x: Math.floor(center.x),
        y: Math.floor(center.y),
        z: Math.floor(center.z),
        dimension: center.dimension,
      };
      if (position.x === 0 && position.y === 63 && position.z === 0) {
        return [blockObservation(position, {
          blockId: "minecraft:sand",
          solid: true,
        })];
      }
      if (position.y === 63 && position.z === 0) {
        return [position.x === 1 ? kelp : stone];
      }
      return [blockObservation(position, {
        blockId: "minecraft:air",
        diggable: false,
        replaceable: true,
        solid: false,
      })];
    };
    let resolveStableApproach!: () => void;
    const stableApproach = new Promise<void>((resolve) => {
      resolveStableApproach = resolve;
    });
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
        if (position.x === 2.5 && radius === 0.75) {
          resolveStableApproach();
        }
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => stableApproach).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: expect.objectContaining({ x: 2.5, y: 64, z: 0.5 }),
      radius: 0.75,
    }));
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: expect.objectContaining({ x: 1.5, y: 64, z: 0.5 }),
    }));
    expect(driver.blockQueries).toContainEqual(expect.objectContaining({
      radius: 12,
      selector: expect.objectContaining({
        solid: true,
        requireLineOfSight: true,
      }),
    }));
  });

  it("explores laterally at iron mining depth when candidates are unreachable", async () => {
    const driver = new FakeBeatGameDriver();
    const miningPosition = {
      x: 24.5,
      y: 16,
      z: -12.5,
      dimension: "minecraft:overworld",
    } as const;
    driver.currentObservation = observation({
      position: miningPosition,
      counts: {
        "minecraft:cooked_beef": 12,
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 30,
        "minecraft:stone_sword": 1,
        "minecraft:stone_pickaxe": 1,
        "minecraft:water_bucket": 1,
      },
      remainingDurability: { "minecraft:stone_pickaxe": 131 },
    });
    driver.recipeResolver = (resultItemId) => [{
      recipeId: resultItemId,
      recipeType: "minecraft:crafting",
      resultItemId,
      resultCount: 1,
      ingredients: [],
    }];
    driver.craftabilityResolver = () => ({
      canCraft: true,
      maximumCraftCount: 1,
      requiredStation: "minecraft:crafting_table",
      missing: [],
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:crafting_table") === true
        ? [blockObservation({
          x: 23,
          y: 16,
          z: -12,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:crafting_table" })]
        : [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (
          task.type === "collect-blocks"
          && task.blockIds.includes("minecraft:iron_ore")
        ) {
          driver.currentObservation = observation({
            position: miningPosition,
            counts: driver.currentObservation.inventory.counts,
            remainingDurability: { "minecraft:stone_pickaxe": 1 },
          });
        }
        if (
          task.type === "craft"
          && task.recipeId === "minecraft:stone_pickaxe"
        ) {
          driver.currentObservation = observation({
            position: miningPosition,
            counts: {
              ...driver.currentObservation.inventory.counts,
              "minecraft:stone_pickaxe": 2,
            },
            remainingDurability: { "minecraft:stone_pickaxe": 132 },
          });
        }
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        !driver.paths.some(({ radius, policy }) =>
          radius === 2 && policy.allowMining === true
        )
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(driver.paths.find(({ radius, policy }) =>
      radius === 2 && policy.allowMining === true
    )).toEqual({
      position: expect.objectContaining({ y: miningPosition.y }),
      radius: 2,
      policy: expect.objectContaining({
        allowMining: true,
        avoidFluids: true,
      }),
    });
    expect(driver.xzPaths).toHaveLength(0);
    expect(driver.tasks.map((task) =>
      task.type === "craft"
        ? `${task.type}:${task.recipeId}`
        : task.type
    )).toEqual([
      "collect-blocks",
      "craft:minecraft:stone_pickaxe",
    ]);
  });

  it("keeps collecting cobblestone until the requested buffer is full", async () => {
    const driver = new FakeBeatGameDriver();
    const baseCounts = {
      "minecraft:cooked_beef": 12,
      "minecraft:oak_log": 8,
      "minecraft:cobblestone": 8,
      "minecraft:stone_sword": 1,
      "minecraft:wooden_pickaxe": 1,
    };
    driver.currentObservation = observation({ counts: baseCounts });
    let resolveCollectionStarted!: () => void;
    const collectionStarted = new Promise<void>((resolve) => {
      resolveCollectionStarted = resolve;
    });
    let collectionInterrupted = false;
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (
        task.type === "collect-blocks"
        && task.blockIds.includes("minecraft:stone")
      ) {
        resolveCollectionStarted();
        return Effect.never.pipe(
          Effect.onInterrupt(() =>
            Effect.sync(() => {
              collectionInterrupted = true;
            })
          ),
        );
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => collectionStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      driver.currentObservation = observation({
        counts: {
          ...baseCounts,
          "minecraft:cobblestone": 20,
        },
      });
      yield* Effect.sleep(25);
      expect(collectionInterrupted).toBe(false);
      driver.currentObservation = observation({
        counts: {
          ...baseCounts,
          "minecraft:cobblestone": 32,
        },
      });
      while (!collectionInterrupted) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
      yield* run.awaitCompletion.pipe(Effect.either);
    })));

    expect(collectionInterrupted).toBe(true);
    expect(driver.tasks.filter((task) =>
      task.type === "collect-blocks"
      && task.blockIds.includes("minecraft:stone")
    )).toHaveLength(1);
  });

  it("upgrades a missing or broken wooden pickaxe before mining iron", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:cooked_beef": 12,
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 30,
        "minecraft:stone_sword": 1,
      },
    });
    driver.recipeResolver = (resultItemId) => [{
      recipeId: resultItemId,
      recipeType: "minecraft:crafting",
      resultItemId,
      resultCount: 1,
      ingredients: [],
    }];
    driver.craftabilityResolver = () => ({
      canCraft: true,
      maximumCraftCount: 1,
      requiredStation: "minecraft:crafting_table",
      missing: [],
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:crafting_table") === true
        ? [blockObservation({
          x: 1,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:crafting_table" })]
        : [];
    let resolveIronCollection!: () => void;
    const ironCollectionStarted = new Promise<void>((resolve) => {
      resolveIronCollection = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (
        task.type === "craft"
        && task.recipeId === "minecraft:stone_pickaxe"
      ) {
        driver.currentObservation = observation({
          counts: {
            ...driver.currentObservation.inventory.counts,
            "minecraft:stone_pickaxe": 1,
          },
        });
      }
      if (
        task.type === "collect-blocks"
        && task.blockIds.includes("minecraft:iron_ore")
      ) {
        expect(task.avoidSubmergedTargets).toBe(true);
        expect(driver.taskPolicies.at(-1)?.avoidFluids).toBe(true);
        resolveIronCollection();
        return Effect.never;
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => ironCollectionStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks.map((task) =>
      task.type === "craft"
        ? `${task.type}:${task.recipeId}`
        : task.type
    )).toEqual([
      "craft:minecraft:stone_pickaxe",
      "collect-blocks",
    ]);
  });

  it("replaces a remembered workstation that cannot be reached", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      position: { y: 54 },
      counts: {
        "minecraft:cooked_beef": 8,
        "minecraft:oak_log": 5,
        "minecraft:oak_planks": 3,
        "minecraft:stick": 2,
        "minecraft:wooden_pickaxe": 1,
        "minecraft:cobblestone": 20,
      },
    });
    const unreachableTable = blockObservation({
      x: 8,
      y: 54,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:crafting_table" });
    const undergroundTable = blockObservation({
      x: 2,
      y: 40,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:crafting_table" });
    const localTable = blockObservation({
      x: 1,
      y: 54,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:crafting_table" });
    let localTablePlaced = false;
    driver.recipeResolver = (resultItemId) => [{
      recipeId: resultItemId,
      recipeType: "minecraft:crafting",
      resultItemId,
      resultCount: 1,
      ingredients: [],
    }];
    driver.craftabilityResolver = (recipeId) => ({
      canCraft: true,
      maximumCraftCount: 1,
      ...(recipeId === "minecraft:stone_sword"
        ? { requiredStation: "minecraft:crafting_table" }
        : {}),
      missing: [],
    });
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds?.includes("minecraft:crafting_table") === true) {
        return localTablePlaced
          ? [localTable]
          : [undergroundTable, unreachableTable];
      }
      if (selector.replaceable === false) {
        return [blockObservation({
          x: 1,
          y: 53,
          z: 0,
          dimension: "minecraft:overworld",
        })];
      }
      if (selector.replaceable === true) {
        return [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        }, { replaceable: true })];
      }
      return [];
    };
    driver.pathResolver = (position, radius, policy) =>
      Effect.sync(() => {
        driver.paths.push({ position, radius, policy });
      }).pipe(
        Effect.zipRight(
          position.x === unreachableTable.position.x + 0.5
            ? Effect.fail(new BeatGameDriverError({
              operation: "pathfind",
              code: "unreachable_goal",
              retryable: false,
              message: "No route found to the goal",
            }))
            : Effect.void,
        ),
      );
    let resolveSwordCraft!: () => void;
    const swordCraftStarted = new Promise<void>((resolve) => {
      resolveSwordCraft = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (
        task.type === "craft"
        && task.recipeId === "minecraft:stone_sword"
      ) {
        resolveSwordCraft();
        return Effect.never;
      }
      return Effect.void;
    };
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        if (action.type === "place-block") {
          localTablePlaced = true;
        }
        return {};
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => swordCraftStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.paths[0]?.position).toEqual({
      x: 8.5,
      y: 54,
      z: 0.5,
      dimension: "minecraft:overworld",
    });
    expect(driver.paths[0]?.policy.allowMining).toBe(false);
    expect(driver.paths[0]?.policy.allowPlacing).toBe(false);
    expect(driver.paths[0]?.policy.avoidFluids).toBe(true);
    expect(driver.paths[0]?.policy.maxSearchTimeMs).toBe(5_000);
    expect(driver.paths[0]?.radius).toBe(1.5);
    expect(driver.paths).not.toContainEqual(expect.objectContaining({
      position: {
        x: undergroundTable.position.x + 0.5,
        y: undergroundTable.position.y,
        z: undergroundTable.position.z + 0.5,
        dimension: undergroundTable.position.dimension,
      },
    }));
    expect(driver.tasks.map((task) => task.type === "craft"
      ? `${task.type}:${task.recipeId}`
      : task.type)).toEqual([
      "craft:minecraft:crafting_table",
      "build",
      "craft:minecraft:stone_sword",
    ]);
    expect(driver.tasks.at(-1)).toMatchObject({
      station: localTable.position,
    });
    expect(driver.actions).toContainEqual({
      type: "select-item",
      selector: { itemIds: ["minecraft:crafting_table"] },
    });
    expect(driver.actions).toContainEqual({
      type: "place-block",
      against: {
        x: localTable.position.x,
        y: localTable.position.y - 1,
        z: localTable.position.z,
        dimension: localTable.position.dimension,
      },
      face: "up",
      hand: "main",
    });
  });

  it("cooks a full existing raw-food batch without exploring for a buffer", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:cooked_mutton": 5,
        "minecraft:beef": 6,
        "minecraft:coal": 1,
        "minecraft:furnace": 1,
        "minecraft:oak_log": 3,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
      },
    });
    const furnace = blockObservation({
      x: 1,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:furnace" });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [furnace]
        : [];
    let resolveFoodSmeltStarted!: () => void;
    const foodSmeltStarted = new Promise<void>((resolve) => {
      resolveFoodSmeltStarted = resolve;
    });
    driver.taskObserver = (task) => {
      if (
        task.type === "smelt"
        && task.input.itemIds?.includes("minecraft:beef")
      ) {
        resolveFoodSmeltStarted();
      }
    };
    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => foodSmeltStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.entityQueries.some(({ selector }) =>
      selector.entityTypes?.includes("minecraft:cow") === true
    )).toBe(false);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "smelt",
      input: { itemIds: ["minecraft:beef"] },
      count: 6,
    }));
  });

  it("gathers a stone buffer before cooking without a furnace", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      food: defaultBeatGameStrategy.eatBelowFood,
      counts: {
        "minecraft:beef": 2,
        "minecraft:oak_log": 8,
        "minecraft:wooden_pickaxe": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:stone") === true
        ? [blockObservation({
          x: 2,
          y: 63,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:stone" })]
        : [];

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "collect-blocks")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "collect-blocks",
      blockIds: ["minecraft:stone"],
      count: 20,
    }));
    expect(driver.tasks.some((task) => task.type === "smelt")).toBe(false);
  });

  it("replans food preparation when furnace materials remain unavailable", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      food: defaultBeatGameStrategy.eatBelowFood,
      counts: {
        "minecraft:beef": 2,
        "minecraft:crafting_table": 1,
        "minecraft:oak_log": 8,
        "minecraft:wooden_pickaxe": 1,
        "minecraft:wooden_sword": 1,
      },
    });
    const craftingTable = blockObservation({
      x: 1,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:crafting_table" });
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds?.includes("minecraft:crafting_table") === true) {
        return [craftingTable];
      }
      if (selector.replaceable === false) {
        return [blockObservation({
          x: 2,
          y: 63,
          z: 0,
          dimension: "minecraft:overworld",
        })];
      }
      if (selector.replaceable === true) {
        return [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        }, { blockId: "minecraft:air", replaceable: true })];
      }
      return [];
    };
    driver.recipeResolver = (resultItemId) =>
      resultItemId === "minecraft:furnace"
        ? [{
          recipeId: "minecraft:furnace",
          recipeType: "minecraft:crafting_shaped",
          resultItemId,
          resultCount: 1,
          ingredients: [{
            itemIds: [
              "minecraft:blackstone",
              "minecraft:cobbled_deepslate",
              "minecraft:cobblestone",
            ],
            tags: [],
            count: 8,
          }],
        }]
        : [];
    driver.craftabilityResolver = () => ({
      canCraft: false,
      maximumCraftCount: 0,
      requiredStation: "minecraft:crafting_table",
      missing: [{
        itemIds: [
          "minecraft:blackstone",
          "minecraft:cobbled_deepslate",
          "minecraft:cobblestone",
        ],
        tags: [],
        available: 0,
        missing: 8,
      }],
    });

    const failure = await Effect.runPromise(Effect.scoped(
      Effect.gen(function* () {
        const run = yield* beatGameWithDriver(driver, {
          strategy: {
            maximumActionRetries: 0,
            observationPollMs: 1,
          },
        });
        const failure = yield* run.events.pipe(
          Stream.filter((event) =>
            event.type === "action-failed"
            && event.detail?.includes(
              "resource acquisition remains incomplete",
            ) === true
          ),
          Stream.runHead,
          Effect.timeout("5 seconds"),
        );
        return failure;
      }),
    ));

    expect(Option.isSome(failure)).toBe(true);
    expect(Option.getOrUndefined(failure)).toMatchObject({
      detail: expect.stringContaining("Interrupted for replanning"),
    });
    expect(driver.xzPaths.length).toBeGreaterThanOrEqual(1);
    expect(driver.tasks.some((task) => task.type === "smelt")).toBe(false);
  }, 10_000);

  it("cooks a partial raw-food batch at the normal hunger threshold", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      food: defaultBeatGameStrategy.eatBelowFood,
      counts: {
        "minecraft:chicken": 2,
        "minecraft:coal": 1,
        "minecraft:furnace": 1,
        "minecraft:oak_log": 9,
        "minecraft:cobblestone": 23,
        "minecraft:stone_sword": 1,
        "minecraft:wooden_pickaxe": 1,
      },
    });
    const furnace = blockObservation({
      x: 1,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:furnace" });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [furnace]
        : [];
    let resolveFoodSmeltStarted!: () => void;
    const foodSmeltStarted = new Promise<void>((resolve) => {
      resolveFoodSmeltStarted = resolve;
    });
    driver.taskObserver = (task) => {
      if (
        task.type === "smelt"
        && task.input.itemIds?.includes("minecraft:chicken")
      ) {
        resolveFoodSmeltStarted();
      }
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => foodSmeltStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.entityQueries.some(({ selector }) =>
      selector.entityTypes?.includes("minecraft:cow") === true
    )).toBe(false);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "smelt",
      input: { itemIds: ["minecraft:chicken"] },
      count: 2,
    }));
  });

  it("fishes exposed water at low health before exploring", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 6.5,
      food: 14,
      counts: {
        "minecraft:fishing_rod": 1,
        "minecraft:oak_log": 3,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:shield": 1,
      },
    });
    const water = blockObservation({
      x: 3,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, {
      blockId: "minecraft:water",
      properties: { level: "0" },
    });
    const airAboveWater = blockObservation({
      x: 3,
      y: 65,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:air", replaceable: true });
    driver.surfaceColumns = [-1, 0, 1].map((z) => ({
      x: 1,
      z,
      loaded: true,
      surfaceY: 63,
      blockId: "minecraft:grass_block",
      skyLight: 15,
      blockLight: 0,
    }));
    driver.blockQueryResolver = ({ center, radius, selector }) =>
      radius > 1
        && selector.blockIds?.includes("minecraft:water") === true
        && selector.requireLineOfSight !== true
        ? [water]
        : selector.replaceable === true
            && Math.floor(center.x) === airAboveWater.position.x
            && Math.floor(center.y) === airAboveWater.position.y
            && Math.floor(center.z) === airAboveWater.position.z
        ? [airAboveWater]
        : [];
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        if (action.type === "look") {
          driver.currentObservation = {
            ...driver.currentObservation,
            player: {
              ...driver.currentObservation.player,
              rotation: {
                yaw: action.yaw,
                pitch: action.pitch,
              },
            },
          };
        }
        return {};
      });
    let resolveFishingStarted!: () => void;
    const fishingStarted = new Promise<void>((resolve) => {
      resolveFishingStarted = resolve;
    });
    driver.taskObserver = (task) => {
      if (task.type === "fish") {
        resolveFishingStarted();
      }
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => fishingStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual({
      type: "fish",
      maximumCatches: 3,
      maximumFailedCasts: 4,
    });
    expect(driver.entityQueries.some(({ selector }) =>
      selector.entityTypes?.includes("minecraft:cow") === true
    )).toBe(false);
    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: {
        x: 1.5,
        y: 64,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 0.75,
      policy: expect.objectContaining({
        allowMining: false,
        avoidFluids: true,
      }),
    }));
  });

  it("casts from a stable lane instead of the nearest water edge", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 20,
      food: 14,
      position: { x: 0.5, y: 64, z: 0.5 },
      counts: {
        "minecraft:fishing_rod": 1,
        "minecraft:oak_log": 3,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:shield": 1,
      },
    });
    const water = blockObservation({
      x: 3,
      y: 62,
      z: 0,
      dimension: "minecraft:overworld",
    }, {
      blockId: "minecraft:water",
      properties: { level: "0" },
    });
    driver.surfaceColumns = [-1, 0, 1].flatMap((z) =>
      [0, 1, 2].map((x) => ({
        x,
        z,
        loaded: true,
        surfaceY: 63,
        blockId: "minecraft:grass_block",
        skyLight: 15,
        blockLight: 0,
      }))
    );
    driver.blockQueryResolver = ({ center, radius, selector }) =>
      radius > 1
        && selector.blockIds?.includes("minecraft:water") === true
        && selector.requireLineOfSight !== true
        ? [water]
        : selector.replaceable === true
            && Math.floor(center.x) === water.position.x
            && Math.floor(center.y) === water.position.y + 1
            && Math.floor(center.z) === water.position.z
        ? [blockObservation({
          ...water.position,
          y: water.position.y + 1,
        }, { blockId: "minecraft:air", replaceable: true })]
        : [];
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        if (action.type === "look") {
          driver.currentObservation = {
            ...driver.currentObservation,
            player: {
              ...driver.currentObservation.player,
              rotation: { yaw: action.yaw, pitch: action.pitch },
            },
          };
        }
        return {};
      });
    let resolveFishingStarted!: () => void;
    const fishingStarted = new Promise<void>((resolve) => {
      resolveFishingStarted = resolve;
    });
    driver.taskObserver = (task) => {
      if (task.type === "fish") {
        resolveFishingStarted();
      }
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => fishingStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: {
        x: 0.5,
        y: 64,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
    }));
    expect(driver.actions).toContainEqual(expect.objectContaining({
      type: "look",
      pitch: 30,
    }));
  });

  it("refreshes water after crafting a fishing rod and casts from shore", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 6.5,
      food: 14,
      counts: {
        "minecraft:stick": 3,
        "minecraft:string": 2,
      },
    });
    const initialWater = blockObservation({
      x: 3,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, {
      blockId: "minecraft:water",
      properties: { level: "0" },
    });
    const refreshedWater = blockObservation({
      x: 33,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, {
      blockId: "minecraft:water",
      properties: { level: "0" },
    });
    const craftingTable = blockObservation({
      x: 1,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:crafting_table" });
    driver.surfaceColumns = [-1, 0, 1].map((z) => ({
      x: 31,
      z,
      loaded: true,
      surfaceY: 63,
      blockId: "minecraft:grass_block",
      skyLight: 15,
      blockLight: 0,
    }));
    driver.recipeResolver = (resultItemId) => [{
      recipeId: resultItemId,
      recipeType: "minecraft:crafting",
      resultItemId,
      resultCount: 1,
      ingredients: [],
    }];
    driver.craftabilityResolver = () => ({
      canCraft: true,
      maximumCraftCount: 1,
      requiredStation: "minecraft:crafting_table",
      missing: [],
    });
    driver.blockQueryResolver = ({ center, radius, selector }) => {
      if (
        radius > 1
        && selector.blockIds?.includes("minecraft:water") === true
        && selector.properties?.level === "0"
      ) {
        return center.x < 10 ? [initialWater] : [refreshedWater];
      }
      if (
        selector.blockIds?.includes("minecraft:crafting_table") === true
      ) {
        return [craftingTable];
      }
      if (selector.replaceable === true) {
        const water = center.x < 10 ? initialWater : refreshedWater;
        return Math.floor(center.x) === water.position.x
            && Math.floor(center.y) === water.position.y + 1
            && Math.floor(center.z) === water.position.z
          ? [blockObservation({
            ...water.position,
            y: water.position.y + 1,
          }, { blockId: "minecraft:air", replaceable: true })]
          : [];
      }
      return [];
    };
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        if (action.type === "look") {
          driver.currentObservation = {
            ...driver.currentObservation,
            player: {
              ...driver.currentObservation.player,
              rotation: { yaw: action.yaw, pitch: action.pitch },
            },
          };
        }
        return {};
      });
    let resolveFishingStarted!: () => void;
    const fishingStarted = new Promise<void>((resolve) => {
      resolveFishingStarted = resolve;
    });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (
          task.type === "craft"
          && task.recipeId === "minecraft:fishing_rod"
        ) {
          driver.currentObservation = observation({
            health: 6.5,
            food: 14,
            position: { x: 30, y: 64, z: 0 },
            counts: { "minecraft:fishing_rod": 1 },
          });
        }
        if (task.type === "fish") {
          resolveFishingStarted();
        }
        return {};
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => fishingStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    const waterQueryCenters = driver.blockQueries.filter(({ selector }) =>
      selector.blockIds?.includes("minecraft:water") === true
      && selector.properties?.level === "0"
    ).map(({ center }) => center.x);
    expect(waterQueryCenters).toContain(0);
    expect(waterQueryCenters).toContain(30);
    expect(driver.paths).toContainEqual(expect.objectContaining({
      position: {
        x: 31.5,
        y: 64,
        z: 0.5,
        dimension: "minecraft:overworld",
      },
      radius: 0.75,
      policy: expect.objectContaining({ avoidFluids: true }),
    }));
  });

  it("hunts when optional fishing-rod ingredients are incomplete", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:string": 2,
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 20,
        "minecraft:stone_pickaxe": 1,
        "minecraft:stone_sword": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:shield": 1,
      },
    });
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:cow",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.surfaceColumns = [-1, 0, 1].map((z) => ({
      x: 0,
      z,
      loaded: true,
      surfaceY: 63,
      blockId: "minecraft:grass_block",
      skyLight: 15,
      blockLight: 0,
    }));
    let resolveHuntStarted!: () => void;
    const huntStarted = new Promise<void>((resolve) => {
      resolveHuntStarted = resolve;
    });
    driver.entityQueryResolver = (query) => {
      if (query.selector.entityTypes?.includes("minecraft:cow") === true) {
        resolveHuntStarted();
        return [cow];
      }
      return [];
    };
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (task.type === "attack-entity") {
        return Effect.never;
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => huntStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.entityQueries).toContainEqual(expect.objectContaining({
      selector: expect.objectContaining({
        entityTypes: expect.arrayContaining(["minecraft:cow"]),
      }),
    }));
    expect(driver.tasks.some((task) => task.type === "fish")).toBe(false);
  });

  it("hunts for food after fishing catches a non-food item", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:cooked_mutton": 7,
        "minecraft:fishing_rod": 1,
        "minecraft:oak_log": 3,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:shield": 1,
      },
    });
    const water = blockObservation({
      x: 3,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, {
      blockId: "minecraft:water",
      properties: { level: "0" },
    });
    const airAboveWater = blockObservation({
      x: 3,
      y: 65,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:air", replaceable: true });
    driver.surfaceColumns = [-1, 0, 1].map((z) => ({
      x: 1,
      z,
      loaded: true,
      surfaceY: 63,
      blockId: "minecraft:grass_block",
      skyLight: 15,
      blockLight: 0,
    }));
    driver.blockQueryResolver = ({ center, radius, selector }) =>
      radius > 1
        && selector.blockIds?.includes("minecraft:water") === true
        ? [water]
        : selector.replaceable === true
            && Math.floor(center.x) === airAboveWater.position.x
            && Math.floor(center.y) === airAboveWater.position.y
            && Math.floor(center.z) === airAboveWater.position.z
        ? [airAboveWater]
        : [];
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        if (action.type === "look") {
          driver.currentObservation = {
            ...driver.currentObservation,
            player: {
              ...driver.currentObservation.player,
              rotation: {
                yaw: action.yaw,
                pitch: action.pitch,
              },
            },
          };
        }
        return {};
      });
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:cow",
      position: {
        x: 6,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    let resolveHuntStarted!: () => void;
    const huntStarted = new Promise<void>((resolve) => {
      resolveHuntStarted = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (task.type === "fish") {
        driver.currentObservation = observation({
          counts: {
            ...driver.currentObservation.inventory.counts,
            "minecraft:pufferfish": 1,
          },
        });
        driver.entityResults = [cow];
      }
      if (task.type === "attack-entity") {
        resolveHuntStarted();
        return Effect.never;
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => huntStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks.map(({ type }) => type)).toContain("fish");
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        connectionEpoch: cow.connectionEpoch,
        networkId: cow.networkId,
      }),
    }));
  });

  it("immediately cooks a partial raw-food batch at low health", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      food: 17,
      counts: {
        "minecraft:porkchop": 1,
        "minecraft:coal": 2,
      },
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [blockObservation({
          x: 1,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:furnace" })]
        : [];
    let resolveFoodSmelt!: () => void;
    const foodSmeltStarted = new Promise<void>((resolve) => {
      resolveFoodSmelt = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (
        task.type === "smelt"
        && task.input.itemIds?.includes("minecraft:porkchop")
      ) {
        resolveFoodSmelt();
        return Effect.never;
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => foodSmeltStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.entityQueries.some(({ selector }) =>
      selector.entityTypes?.includes("minecraft:cow") === true
    )).toBe(false);
    expect(driver.tasks.filter((task) => task.type === "smelt")).toEqual([
      expect.objectContaining({
        input: { itemIds: ["minecraft:porkchop"] },
        count: 1,
        fuel: {
          itemIds: ["minecraft:coal", "minecraft:charcoal"],
        },
      }),
    ]);
  });

  it("does not interrupt raw-food cooking at the normal hunger threshold", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 10.5,
      food: 11,
      counts: {
        "minecraft:salmon": 1,
        "minecraft:coal": 1,
      },
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [blockObservation({
          x: 1,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:furnace" })]
        : [];
    let resolveFoodSmelt!: () => void;
    const foodSmeltStarted = new Promise<void>((resolve) => {
      resolveFoodSmelt = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (task.type === "smelt") {
        resolveFoodSmelt();
        return Effect.never;
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => foodSmeltStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* Effect.sleep(25);
      yield* run.stop;
    })));

    expect(driver.tasks.filter((task) => task.type === "smelt")).toHaveLength(1);
    expect(driver.tasks.some((task) => task.type === "auto-eat")).toBe(false);
  });

  it("recovers an interrupted food batch from a nearby furnace", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
      },
    });
    const furnace = blockObservation({
      x: 1,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:furnace" });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [furnace]
        : [];
    let resolveRecovery!: () => void;
    const recoveryStarted = new Promise<void>((resolve) => {
      resolveRecovery = resolve;
    });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "transfer-container") {
          driver.currentObservation = observation({
            counts: {
              ...driver.currentObservation.inventory.counts,
              "minecraft:cooked_mutton": 8,
            },
          });
          resolveRecovery();
        }
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => recoveryStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual({
      type: "transfer-container",
      direction: "withdraw",
      container: furnace.position,
      operations: [{
        selector: {},
        count: 192,
        allowPartial: true,
      }],
    });
    expect(driver.tasks.some((task) => task.type === "attack-entity"))
      .toBe(false);
  });

  it("drains an interrupted furnace before starting another food batch", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      food: 17,
      counts: {
        "minecraft:porkchop": 1,
        "minecraft:coal": 1,
      },
    });
    const furnace = blockObservation({
      x: 1,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:furnace" });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [furnace]
        : [];
    let resolveFoodSmelt!: () => void;
    const foodSmeltStarted = new Promise<void>((resolve) => {
      resolveFoodSmelt = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (task.type === "transfer-container") {
        driver.currentObservation = observation({
          counts: {
            ...driver.currentObservation.inventory.counts,
            "minecraft:cooked_chicken": 1,
          },
        });
        return Effect.void;
      }
      if (
        task.type === "smelt"
        && task.input.itemIds?.includes("minecraft:porkchop")
      ) {
        resolveFoodSmelt();
        return Effect.never;
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => foodSmeltStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks.slice(0, 2)).toEqual([
      {
        type: "transfer-container",
        direction: "withdraw",
        container: furnace.position,
        operations: [{
          selector: {},
          count: 192,
          allowPartial: true,
        }],
      },
      expect.objectContaining({
        type: "smelt",
        input: { itemIds: ["minecraft:porkchop"] },
        count: 1,
        fuel: {
          itemIds: ["minecraft:coal", "minecraft:charcoal"],
        },
        station: furnace.position,
      }),
    ]);
  });

  it("reclaims a furnace placed for a food batch", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      food: 17,
      counts: {
        "minecraft:porkchop": 1,
        "minecraft:coal": 1,
        "minecraft:furnace": 1,
        "minecraft:wooden_pickaxe": 1,
      },
    });
    const furnace = blockObservation({
      x: 2,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:furnace" });
    const craftingTable = blockObservation({
      x: 1,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:crafting_table" });
    let furnacePlaced = false;
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds?.includes("minecraft:furnace") === true) {
        return furnacePlaced ? [furnace] : [];
      }
      if (
        selector.blockIds?.includes("minecraft:crafting_table") === true
      ) {
        return [craftingTable];
      }
      if (selector.replaceable === false) {
        return [blockObservation({
          x: furnace.position.x,
          y: furnace.position.y - 1,
          z: furnace.position.z,
          dimension: furnace.position.dimension,
        })];
      }
      if (selector.replaceable === true) {
        return [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        }, { replaceable: true })];
      }
      return [];
    };
    const operationOrder: string[] = [];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        operationOrder.push(task.type);
        if (task.type === "build") {
          furnacePlaced = true;
        }
        if (
          task.type === "smelt"
          && task.input.itemIds?.includes("minecraft:porkchop")
        ) {
          driver.currentObservation = observation({
            health: 8,
            food: 17,
            counts: {
              "minecraft:cooked_porkchop": 1,
              "minecraft:wooden_pickaxe": 1,
            },
          });
        }
      });
    let resolveFurnaceReclaimed!: () => void;
    const furnaceReclaimed = new Promise<void>((resolve) => {
      resolveFurnaceReclaimed = resolve;
    });
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        operationOrder.push(action.type);
        if (
          action.type === "dig-block"
          && action.position.x === furnace.position.x
          && action.position.y === furnace.position.y
          && action.position.z === furnace.position.z
        ) {
          furnacePlaced = false;
          resolveFurnaceReclaimed();
        }
        return {};
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => furnaceReclaimed).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.actions).toContainEqual({
      type: "dig-block",
      position: furnace.position,
    });
    expect(operationOrder.indexOf("select-item")).toBeGreaterThan(
      operationOrder.indexOf("smelt"),
    );
    expect(operationOrder.indexOf("dig-block")).toBeGreaterThan(
      operationOrder.indexOf("select-item"),
    );
  });

  it("reclaims a placed furnace when cooking is interrupted", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      food: 17,
      counts: {
        "minecraft:porkchop": 1,
        "minecraft:coal": 1,
        "minecraft:furnace": 1,
        "minecraft:wooden_pickaxe": 1,
      },
    });
    const furnace = blockObservation({
      x: 2,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:furnace" });
    const craftingTable = blockObservation({
      x: 1,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:crafting_table" });
    let furnacePlaced = false;
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds?.includes("minecraft:furnace") === true) {
        return furnacePlaced ? [furnace] : [];
      }
      if (
        selector.blockIds?.includes("minecraft:crafting_table") === true
      ) {
        return [craftingTable];
      }
      if (selector.replaceable === false) {
        return [blockObservation({
          x: furnace.position.x,
          y: furnace.position.y - 1,
          z: furnace.position.z,
          dimension: furnace.position.dimension,
        })];
      }
      if (selector.replaceable === true) {
        return [blockObservation({
          x: Math.floor(center.x),
          y: Math.floor(center.y),
          z: Math.floor(center.z),
          dimension: center.dimension,
        }, { replaceable: true })];
      }
      return [];
    };
    let resolveSmeltStarted!: () => void;
    const smeltStarted = new Promise<void>((resolve) => {
      resolveSmeltStarted = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (task.type === "build") {
        furnacePlaced = true;
      }
      if (task.type === "smelt") {
        resolveSmeltStarted();
        return Effect.never;
      }
      return Effect.void;
    };
    let resolveFurnaceReclaimed!: () => void;
    const furnaceReclaimed = new Promise<void>((resolve) => {
      resolveFurnaceReclaimed = resolve;
    });
    driver.actionResolver = (action) =>
      Effect.sync(() => {
        if (
          action.type === "dig-block"
          && action.position.x === furnace.position.x
          && action.position.y === furnace.position.y
          && action.position.z === furnace.position.z
        ) {
          furnacePlaced = false;
          resolveFurnaceReclaimed();
        }
        return {};
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => smeltStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
      yield* Effect.promise(() => furnaceReclaimed).pipe(
        Effect.timeout("5 seconds"),
      );
    })));

    expect(driver.actions).toContainEqual({
      type: "dig-block",
      position: furnace.position,
    });
  });

  it("skips an unreachable recovery furnace and hunts for food", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
      },
    });
    const furnace = blockObservation({
      x: 1,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:furnace" });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [furnace]
        : [];
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:cow",
      position: {
        x: 3,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    let resolveHunt!: () => void;
    const huntStarted = new Promise<void>((resolve) => {
      resolveHunt = resolve;
    });
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
        if (task.type === "attack-entity") {
          resolveHunt();
        }
      }).pipe(
        Effect.zipRight(
          task.type === "transfer-container"
            ? Effect.fail(new BeatGameDriverError({
              operation: "task.transfer-container",
              code: "unreachable",
              retryable: false,
              message: "No route found to the goal",
            }))
            : task.type === "attack-entity"
            ? Effect.never
            : Effect.void,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => huntStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "transfer-container",
      container: furnace.position,
    }));
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
    }));
  });

  it("does not revisit a drained recovery furnace during the same run", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
      },
    });
    const furnace = blockObservation({
      x: 1,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:furnace" });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [furnace]
        : [];
    let resolveSecondFrontier!: () => void;
    const secondFrontierStarted = new Promise<void>((resolve) => {
      resolveSecondFrontier = resolve;
    });
    driver.xzPathResolver = (x, z, dimension, radius, policy) =>
      Effect.sync(() => {
        driver.xzPaths.push({ x, z, dimension, radius, policy });
        if (driver.xzPaths.length === 2) {
          resolveSecondFrontier();
        }
      }).pipe(
        Effect.flatMap(() =>
          driver.xzPaths.length === 1 ? Effect.void : Effect.never,
        ),
      );

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => secondFrontierStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks.filter((task) =>
      task.type === "transfer-container"
    )).toHaveLength(1);
  });

  it("ignores distant underground furnaces when gathering food", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
      },
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [blockObservation({
          x: 8,
          y: 32,
          z: 8,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:furnace" })]
        : [];
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:cow",
      position: {
        x: 3,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        !driver.tasks.some((task) => task.type === "attack-entity")
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks.some((task) =>
      task.type === "transfer-container"
    )).toBe(false);
  });

  it("prefers a nearby high-yield animal during emergency food recovery", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      food: 16,
      counts: {
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
      },
    });
    const chicken = {
      connectionEpoch: "epoch-1",
      networkId: 41,
      entityType: "minecraft:chicken",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 4,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    const cow = {
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:cow",
      position: {
        x: 12,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    driver.entityResults = [chicken, cow];
    driver.taskResolver = (task) =>
      Effect.sync(() => {
        driver.tasks.push(task);
      }).pipe(Effect.zipRight(Effect.never));

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "attack-entity")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({
        connectionEpoch: cow.connectionEpoch,
        networkId: cow.networkId,
      }),
    }));
  });

  it("retargets after a moving land animal exceeds its chase budget", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 20,
      food: 6,
      counts: {
        "minecraft:cobblestone": 20,
        "minecraft:oak_log": 8,
        "minecraft:wooden_sword": 1,
      },
    });
    const rabbit = {
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:rabbit",
      position: {
        x: 2,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:01.000Z",
    } as const;
    const cow = {
      ...rabbit,
      networkId: 44,
      entityType: "minecraft:cow",
      position: { ...rabbit.position, x: 4 },
      health: 10,
    } as const;
    driver.entityResults = [rabbit];
    driver.taskResolver = (task) =>
      Effect.suspend(() => {
        driver.tasks.push(task);
        if (task.type !== "attack-entity") {
          return Effect.void;
        }
        if (task.target.networkId !== rabbit.networkId) {
          return Effect.never;
        }
        driver.entityResults = [cow];
        return Effect.fail(new BeatGameDriverError({
          operation: "task.attack-entity",
          code: "land_chase_timeout",
          retryable: true,
          message: "The rabbit kept moving out of reach",
        }));
      });

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (
        driver.tasks.filter((task) => task.type === "attack-entity").length < 2
      ) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    }).pipe(Effect.timeout("5 seconds"))));

    expect(
      driver.tasks
        .filter((task) => task.type === "attack-entity")
        .slice(0, 2)
        .map((task) => task.type === "attack-entity"
          ? task.target.networkId
          : undefined),
    ).toEqual([rabbit.networkId, cow.networkId]);
  });

  it("eats raw food for emergency recovery when no furnace is available", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      food: 15,
      counts: { "minecraft:mutton": 2 },
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      return task.type === "auto-eat" ? Effect.never : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "auto-eat")) {
        yield* Effect.sleep(1);
      }
      yield* Effect.sleep(250);
      yield* run.stop;
    })));

    expect(driver.tasks.filter((task) => task.type === "auto-eat")).toEqual([
      expect.objectContaining({
        foodItemIds: ["minecraft:mutton"],
        foodLevel: 18,
        maximumMeals: 2,
        completeWhenNoFood: true,
      }),
    ]);
    expect(driver.tasks.some((task) =>
      task.type === "craft" || task.type === "smelt"
    )).toBe(false);
  });

  it("ignores a vertically distant furnace during emergency recovery", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      food: 15,
      counts: { "minecraft:salmon": 1 },
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [blockObservation({
          x: 1,
          y: 32,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:furnace" })]
        : [];
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      return task.type === "auto-eat" ? Effect.never : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "auto-eat")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "auto-eat",
      foodItemIds: ["minecraft:salmon"],
      foodLevel: 18,
      maximumMeals: 1,
      completeWhenNoFood: true,
    }));
    expect(driver.tasks.some((task) =>
      task.type === "craft" || task.type === "smelt"
    )).toBe(false);
  });

  it("eats raw food when a nearby furnace cannot be reached", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      food: 15,
      counts: { "minecraft:salmon": 1 },
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [blockObservation({
          x: 16,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:furnace" })]
        : [];
    driver.pathResolver = () =>
      Effect.fail(new BeatGameDriverError({
        operation: "pathfind",
        code: "unreachable",
        retryable: true,
        message: "The furnace is isolated by terrain",
      }));
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      return task.type === "auto-eat" ? Effect.never : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "auto-eat")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "auto-eat",
      foodItemIds: ["minecraft:salmon"],
      maximumMeals: 1,
      completeWhenNoFood: true,
    }));
    expect(driver.tasks.some((task) => task.type === "smelt")).toBe(false);
  });

  it("uses rotten flesh for emergency recovery instead of traveling for food", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      food: 17,
      counts: { "minecraft:rotten_flesh": 1 },
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      return task.type === "auto-eat" ? Effect.never : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "auto-eat")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "auto-eat",
      foodItemIds: ["minecraft:rotten_flesh"],
      foodLevel: 18,
      completeWhenNoFood: true,
    }));
    expect(driver.tasks.some((task) => task.type === "explore")).toBe(false);
  });

  it("preserves cookable food when emergency food can recover health", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 8,
      food: 17,
      counts: {
        "minecraft:cod": 2,
        "minecraft:rotten_flesh": 1,
      },
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      return task.type === "auto-eat" ? Effect.never : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "auto-eat")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "auto-eat",
      foodItemIds: ["minecraft:rotten_flesh"],
      foodLevel: 18,
      completeWhenNoFood: true,
    }));
  });

  it("does not interrupt eating solely because health becomes unsafe", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 19,
      food: 14,
      counts: { "minecraft:rotten_flesh": 1 },
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (task.type !== "auto-eat") {
        return Effect.void;
      }
      driver.currentObservation = observation({
        health: 17,
        food: 14,
        counts: { "minecraft:rotten_flesh": 1 },
      });
      return Effect.never;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.sleep(250);
      yield* run.stop;
    })));

    expect(driver.tasks.filter((task) => task.type === "auto-eat")).toEqual([
      expect.objectContaining({
        foodItemIds: ["minecraft:rotten_flesh"],
        foodLevel: 14,
        maximumMeals: 1,
      }),
    ]);
  });

  it("interrupts a food hunt to eat available food before hunger becomes unsafe", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      food: 15,
      counts: {
        "minecraft:oak_log": 4,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:cooked_mutton": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:cow",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    let interruptedHunts = 0;
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (task.type === "attack-entity") {
        driver.currentObservation = observation({
          food: 14,
          counts: {
            "minecraft:oak_log": 4,
            "minecraft:cobblestone": 20,
            "minecraft:stone_sword": 1,
            "minecraft:cooked_mutton": 1,
          },
        });
        return Effect.never.pipe(
          Effect.onInterrupt(() =>
            Effect.sync(() => {
              interruptedHunts += 1;
            })
          ),
        );
      }
      return task.type === "auto-eat" ? Effect.never : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "auto-eat")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(interruptedHunts).toBe(1);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "auto-eat",
      foodItemIds: ["minecraft:cooked_mutton"],
      foodLevel: 14,
      maximumMeals: 1,
    }));
  });

  it("interrupts resource gathering to hunt when hunger becomes urgent", async () => {
    const driver = new FakeBeatGameDriver();
    const salmon = {
      connectionEpoch: "epoch-1",
      networkId: 52,
      entityType: "minecraft:salmon",
      position: {
        x: 3,
        y: 61,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 3,
      observedAt: "2026-01-01T00:00:00.000Z",
    } as const;
    driver.currentObservation = observation({ food: 11 });
    driver.entityQueryResolver = ({ selector }) =>
      selector.entityTypes?.includes("minecraft:salmon") === true
        ? [salmon]
        : [];
    let interruptedCollections = 0;
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (task.type !== "collect-blocks") {
        return task.type === "attack-entity" ? Effect.never : Effect.void;
      }
      driver.currentObservation = observation({ food: 10 });
      return Effect.never.pipe(
        Effect.onInterrupt(() =>
          Effect.sync(() => {
            interruptedCollections += 1;
          })
        ),
      );
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "attack-entity")) {
        yield* Effect.sleep(1);
      }
      yield* run.stop;
    })));

    expect(interruptedCollections).toBe(1);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "attack-entity",
      target: expect.objectContaining({ networkId: salmon.networkId }),
    }));
  });

  it("continues gathering raw food through the normal meal threshold", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      food: 15,
      counts: {
        "minecraft:oak_log": 4,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:cooked_mutton": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 42,
      entityType: "minecraft:cow",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    let interruptedHunts = 0;
    let resolveHuntStarted!: () => void;
    const huntStarted = new Promise<void>((resolve) => {
      resolveHuntStarted = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (task.type !== "attack-entity") {
        return Effect.void;
      }
      driver.currentObservation = observation({
        food: 14,
        counts: {
          "minecraft:oak_log": 4,
          "minecraft:cobblestone": 20,
          "minecraft:stone_sword": 1,
          "minecraft:beef": 1,
        },
      });
      resolveHuntStarted();
      return Effect.never.pipe(
        Effect.onInterrupt(() =>
          Effect.sync(() => {
            interruptedHunts += 1;
          })
        ),
      );
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => huntStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* Effect.sleep(100);
      expect(interruptedHunts).toBe(0);
      expect(driver.tasks.some((task) => task.type === "auto-eat")).toBe(false);
      yield* run.stop;
    })));
  });

  it("keeps gathering wood with raw food above the emergency threshold", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      food: 8,
      counts: { "minecraft:mutton": 5 },
    });
    let interruptedCollections = 0;
    let resolveCollectionStarted!: () => void;
    const collectionStarted = new Promise<void>((resolve) => {
      resolveCollectionStarted = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (task.type !== "collect-blocks") {
        return Effect.void;
      }
      resolveCollectionStarted();
      return Effect.never.pipe(
        Effect.onInterrupt(() =>
          Effect.sync(() => {
            interruptedCollections += 1;
          })
        ),
      );
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => collectionStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* Effect.sleep(100);
      expect(interruptedCollections).toBe(0);
      expect(driver.tasks.some((task) => task.type === "auto-eat")).toBe(false);
      yield* run.stop;
    })));
  });

  it("continues a food-supply hunt while wounded", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      health: 14,
      food: 12,
      counts: {
        "minecraft:oak_log": 8,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 43,
      entityType: "minecraft:cow",
      position: {
        x: 8,
        y: 64,
        z: 0,
        dimension: "minecraft:overworld",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      health: 10,
      observedAt: "2026-01-01T00:00:01.000Z",
    }];
    let interruptedHunts = 0;
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      return task.type === "attack-entity"
        ? Effect.never.pipe(
          Effect.onInterrupt(() =>
            Effect.sync(() => {
              interruptedHunts += 1;
            })
          ),
        )
        : Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      while (!driver.tasks.some((task) => task.type === "attack-entity")) {
        yield* Effect.sleep(1);
      }
      yield* Effect.sleep(250);
      expect(interruptedHunts).toBe(0);
      yield* run.stop;
    })));
  });

  it("buffers charcoal before cooking a food batch", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:oak_log": 4,
        "minecraft:oak_planks": 3,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:beef": 8,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:water_bucket": 1,
        "minecraft:flint_and_steel": 1,
        "minecraft:shield": 1,
      },
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [blockObservation({
          x: 1,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:furnace" })]
        : [];
    let resolveFoodSmelt!: () => void;
    const foodSmeltStarted = new Promise<void>((resolve) => {
      resolveFoodSmelt = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (
        task.type !== "smelt"
        || !task.input.itemIds?.includes("minecraft:beef")
      ) {
        return Effect.void;
      }
      resolveFoodSmelt();
      return Effect.never;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => foodSmeltStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks.filter((task) => task.type === "smelt")).toEqual([
      expect.objectContaining({
        input: {
          itemIds: expect.arrayContaining(["minecraft:oak_log"]),
        },
        count: 3,
        fuel: {
          itemIds: [
            "minecraft:oak_planks",
            "minecraft:spruce_planks",
            "minecraft:birch_planks",
            "minecraft:jungle_planks",
            "minecraft:acacia_planks",
            "minecraft:dark_oak_planks",
            "minecraft:mangrove_planks",
            "minecraft:cherry_planks",
            "minecraft:pale_oak_planks",
            "minecraft:crimson_planks",
            "minecraft:warped_planks",
          ],
        },
      }),
      expect.objectContaining({
        input: { itemIds: ["minecraft:beef"] },
        count: 8,
        fuel: {
          itemIds: ["minecraft:coal", "minecraft:charcoal"],
        },
      }),
    ]);
  });

  it("gathers distinct starter fuel before turning the last log into charcoal", async () => {
    const driver = new FakeBeatGameDriver();
    const initialCounts = {
      "minecraft:oak_log": 2,
      "minecraft:cobblestone": 20,
      "minecraft:stone_sword": 1,
      "minecraft:beef": 8,
      "minecraft:iron_ingot": 7,
      "minecraft:iron_pickaxe": 1,
      "minecraft:water_bucket": 1,
      "minecraft:flint_and_steel": 1,
      "minecraft:shield": 1,
    };
    driver.currentObservation = observation({ counts: initialCounts });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [blockObservation({
          x: 1,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:furnace" })]
        : [];
    let resolveFoodSmelt!: () => void;
    const foodSmeltStarted = new Promise<void>((resolve) => {
      resolveFoodSmelt = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (task.type === "transfer-container") {
        driver.currentObservation = observation({
          counts: {
            ...initialCounts,
            "minecraft:oak_log": 1,
          },
        });
      }
      if (
        task.type === "collect-blocks"
        && task.blockIds.includes("minecraft:oak_log")
      ) {
        driver.currentObservation = observation({
          counts: {
            ...initialCounts,
            "minecraft:oak_log": 10,
          },
        });
      }
      if (
        task.type === "smelt"
        && task.input.itemIds?.includes("minecraft:beef")
      ) {
        resolveFoodSmelt();
        return Effect.never;
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => foodSmeltStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    const resourceTasks = driver.tasks.filter((task) =>
      task.type === "collect-blocks" || task.type === "smelt"
    );
    expect(resourceTasks).toEqual([
      expect.objectContaining({
        type: "collect-blocks",
        blockIds: expect.arrayContaining(["minecraft:oak_log"]),
        count: 8,
      }),
      expect.objectContaining({
        type: "smelt",
        input: {
          itemIds: expect.arrayContaining(["minecraft:oak_log"]),
        },
        count: 3,
        fuel: {
          itemIds: expect.arrayContaining(["minecraft:oak_log"]),
        },
      }),
      expect.objectContaining({
        type: "smelt",
        input: { itemIds: ["minecraft:beef"] },
        count: 8,
      }),
    ]);
  });

  it("moves a furnace batch after fuel gathering changes elevation", async () => {
    const driver = new FakeBeatGameDriver();
    const initialCounts = {
      "minecraft:oak_log": 2,
      "minecraft:cobblestone": 20,
      "minecraft:stone_sword": 1,
      "minecraft:beef": 8,
      "minecraft:iron_ingot": 7,
      "minecraft:iron_pickaxe": 1,
      "minecraft:water_bucket": 1,
      "minecraft:flint_and_steel": 1,
      "minecraft:shield": 1,
    };
    driver.currentObservation = observation({
      counts: initialCounts,
      position: { x: 0, y: 48, z: 0 },
    });
    const undergroundFurnace = blockObservation({
      x: 1,
      y: 48,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:furnace" });
    const surfaceFurnace = blockObservation({
      x: 3,
      y: 64,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:furnace" });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [driver.currentObservation.player.position.y >= 64
          ? surfaceFurnace
          : undergroundFurnace]
        : [];
    let resolveFoodSmelt!: () => void;
    const foodSmeltStarted = new Promise<void>((resolve) => {
      resolveFoodSmelt = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (
        task.type === "collect-blocks"
        && task.blockIds.includes("minecraft:oak_log")
      ) {
        driver.currentObservation = observation({
          counts: {
            ...initialCounts,
            "minecraft:oak_log": 10,
          },
          position: { x: 2, y: 64, z: 0 },
        });
      }
      if (
        task.type === "smelt"
        && task.input.itemIds?.includes("minecraft:beef")
      ) {
        resolveFoodSmelt();
        return Effect.never;
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => foodSmeltStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks.filter((task) => task.type === "smelt")).toEqual([
      expect.objectContaining({
        input: {
          itemIds: expect.arrayContaining(["minecraft:oak_log"]),
        },
        station: surfaceFurnace.position,
      }),
      expect.objectContaining({
        input: { itemIds: ["minecraft:beef"] },
        station: surfaceFurnace.position,
      }),
    ]);
    expect(driver.tasks).not.toContainEqual(expect.objectContaining({
      type: "smelt",
      station: undergroundFurnace.position,
    }));
  });

  it("uses existing efficient fuel without manufacturing a spare", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: {
        "minecraft:oak_log": 4,
        "minecraft:oak_planks": 3,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:porkchop": 8,
        "minecraft:charcoal": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:water_bucket": 1,
        "minecraft:flint_and_steel": 1,
        "minecraft:shield": 1,
      },
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [blockObservation({
          x: 1,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:furnace" })]
        : [];
    let resolveFoodSmelt!: () => void;
    const foodSmeltStarted = new Promise<void>((resolve) => {
      resolveFoodSmelt = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (
        task.type === "smelt"
        && task.input.itemIds?.includes("minecraft:porkchop")
      ) {
        resolveFoodSmelt();
        return Effect.never;
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => foodSmeltStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks.filter((task) => task.type === "smelt")).toEqual([
      expect.objectContaining({
        input: { itemIds: ["minecraft:porkchop"] },
        count: 8,
        fuel: {
          itemIds: ["minecraft:coal", "minecraft:charcoal"],
        },
      }),
    ]);
  });

  it("uses wood directly for a tiny food batch", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      food: 14,
      counts: {
        "minecraft:oak_log": 4,
        "minecraft:oak_planks": 1,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:cod": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:water_bucket": 1,
        "minecraft:flint_and_steel": 1,
        "minecraft:shield": 1,
      },
    });
    driver.blockQueryResolver = ({ selector }) =>
      selector.blockIds?.includes("minecraft:furnace") === true
        ? [blockObservation({
          x: 1,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:furnace" })]
        : [];
    let resolveFoodSmelt!: () => void;
    const foodSmeltStarted = new Promise<void>((resolve) => {
      resolveFoodSmelt = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (
        task.type === "smelt"
        && task.input.itemIds?.includes("minecraft:cod")
      ) {
        resolveFoodSmelt();
        return Effect.never;
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => foodSmeltStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks.filter((task) => task.type === "smelt")).toEqual([
      expect.objectContaining({
        input: { itemIds: ["minecraft:cod"] },
        count: 1,
        fuel: {
          itemIds: [
            "minecraft:oak_planks",
            "minecraft:spruce_planks",
            "minecraft:birch_planks",
            "minecraft:jungle_planks",
            "minecraft:acacia_planks",
            "minecraft:dark_oak_planks",
            "minecraft:mangrove_planks",
            "minecraft:cherry_planks",
            "minecraft:pale_oak_planks",
            "minecraft:crimson_planks",
            "minecraft:warped_planks",
          ],
        },
      }),
    ]);
  });

  it("mines nearby coal before burning wood for a small batch", async () => {
    const driver = new FakeBeatGameDriver();
    const initialCounts = {
      "minecraft:oak_log": 4,
      "minecraft:oak_planks": 3,
      "minecraft:cobblestone": 20,
      "minecraft:stone_sword": 1,
      "minecraft:cod": 1,
      "minecraft:iron_ingot": 7,
      "minecraft:iron_pickaxe": 1,
      "minecraft:water_bucket": 1,
      "minecraft:flint_and_steel": 1,
      "minecraft:shield": 1,
    };
    driver.currentObservation = observation({ food: 14, counts: initialCounts });
    driver.blockQueryResolver = ({ selector }) => {
      if (selector.blockIds?.includes("minecraft:furnace") === true) {
        return [blockObservation({
          x: 1,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:furnace" })];
      }
      if (selector.blockIds?.includes("minecraft:coal_ore") === true) {
        return [blockObservation({
          x: 3,
          y: 63,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:coal_ore" })];
      }
      return [];
    };
    let resolveFoodSmelt!: () => void;
    const foodSmeltStarted = new Promise<void>((resolve) => {
      resolveFoodSmelt = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (task.type === "collect-blocks") {
        driver.currentObservation = observation({
          counts: {
            ...initialCounts,
            "minecraft:coal": 4,
          },
        });
      }
      if (
        task.type === "smelt"
        && task.input.itemIds?.includes("minecraft:cod")
      ) {
        resolveFoodSmelt();
        return Effect.never;
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => foodSmeltStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.blockQueries).toContainEqual({
      center: expect.objectContaining({ dimension: "minecraft:overworld" }),
      radius: 16,
      selector: {
        blockIds: [
          "minecraft:coal_ore",
          "minecraft:deepslate_coal_ore",
        ],
        diggable: true,
      },
      maximumResults: 12,
    });
    const coalTaskIndex = driver.tasks.findIndex((task) =>
      task.type === "collect-blocks"
      && task.blockIds.includes("minecraft:coal_ore")
    );
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "collect-blocks",
      blockIds: [
        "minecraft:coal_ore",
        "minecraft:deepslate_coal_ore",
      ],
      count: 3,
      searchRadius: 16,
      avoidSubmergedTargets: true,
    }));
    expect(driver.taskPolicies[coalTaskIndex]).toMatchObject({
      avoidFluids: true,
    });
    expect(driver.tasks.filter((task) => task.type === "smelt")).toEqual([
      expect.objectContaining({
        input: { itemIds: ["minecraft:cod"] },
        count: 1,
        fuel: {
          itemIds: ["minecraft:coal", "minecraft:charcoal"],
        },
      }),
    ]);
  });

  it("uses wood instead of diving for submerged furnace coal", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      food: 14,
      counts: {
        "minecraft:oak_log": 4,
        "minecraft:oak_planks": 1,
        "minecraft:cobblestone": 20,
        "minecraft:stone_sword": 1,
        "minecraft:cod": 1,
        "minecraft:iron_ingot": 7,
        "minecraft:iron_pickaxe": 1,
        "minecraft:water_bucket": 1,
        "minecraft:flint_and_steel": 1,
        "minecraft:shield": 1,
      },
    });
    const coal = blockObservation({
      x: 3,
      y: 62,
      z: 0,
      dimension: "minecraft:overworld",
    }, { blockId: "minecraft:coal_ore" });
    driver.blockQueryResolver = ({ center, selector }) => {
      if (selector.blockIds?.includes("minecraft:furnace") === true) {
        return [blockObservation({
          x: 1,
          y: 64,
          z: 0,
          dimension: "minecraft:overworld",
        }, { blockId: "minecraft:furnace" })];
      }
      if (selector.blockIds?.includes("minecraft:coal_ore") === true) {
        return [coal];
      }
      if (
        selector.blockIds?.includes("minecraft:water") === true
        && Math.abs(center.x - (coal.position.x + 0.5)) < 0.1
        && Math.abs(center.y - (coal.position.y + 0.5)) < 0.1
      ) {
        return [blockObservation({
          ...coal.position,
          y: coal.position.y + 1,
        }, { blockId: "minecraft:water", replaceable: true })];
      }
      return [];
    };
    let resolveFoodSmelt!: () => void;
    const foodSmeltStarted = new Promise<void>((resolve) => {
      resolveFoodSmelt = resolve;
    });
    driver.taskResolver = (task) => {
      driver.tasks.push(task);
      if (
        task.type === "smelt"
        && task.input.itemIds?.includes("minecraft:cod")
      ) {
        resolveFoodSmelt();
        return Effect.never;
      }
      return Effect.void;
    };

    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const run = yield* beatGameWithDriver(driver, {
        strategy: { observationPollMs: 1 },
      });
      yield* Effect.promise(() => foodSmeltStarted).pipe(
        Effect.timeout("5 seconds"),
      );
      yield* run.stop;
    })));

    expect(driver.tasks.some((task) =>
      task.type === "collect-blocks"
      && task.blockIds.includes("minecraft:coal_ore")
    )).toBe(false);
    expect(driver.tasks).toContainEqual(expect.objectContaining({
      type: "smelt",
      input: { itemIds: ["minecraft:cod"] },
      fuel: {
        itemIds: expect.arrayContaining(["minecraft:oak_planks"]),
      },
    }));
  });

  it("runs custom Effect policy inside the normal planner lifecycle", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      dimension: "minecraft:the_end",
      counts: {
        "minecraft:cooked_beef": 16,
        "minecraft:bow": 1,
        "minecraft:arrow": 32,
      },
    });
    const store = new InMemoryBeatGameCheckpointStore();
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.FIGHT_ENDER_DRAGON,
      {
        runId: "hook-run",
        teamId: "hook-team",
      },
    ), undefined));
    let hookCheckpointRevision = 0;

    const result = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "hook-run",
        team: { teamId: "hook-team" },
        checkpointStore: store,
        hooks: {
          ...postDragonHooks(driver),
          fightEnderDragon: ({ checkpoint: current }) =>
            Effect.sync(() => {
              hookCheckpointRevision = current.revision;
              return true;
            }),
        },
      }).pipe(Effect.flatMap(({ awaitCompletion }) => awaitCompletion)),
    ));

    expect(hookCheckpointRevision).toBeGreaterThan(1);
    expect(result.finalCheckpoint.planner.status)
      .toBe(BeatGameRunStatus.COMPLETED);
  });

  it("coordinates and awaits every driver in a multi-bot run", async () => {
    const store = new InMemoryBeatGameCheckpointStore();
    const drivers = [
      new FakeBeatGameDriver("instance-1", "bot-a"),
      new FakeBeatGameDriver("instance-1", "bot-b"),
    ];
    for (const driver of drivers) {
      driver.currentObservation = observation({
        dimension: "minecraft:the_end",
        counts: {
          "minecraft:cooked_beef": 16,
          "minecraft:bow": 1,
          "minecraft:arrow": 32,
          "minecraft:torch": 1,
          "minecraft:dragon_egg": 1,
        },
      });
      await Effect.runPromise(store.save(checkpoint(
        BeatGamePhase.FIGHT_ENDER_DRAGON,
        {
          runId: `team-run-${driver.botId}`,
          teamId: "team-run",
          instanceId: driver.instanceId,
          botId: driver.botId,
        },
      ), undefined));
    }

    const results = await Effect.runPromise(Effect.scoped(
      beatGameTeamWithDrivers(drivers, {
        teamId: "team-run",
        checkpointStore: store,
        hooks: {
          exitEnd: ({ driver: current, observation: currentObservation }) =>
            Effect.sync(() => {
              const fake = drivers.find(({ botId }) =>
                botId === current.botId
              );
              if (fake === undefined) {
                throw new Error(`Missing fake driver ${current.botId}`);
              }
              fake.currentObservation = observation({
                dimension: "minecraft:overworld",
                counts: currentObservation.inventory.counts,
              });
            }),
        },
      }).pipe(Effect.flatMap(({ awaitCompletion }) => awaitCompletion)),
    ));

    expect(results.map(({ botId }) => botId).sort()).toEqual([
      "bot-a",
      "bot-b",
    ]);
    expect(results.every(({ finalCheckpoint }) =>
      finalCheckpoint.planner.status === BeatGameRunStatus.COMPLETED
    )).toBe(true);
  });

  it("recovers from retryable observation failures", async () => {
    const driver = new FakeBeatGameDriver();
    const endObservation = observation({
      dimension: "minecraft:the_end",
      counts: {
        "minecraft:cooked_beef": 16,
        "minecraft:bow": 1,
        "minecraft:arrow": 32,
      },
    });
    driver.currentObservation = endObservation;
    let observations = 0;
    driver.observationResolver = () => {
      observations += 1;
      if (observations === 2) {
        return Effect.fail(new BeatGameDriverError({
          operation: "observe",
          retryable: true,
          message: "connection restarted",
        }));
      }
      return Effect.succeed(driver.currentObservation);
    };
    const store = new InMemoryBeatGameCheckpointStore();
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.FIGHT_ENDER_DRAGON,
      {
        runId: "recovery-run",
        teamId: "recovery-team",
      },
    ), undefined));

    const result = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "recovery-run",
        team: { teamId: "recovery-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
        hooks: postDragonHooks(driver),
      }).pipe(Effect.flatMap(({ awaitCompletion }) => awaitCompletion)),
    ));

    expect(observations).toBeGreaterThanOrEqual(3);
    expect(result.finalCheckpoint.planner.status)
      .toBe(BeatGameRunStatus.COMPLETED);
  });

  it("observes a timed-out action before deciding whether to retry it", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      counts: { "minecraft:ender_eye": 12 },
    });
    const store = new InMemoryBeatGameCheckpointStore();
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.ACTIVATE_END_PORTAL,
      {
        runId: "idempotent-retry-run",
        teamId: "idempotent-retry-team",
      },
    ), undefined));
    let activationAttempts = 0;

    const result = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "idempotent-retry-run",
        team: { teamId: "idempotent-retry-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
        hooks: {
          ...postDragonHooks(driver),
          activateEndPortal: () =>
            Effect.suspend(() => {
              activationAttempts += 1;
              driver.currentObservation = observation({
                dimension: "minecraft:the_end",
                counts: {
                  "minecraft:cooked_beef": 16,
                  "minecraft:bow": 1,
                  "minecraft:arrow": 32,
                },
              });
              return Effect.fail(new BeatGameDriverError({
                operation: "activate-end-portal",
                retryable: true,
                message: "response was lost after the dimension changed",
              }));
            }),
        },
      }).pipe(Effect.flatMap(({ awaitCompletion }) => awaitCompletion)),
    ));

    expect(activationAttempts).toBe(1);
    expect(result.finalCheckpoint.planner.status)
      .toBe(BeatGameRunStatus.COMPLETED);
  });

  it("interrupts a long action when a run is paused", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      dimension: "minecraft:the_end",
      counts: {
        "minecraft:cooked_beef": 16,
        "minecraft:bow": 1,
        "minecraft:arrow": 32,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 99,
      entityType: "minecraft:ender_dragon",
      position: {
        x: 20,
        y: 80,
        z: 20,
        dimension: "minecraft:the_end",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    let interrupted = 0;
    driver.taskResolver = () =>
      Effect.never.pipe(
        Effect.onInterrupt(() =>
          Effect.sync(() => {
            interrupted += 1;
          })
        ),
      );
    const store = new InMemoryBeatGameCheckpointStore();
    await Effect.runPromise(store.save(checkpoint(
      BeatGamePhase.FIGHT_ENDER_DRAGON,
      {
        runId: "pause-run",
        teamId: "pause-team",
      },
    ), undefined));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "pause-run",
        team: { teamId: "pause-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.sleep(10).pipe(
            Effect.zipRight(run.pause),
            Effect.zipRight(Effect.sleep(20)),
            Effect.zipRight(run.stop),
            Effect.zipRight(run.awaitCompletion.pipe(Effect.either)),
          )
        ),
      ),
    ));

    expect(interrupted).toBeGreaterThan(0);
  });

  it("reattaches durable tasks with the restored action identity", async () => {
    const driver = new FakeBeatGameDriver();
    driver.currentObservation = observation({
      dimension: "minecraft:the_end",
      counts: {
        "minecraft:cooked_beef": 16,
        "minecraft:bow": 1,
        "minecraft:arrow": 32,
      },
    });
    driver.entityResults = [{
      connectionEpoch: "epoch-1",
      networkId: 99,
      entityType: "minecraft:ender_dragon",
      position: {
        x: 20,
        y: 80,
        z: 20,
        dimension: "minecraft:the_end",
      },
      velocity: { x: 0, y: 0, z: 0 },
      alive: true,
      observedAt: "2026-01-01T00:00:00.000Z",
    }];
    driver.taskResolver = () => Effect.never;
    const store = new InMemoryBeatGameCheckpointStore();
    const initial = checkpoint(BeatGamePhase.FIGHT_ENDER_DRAGON);
    await Effect.runPromise(store.save({
      ...initial,
      runId: "durable-resume-run",
      teamId: "durable-resume-team",
      planner: {
        ...initial.planner,
        currentAction: "fight-ender-dragon",
        currentActionId: "restored-action-id",
      },
    }, undefined));

    await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "durable-resume-run",
        team: { teamId: "durable-resume-team" },
        checkpointStore: store,
        strategy: { observationPollMs: 1 },
      }).pipe(
        Effect.flatMap((run) =>
          Effect.sleep(10).pipe(
            Effect.zipRight(run.stop),
            Effect.zipRight(run.awaitCompletion.pipe(Effect.either)),
          )
        ),
      ),
    ));

    expect(driver.taskExecutions[0]?.idempotencyKey).toMatch(
      /^beat-game:restored-action-id:[0-9a-f]{16}:1:[0-9a-f]{16}$/u,
    );
    expect(driver.taskExecutions[0]?.deadline).toBeInstanceOf(Date);
  });

  it("interrupts a blocked observation when the run is stopped", async () => {
    const driver = new FakeBeatGameDriver();
    let observations = 0;
    driver.observationResolver = () => {
      observations += 1;
      return observations === 1
        ? Effect.succeed(observation())
        : Effect.never;
    };

    const exit = await Effect.runPromise(Effect.scoped(
      beatGameWithDriver(driver, {
        runId: "stopped-run",
        team: { teamId: "stopped-team" },
      }).pipe(
        Effect.flatMap((run) =>
          run.stop.pipe(
            Effect.zipRight(run.awaitCompletion),
            Effect.either,
          )
        ),
      ),
    ));

    expect(Either.isLeft(exit)).toBe(true);
    if (Either.isLeft(exit)) {
      expect(exit.left).toBeInstanceOf(BeatGameCancelled);
      expect(exit.left._tag).toBe("BeatGameCancelled");
      if (exit.left._tag === "BeatGameCancelled") {
        expect(exit.left.reason).toBe("stopped");
      }
    }
  });
});
