Files
c910457817 v0.4.0 vNext — closed-loop world model + settlement contract (#29)
* feat(v0.4.0): vNext — closed-loop world model + settlement contract

Implements the vNext architecture from the research doc: demote the noisy
multi-rail planner in favour of a closed loop (world truth → invariant check)
plus a single utility-driven goal authority.

L1 services (fix no_drop / silent pathfinder hang first):
- InventoryLedger: diff-based "did I actually get it" verifier; acquire-food
  now confirms via ledger.gainedSince instead of the unreliable count/event.
- MotionService.gotoSafe: wall-clock timeout + progress watchdog +
  path_update(noPath/timeout) → structured {reached|stuck|timeout|nopath}.

L3 plan — unify the three competing rails (curriculum/manifesto/storyline):
- Settlement Contract: ordered M0–M9 milestones, each invariant-checked
  against an authoritative world view (early steps delegate to the proven
  curriculum; late game adds farming).
- InvariantChecker + predicate library; GoalManager selects the lowest unmet
  milestone via utility argmax (food-urgency preempts, DEPS-style).
- Wired into the scheduler: bot.js precomputes snapshot.contract; reflex.js
  consumes it in place of the storyline rail. Manifesto L0 still preempts.

Eval + robustness:
- Village Score (single 0..1 metric) on the snapshot + TUI "build" line.
- survive.dig-in skill + dusk_dig_in mode (exposed at night, no bed → cover).
- approach_block helper (GoalNear + lookAt, avoids GoalLookAtBlock #341).

+28 new tests (450 total green). LLM remains entirely off the tick path.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(v0.4.0): finish vNext plan — anti-loop, skill-graph, worldDelta diff, flee→motion

Completes the remaining v0.4.0 plan items and one fix motivated by a live
in-game observation (flee hanging 30s against a persistent zombie).

- flee → MotionService.gotoSafe: structured {stuck|timeout|nopath} in ~4s with
  a blind-retreat fallback, instead of the observed 30s pathfinder hang + 3
  watchdog replans. Movements setup guarded so it is unit-testable.
- QW5 anti-loop (runtime/anti-loop.js): same skill failing >=3x in 5min →
  30min blacklist (reflex shouldSkip) + one-shot improvement_request
  (bot.js drainFired -> writeProposal).
- 4.1 closed-loop worldDelta: runSkill snapshots inventory before execute and
  attaches the real delta (_invObserved) to every successful result; opt-in
  skill.expectGain asserts the claimed gain or returns world_unchanged.
- 3.6 skill-graph (Plan4MC): declarative requires/produces for ~20 skills;
  prerequisitesMet/canRun/runnableFrontier; GoalManager annotates suggestions
  with blockedBy when prereqs are unmet.

+22 tests (472 total green). Live smoke confirmed dig-in works and no new
errors; flee loop is what this commit's flee migration addresses.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Yuriy Mayatnikov <mayatnikov@me.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-28 11:29:39 +03:00

234 lines
8.1 KiB
JavaScript

// survive.acquire-food — turn "hungry and no edible item" into a concrete
// world action. The first implementation is intentionally conservative:
// pick up nearby drops if they are already visible, otherwise hunt a nearby
// passive animal. It does not harvest player-looking crops.
import pathfinderPkg from "mineflayer-pathfinder";
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"]);
let pluginLoaded = new WeakSet();
function ensurePathfinder(bot) {
if (pluginLoaded.has(bot)) return;
bot.loadPlugin(pathfinder);
pluginLoaded.add(bot);
}
function setMovementsForTravel(bot) {
const m = new Movements(bot);
m.canDig = true;
m.allow1by1towers = false;
bot.pathfinder.setMovements(m);
}
function withTimeout(promise, ms, label) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms / 1000}s`)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
function foodCount(bot) {
const allowed = foods(bot);
return bot.inventory.items().reduce((sum, item) => allowed.has(item.name) ? sum + item.count : sum, 0);
}
// Success here is "did edible food actually enter the inventory". Trusting the
// `playerCollect` event or `nearestEntity` going away is what produced the live
// `no_drop` false-failures (research §A.4). When the InventoryLedger is wired
// (ctx.ledger) we verify by diff against a baseline; otherwise we fall back to
// a local before/after count so the skill still works in unit tests.
function makeFoodTracker(ctx, bot) {
const isFood = (name) => foods(bot).has(name);
if (ctx?.ledger) {
ctx.ledger.update(bot);
const base = ctx.ledger.mark();
return {
mode: "ledger",
gained() {
ctx.ledger.update(bot);
return ctx.ledger.gainedSince(base, isFood);
},
};
}
const before = foodCount(bot);
return { mode: "count", gained: () => foodCount(bot) - before };
}
function nearestPassiveFoodMob(bot, maxDistance = 32) {
const here = bot?.entity?.position;
if (!here) return null;
let best = null;
for (const e of Object.values(bot.entities ?? {})) {
if (!e?.position || !PASSIVE_FOOD_MOBS.has(e.name)) continue;
const d = e.position.distanceTo(here);
if (d > maxDistance) continue;
if (!best || d < best.distance) best = { entity: e, distance: d };
}
return best;
}
function nearbyDroppedItems(bot, maxDistance = 8) {
const here = bot?.entity?.position;
if (!here) return [];
return Object.values(bot.entities ?? {})
.filter((e) => e?.position && (e.type === "object" || e.name === "item"))
.map((e) => ({ entity: e, distance: e.position.distanceTo(here) }))
.filter((e) => e.distance <= maxDistance)
.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);
let picked = 0;
for (const { entity } of nearbyDroppedItems(bot, 8).slice(0, 6)) {
try {
await withTimeout(
bot.pathfinder.goto(new goals.GoalNear(entity.position.x, entity.position.y, entity.position.z, 1)),
8_000,
"gotoDrop",
);
picked++;
} catch {}
}
if (picked > 0) await new Promise((r) => setTimeout(r, 600));
return picked;
}
export const skill = Object.freeze({
id: "survive.acquire-food",
title: "Acquire a basic food item",
timeoutMs: 75_000,
preconditions(ctx) {
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
if (foodCount(ctx.bot) > 0) return { ok: false, code: "already_have", detail: "already carrying edible food" };
if (nearestPassiveFoodMob(ctx.bot) || nearbyDroppedItems(ctx.bot, 8).length > 0) return { ok: true };
return { ok: false, code: "no_target", detail: "no nearby food drops or passive food mobs" };
},
async execute(ctx) {
const bot = ctx.bot;
const track = makeFoodTracker(ctx, bot);
const picked = await pickupNearbyDrops(bot);
const dropGain = track.gained();
if (dropGain > 0) {
return {
ok: true,
code: "done",
detail: { source: "drop", picked, verify: track.mode },
worldDelta: { acquiredFood: dropGain, source: "drop" },
};
}
const target = nearestPassiveFoodMob(bot);
if (!target) return { ok: false, code: "no_target", detail: "no passive food mob visible", worldDelta: null };
ensurePathfinder(bot);
setMovementsForTravel(bot);
try {
await withTimeout(
bot.pathfinder.goto(new goals.GoalFollow(target.entity, 2)),
30_000,
"pathToFoodMob",
);
} catch (e) {
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)`);
try {
for (let i = 0; i < 8; i++) {
const current = Object.values(bot.entities ?? {}).find((e) => e.id === target.entity.id);
if (!current) break;
if (current.position.distanceTo(bot.entity.position) > 4) {
try {
await withTimeout(
bot.pathfinder.goto(new goals.GoalFollow(current, 2)),
8_000,
"repathFoodMob",
);
} catch {}
}
bot.attack(current);
await new Promise((r) => setTimeout(r, 700));
}
await new Promise((r) => setTimeout(r, 1_000));
await pickupNearbyDrops(bot);
const huntGain = track.gained();
if (huntGain <= 0) {
return { ok: false, code: "no_drop", detail: `hunted ${target.entity.name} but found no edible drop`, worldDelta: null };
}
return {
ok: true,
code: "done",
detail: { source: "hunt", mob: target.entity.name, gained: huntGain, verify: track.mode },
worldDelta: { acquiredFood: huntGain, source: "hunt", mob: target.entity.name },
};
} catch (e) {
warn("action", `survive.acquire-food failed: ${e.message}`);
return { ok: false, code: "failed", detail: e.message, worldDelta: null };
}
},
recover(ctx, result) {
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, yawToward, horizontalDistance };