fix(v0.3.1): mechanical food/stuck fixes — bot reaches the chicken now

The wedge wasn't only in the manifesto layer; several mechanical bugs
kept the bot in a dead random-walk:

- storyline / manifesto / curriculum: "local food" now means an edible
  passive mob within <=32 blocks. A distant chicken or a cod no longer
  fools the bot into dispatching acquire-food (which then fails on
  no_path). Long-range food goes through scout-food instead.

- scout-food: partial approach to a target now counts as progress
  (approached_target, e.g. moved:14); a blocked heading is NOT counted
  as movement; added blind/tunnel fallback so it doesn't die when the
  pathfinder can't route cleanly.

- acquire-food: on no_path it now also tries a blind/tunnel approach to
  the animal; no_drop routes back into food scouting instead of giving
  up.

- explore.far / relocate / flee: fewer false "done" results (micro-steps
  no longer counted as success), more genuine escapes from stuck.

- scripts/show-story.js: live IPC now actually renders the current
  storyline step.

Verification: scripts/lint-patch.js clean; npm test 404/404 green; bot
relaunched in tmux `pepa`. Live logs show real progress — bot switched
to survive.scout-food, approached the chicken (approached_target
moved:14), then reached survive.acquire-food: hunting chicken. Food
isn't fully closed yet but the remaining issue is concrete pickup/drop,
not dead random-walk.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-28 09:20:07 +03:00
co-authored by Claude Opus 4.7
parent b68d4b3ee7
commit 1cf60f81e9
19 changed files with 548 additions and 106 deletions
+51 -4
View File
@@ -8,6 +8,7 @@ const { pathfinder, goals, Movements } = pathfinderPkg;
import { info, warn } from "../log.js";
import { foods } from "./groups.js";
import { blindWalkOrTunnelOut } from "./explore-far.js";
const PASSIVE_FOOD_MOBS = new Set(["cow", "pig", "chicken", "sheep", "rabbit", "mooshroom"]);
@@ -61,6 +62,41 @@ function nearbyDroppedItems(bot, maxDistance = 8) {
.sort((a, b) => a.distance - b.distance);
}
function horizontalDistance(a, b) {
return Math.hypot((b?.x ?? 0) - (a?.x ?? 0), (b?.z ?? 0) - (a?.z ?? 0));
}
function yawToward(from, to) {
if (!from || !to) return null;
const dx = to.x - from.x;
const dz = to.z - from.z;
if (Math.hypot(dx, dz) < 0.5) return null;
return -Math.atan2(dx, dz);
}
async function fallbackApproachFoodMob(bot, target, err) {
try { bot.pathfinder?.stop?.(); } catch {}
const start = bot.entity.position.clone?.() ?? { ...bot.entity.position };
const alreadyMoved = horizontalDistance(start, bot.entity.position);
if (alreadyMoved >= 4) {
return { ok: true, moved: alreadyMoved, mode: "pathfinder_partial", error: err?.message ?? "path failed" };
}
const yaw = yawToward(bot.entity.position, target.entity.position);
if (yaw === null) return { ok: false, moved: 0, error: err?.message ?? "path failed" };
const blind = await blindWalkOrTunnelOut(bot, {
yaw,
dirName: `toward-${target.entity.name}`,
blindMs: 8_000,
minMove: 4,
reason: `acquire-food target ${target.entity.name}`,
});
const moved = horizontalDistance(start, bot.entity.position);
if (blind.ok || moved >= 4) {
return { ok: true, moved, mode: "blind_target", error: err?.message ?? "path failed" };
}
return { ok: false, moved, error: err?.message ?? "path failed" };
}
async function pickupNearbyDrops(bot) {
ensurePathfinder(bot);
setMovementsForTravel(bot);
@@ -115,7 +151,18 @@ export const skill = Object.freeze({
"pathToFoodMob",
);
} catch (e) {
return { ok: false, code: "no_path", detail: e.message, worldDelta: null };
const approached = await fallbackApproachFoodMob(bot, target, e);
const current = Object.values(bot.entities ?? {}).find((entity) => entity.id === target.entity.id);
const dist = current?.position?.distanceTo(bot.entity.position) ?? Infinity;
if (!approached.ok) return { ok: false, code: "no_path", detail: e.message, worldDelta: null };
if (dist > 4) {
return {
ok: false,
code: "approached_target",
detail: { target: target.entity.name, moved: Math.round(approached.moved), mode: approached.mode, error: approached.error },
worldDelta: { moved: Math.round(approached.moved), target: target.entity.name, mode: approached.mode },
};
}
}
info("action", `survive.acquire-food: hunting ${target.entity.name} (${target.distance.toFixed(1)}m)`);
@@ -153,11 +200,11 @@ export const skill = Object.freeze({
}
},
recover(ctx, result) {
if (result.code === "no_target" || result.code === "no_path") {
return { hint: "wander", reason: "need to search for passive food mobs" };
if (result.code === "no_target" || result.code === "no_path" || result.code === "approached_target" || result.code === "no_drop") {
return { hint: "scout-food", reason: "need a long-range food search, not local acquire-food retry" };
}
return null;
},
});
export const _internal = { foodCount, nearestPassiveFoodMob };
export const _internal = { foodCount, nearestPassiveFoodMob, yawToward, horizontalDistance };
+34
View File
@@ -8,6 +8,7 @@ import { test } from "node:test";
import assert from "node:assert/strict";
import { runSkill, RUNNER_CODES, _registerForTest } from "./index.js";
import { __testing as scoutFoodTesting } from "./scout-food.js";
const ctx = {}; // skills under test ignore ctx fully
@@ -37,6 +38,27 @@ test("preconditions gate execution", async () => {
}
});
test("precondition failures can return recovery hints", async () => {
const teardown = _registerForTest({
id: "test.precondition-recover",
title: "blocked with recovery",
timeoutMs: 1000,
preconditions: () => ({ ok: false, code: "no_target", detail: "none nearby" }),
execute: async () => {
throw new Error("should not run");
},
recover: (_ctx, result) => ({ hint: "scout-food", saw: result.code }),
});
try {
const res = await runSkill("test.precondition-recover", ctx);
assert.equal(res.ok, false);
assert.equal(res.code, "no_target");
assert.deepEqual(res.recovery, { hint: "scout-food", saw: "no_target" });
} finally {
teardown();
}
});
test("gather.logs precondition refuses nearby hostiles", async () => {
const bot = { registry: { blocksByName: { oak_log: { id: 1 } } } };
const res = await runSkill("gather.logs", {
@@ -48,6 +70,18 @@ test("gather.logs precondition refuses nearby hostiles", async () => {
assert.match(res.detail, /unsafe to gather logs: drowned 6\.1 blocks away/);
});
test("scout-food progress counts intended cardinal, not sideways tunnel drift", () => {
const north = scoutFoodTesting.CARDINALS.find((c) => c.name === "N");
assert.deepEqual(
scoutFoodTesting.cardinalProgress({ x: 0, z: 0 }, { x: 0, z: -9 }, north),
{ along: 9, total: 9, driftName: "N" },
);
assert.deepEqual(
scoutFoodTesting.cardinalProgress({ x: 0, z: 0 }, { x: 9, z: 0 }, north),
{ along: 0, total: 9, driftName: "E" },
);
});
test("preconditions that throw produce precondition_failed", async () => {
const teardown = _registerForTest({
id: "test.precondition-throw",
+3 -12
View File
@@ -90,16 +90,6 @@ export const skill = Object.freeze({
}
info("action", `explore.far: cardinal probe trials=${trials.map((t) => `${t.name}:${t.dist.toFixed(1)}`).join(" ")} best=${best.name}`);
const probeMoved = horizontalDistance(beforeProbe, bot.entity.position);
if (probeMoved >= 2) {
return {
ok: true,
code: "done",
detail: { mode: "probe-moved", dir: best.name, moved: probeMoved },
worldDelta: { movedTo: clonePos(bot.entity.position) },
};
}
if (best.dist < 0.5) {
// All cardinals blocked. Try the cheap vertical escape first; if it
// does not actually move us, carve a short horizontal tunnel. The
@@ -122,7 +112,8 @@ export const skill = Object.freeze({
return blindWalkOrTunnelOut(bot, {
yaw: best.yaw,
dirName: best.name,
blindMs: args.blindMs ?? 7_000,
blindMs: args.blindMs ?? 20_000,
minMove: args.minMove ?? Math.min(14, Math.max(8, dist * 0.25)),
tunnelPushMs: args.tunnelPushMs,
reason: `explore.far blind ${best.name}`,
intended: { x: tx, y: ty, z: tz },
@@ -130,7 +121,7 @@ export const skill = Object.freeze({
},
});
async function blindWalkOrTunnelOut(bot, { yaw, dirName, blindMs = 7_000, minMove = 0.75, tunnelPushMs, reason = "blind fallback", intended = null } = {}) {
export async function blindWalkOrTunnelOut(bot, { yaw, dirName, blindMs = 7_000, minMove = 0.75, tunnelPushMs, reason = "blind fallback", intended = null } = {}) {
const before = clonePos(bot.entity.position);
try { await bot.look(yaw, 0, true); } catch {}
bot.setControlState("forward", true);
+9 -1
View File
@@ -204,12 +204,20 @@ export async function runSkill(id, ctx, args = {}) {
};
}
if (!pre.ok) {
return {
const result = {
ok: false,
code: pre.code ?? RUNNER_CODES.PRECONDITION_FAILED,
detail: pre.detail ?? "preconditions failed",
worldDelta: null,
};
if (typeof skill.recover === "function") {
try {
result.recovery = skill.recover(ctx, result) ?? null;
} catch (e) {
warn("skill", `${id}.recover threw: ${e.message}`);
}
}
return result;
}
const timeoutMs = skill.timeoutMs ?? 30_000;
+15 -8
View File
@@ -18,12 +18,13 @@ const { pathfinder, goals, Movements } = pathfinderPkg;
import { info } from "../log.js";
import { markRelocationStarted } from "../awareness/wedge-detector.js";
import { blindWalkOrTunnelOut } from "./explore-far.js";
const CARDINALS = [
{ name: "N", dx: 0, dz: -1 },
{ name: "E", dx: 1, dz: 0 },
{ name: "S", dx: 0, dz: 1 },
{ name: "W", dx: -1, dz: 0 },
{ name: "N", dx: 0, dz: -1, yaw: Math.PI },
{ name: "E", dx: 1, dz: 0, yaw: -Math.PI / 2 },
{ name: "S", dx: 0, dz: 1, yaw: 0 },
{ name: "W", dx: -1, dz: 0, yaw: Math.PI / 2 },
];
const DEFAULT_DISTANCE = 300;
const STEP_BLOCKS = 32; // re-path every N blocks for liveness
@@ -37,7 +38,7 @@ function ensurePathfinder(bot) {
}
function setMovementsForTravel(bot) {
const m = new Movements(bot);
m.canDig = false;
m.canDig = true;
m.allow1by1towers = false;
bot.pathfinder.setMovements(m);
}
@@ -100,9 +101,15 @@ export const skill = Object.freeze({
]);
} catch (e) {
errors.push(e?.message ?? String(e));
if (errors.length >= 3) break;
// brief pause then keep trying
await new Promise((r) => setTimeout(r, 500));
info("action", `relocate: path step failed (${e?.message ?? e}); blind fallback ${cardinal.name}`);
const blind = await blindWalkOrTunnelOut(bot, {
yaw: cardinal.yaw,
dirName: cardinal.name,
blindMs: 12_000,
minMove: 8,
reason: `relocate ${cardinal.name}`,
});
if (!blind.ok && errors.length >= 3) break;
}
// Measure actual progress (pathfinder might have routed around)
const dx = bot.entity.position.x - start.x;
+155 -23
View File
@@ -37,15 +37,17 @@ const { pathfinder, goals, Movements } = pathfinderPkg;
import { info, warn } from "../log.js";
import { foods } from "./groups.js";
import { affordancesFor, hasPassiveMobs, isBarren } from "../biome-affordances.js";
import { blindWalkOrTunnelOut } from "./explore-far.js";
const PASSIVE_FOOD_MOBS = new Set(["cow", "pig", "chicken", "sheep", "rabbit", "mooshroom"]);
const CARDINALS = [
{ name: "N", dx: 0, dz: -1 },
{ name: "E", dx: 1, dz: 0 },
{ name: "S", dx: 0, dz: 1 },
{ name: "W", dx: -1, dz: 0 },
{ name: "N", dx: 0, dz: -1, yaw: Math.PI },
{ name: "E", dx: 1, dz: 0, yaw: -Math.PI / 2 },
{ name: "S", dx: 0, dz: 1, yaw: 0 },
{ name: "W", dx: -1, dz: 0, yaw: Math.PI / 2 },
];
const PATROL_TICK_DISTANCE = 16;
const PATROL_STEP_TIMEOUT_MS = 12_000;
const DEFAULT_COMMIT_DISTANCE = 200;
let pluginLoaded = new WeakSet();
@@ -57,7 +59,7 @@ function ensurePathfinder(bot) {
function setMovementsForTravel(bot) {
const m = new Movements(bot);
m.canDig = false;
m.canDig = true;
m.allow1by1towers = false;
bot.pathfinder.setMovements(m);
}
@@ -122,6 +124,27 @@ function scanForFoodCapableNeighbourBiome(bot, radius = 64) {
return null;
}
function scoutState(ctx, bot) {
const here = bot?.entity?.position;
const now = Date.now();
const prev = ctx.scoutFoodState;
const expired = !prev || now - (prev.ts ?? 0) > 10 * 60_000;
const displaced = prev?.origin && here
? Math.hypot(here.x - prev.origin.x, here.z - prev.origin.z) > 128
: false;
if (expired || displaced) {
ctx.scoutFoodState = {
ts: now,
origin: here ? { x: here.x, z: here.z } : null,
tried: new Set(),
};
return ctx.scoutFoodState;
}
prev.ts = now;
if (!(prev.tried instanceof Set)) prev.tried = new Set(prev.tried ?? []);
return prev;
}
async function patrolCardinal(bot, cardinal, distance, ctx) {
ensurePathfinder(bot);
setMovementsForTravel(bot);
@@ -135,12 +158,39 @@ async function patrolCardinal(bot, cardinal, distance, ctx) {
try {
await Promise.race([
bot.pathfinder.goto(goal),
new Promise((_, rej) => setTimeout(() => rej(new Error("patrol step timeout")), 30_000)),
new Promise((_, rej) => setTimeout(() => rej(new Error("patrol step timeout")), PATROL_STEP_TIMEOUT_MS)),
]);
} catch (e) {
return { aborted: false, travelled, error: e?.message ?? String(e) };
info("action", `scout-food: path step failed (${e?.message ?? e}); blind fallback ${cardinal.name}`);
try { bot.pathfinder?.stop?.(); } catch {}
const blind = await blindWalkOrTunnelOut(bot, {
yaw: cardinal.yaw ?? -Math.atan2(cardinal.dx, cardinal.dz),
dirName: cardinal.name,
blindMs: 12_000,
minMove: 6,
reason: `scout-food ${cardinal.name}`,
});
const progress = cardinalProgress(start, bot.entity.position, cardinal);
travelled = progress.along;
const target = nearestPassiveFoodMob(bot, 32);
if (target) return { aborted: false, travelled, target };
if (progress.total >= 4 && progress.along < 4) {
info("action", `scout-food: ${cardinal.name} blocked; drifted ${progress.driftName ?? "sideways"} ${progress.total.toFixed(1)}b`);
return {
aborted: false,
travelled,
blocked: true,
drifted: progress.driftName,
error: `blocked_${cardinal.name}`,
};
}
if (!blind.ok && progress.total < 4) {
return { aborted: false, travelled, error: e?.message ?? String(e) };
}
continue;
}
travelled += PATROL_TICK_DISTANCE;
const progress = cardinalProgress(start, bot.entity.position, cardinal);
travelled = Math.max(travelled + PATROL_TICK_DISTANCE, progress.along);
// Rescan after every step.
const target = nearestPassiveFoodMob(bot, 32);
if (target) return { aborted: false, travelled, target };
@@ -148,6 +198,20 @@ async function patrolCardinal(bot, cardinal, distance, ctx) {
return { aborted: false, travelled };
}
function cardinalProgress(start, pos, cardinal) {
const dx = (pos?.x ?? 0) - (start?.x ?? 0);
const dz = (pos?.z ?? 0) - (start?.z ?? 0);
const along = Math.max(0, dx * cardinal.dx + dz * cardinal.dz);
const total = Math.hypot(dx, dz);
return { along, total, driftName: dominantCardinal(dx, dz, cardinal.name) };
}
function dominantCardinal(dx, dz, fallback = null) {
if (Math.abs(dx) < 0.5 && Math.abs(dz) < 0.5) return fallback;
if (Math.abs(dx) >= Math.abs(dz)) return dx >= 0 ? "E" : "W";
return dz >= 0 ? "S" : "N";
}
export const skill = Object.freeze({
id: "survive.scout-food",
title: "Scout for food at long range (biome-aware)",
@@ -162,7 +226,8 @@ export const skill = Object.freeze({
async execute(ctx, args = {}) {
const bot = ctx.bot;
const before = foodCount(bot);
const triedCardinals = new Set(args?._triedCardinals ?? []);
const state = scoutState(ctx, bot);
const triedCardinals = new Set([...(args?._triedCardinals ?? []), ...(state.tried ?? [])]);
// Step 0: biome check. If barren, head toward a food-capable neighbour.
const biome = currentBiomeName(bot);
@@ -174,14 +239,23 @@ export const skill = Object.freeze({
if (next) {
info("action", `scout-food: leaving barren biome ${biome}${next.biome} via ${next.heading.name}`);
const result = await patrolCardinal(bot, next.heading, DEFAULT_COMMIT_DISTANCE, ctx);
if (result.aborted) return { ok: false, code: "preempted", worldDelta: null };
if (result.target) {
return await tryHunt(bot, result.target, before);
}
return {
ok: false,
code: "no_target",
detail: `walked ${Math.round(result.travelled)}b ${next.heading.name} toward ${next.biome}, still no food`,
if (result.aborted) return { ok: false, code: "preempted", worldDelta: null };
if (result.target) {
return await tryHunt(bot, result.target, before);
}
if (result.blocked) {
state.tried.add(next.heading.name);
return {
ok: false,
code: "blocked_heading",
detail: `blocked ${next.heading.name}, drifted ${result.drifted ?? "sideways"}`,
worldDelta: { moved: Math.round(result.travelled), heading: next.heading.name, drifted: result.drifted ?? null },
};
}
return {
ok: false,
code: "no_target",
detail: `walked ${Math.round(result.travelled)}b ${next.heading.name} toward ${next.biome}, still no food`,
worldDelta: { moved: Math.round(result.travelled), heading: next.heading.name, from_biome: biome, to_biome: next.biome },
};
}
@@ -208,14 +282,23 @@ export const skill = Object.freeze({
};
}
const cardinal = untried[0];
state.tried.add(cardinal.name);
info("action", `scout-food: commit cardinal ${cardinal.name} for ${DEFAULT_COMMIT_DISTANCE}b`);
const result = await patrolCardinal(bot, cardinal, DEFAULT_COMMIT_DISTANCE, ctx);
if (result.aborted) return { ok: false, code: "preempted", worldDelta: null };
if (result.target) return await tryHunt(bot, result.target, before);
const result = await patrolCardinal(bot, cardinal, DEFAULT_COMMIT_DISTANCE, ctx);
if (result.aborted) return { ok: false, code: "preempted", worldDelta: null };
if (result.target) return await tryHunt(bot, result.target, before);
if (result.blocked) {
return {
ok: false,
code: "no_target",
detail: { tried: cardinal.name, travelled: Math.round(result.travelled), error: result.error ?? null },
code: "blocked_heading",
detail: { tried: cardinal.name, travelled: Math.round(result.travelled), drifted: result.drifted ?? null, error: result.error ?? null },
worldDelta: { moved: Math.round(result.travelled), heading: cardinal.name, drifted: result.drifted ?? null, from_biome: biome },
};
}
return {
ok: false,
code: "no_target",
detail: { tried: cardinal.name, travelled: Math.round(result.travelled), error: result.error ?? null },
worldDelta: { moved: Math.round(result.travelled), heading: cardinal.name, from_biome: biome },
};
},
@@ -223,6 +306,12 @@ export const skill = Object.freeze({
if (result.code === "exhausted") {
return { hint: "relocate", reason: "scout-food exhausted all 4 cardinals; needs a long jump" };
}
if (result.code === "blocked_heading") {
return { hint: "scout-food", reason: "chosen scout heading is blocked; retry another cardinal" };
}
if (result.code === "approached_target" || result.code === "no_path") {
return { hint: "scout-food", reason: "made or attempted progress toward food target; rescan from current position" };
}
if (result.code === "no_target") {
return { hint: "wander", reason: "scout completed leg without finding mob; try another cardinal" };
}
@@ -233,12 +322,42 @@ export const skill = Object.freeze({
async function tryHunt(bot, target, before) {
ensurePathfinder(bot);
setMovementsForTravel(bot);
const start = bot.entity.position.clone?.() ?? { ...bot.entity.position };
try {
await Promise.race([
bot.pathfinder.goto(new goals.GoalFollow(target.entity, 2)),
new Promise((_, rej) => setTimeout(() => rej(new Error("path-to-mob timeout")), 30_000)),
]);
} catch (e) {
try { bot.pathfinder?.stop?.(); } catch {}
const moved = horizontalDistance(start, bot.entity.position);
if (moved >= 6) {
return {
ok: false,
code: "approached_target",
detail: { target: target.entity.name, moved: Math.round(moved), mode: "pathfinder_partial", error: e?.message ?? "path failed" },
worldDelta: { moved: Math.round(moved), target: target.entity.name, mode: "pathfinder_partial" },
};
}
const yaw = yawToward(bot.entity.position, target.entity.position);
if (yaw !== null) {
const blind = await blindWalkOrTunnelOut(bot, {
yaw,
dirName: `toward-${target.entity.name}`,
blindMs: 8_000,
minMove: 4,
reason: `scout-food target ${target.entity.name}`,
});
const afterBlind = horizontalDistance(start, bot.entity.position);
if (blind.ok || afterBlind >= 4) {
return {
ok: false,
code: "approached_target",
detail: { target: target.entity.name, moved: Math.round(afterBlind), mode: "blind_target", error: e?.message ?? "path failed" },
worldDelta: { moved: Math.round(afterBlind), target: target.entity.name, mode: "blind_target" },
};
}
}
return { ok: false, code: "no_path", detail: e?.message ?? "path failed", worldDelta: null };
}
info("action", `scout-food: engaging ${target.entity.name}@${target.distance.toFixed(1)}b`);
@@ -269,8 +388,21 @@ async function tryHunt(bot, target, before) {
};
}
function horizontalDistance(a, b) {
return Math.hypot((b?.x ?? 0) - (a?.x ?? 0), (b?.z ?? 0) - (a?.z ?? 0));
}
function yawToward(from, to) {
if (!from || !to) return null;
const dx = to.x - from.x;
const dz = to.z - from.z;
if (Math.hypot(dx, dz) < 0.5) return null;
return -Math.atan2(dx, dz);
}
// Test exports
export const __testing = {
CARDINALS, PATROL_TICK_DISTANCE, DEFAULT_COMMIT_DISTANCE,
CARDINALS, PATROL_TICK_DISTANCE, DEFAULT_COMMIT_DISTANCE, PATROL_STEP_TIMEOUT_MS,
nearestPassiveFoodMob, currentBiomeName, scanForFoodCapableNeighbourBiome,
cardinalProgress, dominantCardinal, horizontalDistance, yawToward,
};