feat(v0.4.1): make the Settlement Contract honest end-to-end
Patches each link of the closed-loop chain (world-truth -> invariant -> dispatch -> worldDelta -> milestone) so the contract can no longer advance on a lie or stall on an unreachable milestone, and surfaces the result on the monitor. - Unblock M6_lighting: add gather.coal producer (mirrors gather.stone, strict expectGain), register it, add the skill-graph node, and make curriculum.shelter.torch two-step (gather coal -> craft torch). craft.torch needed coal but no skill produced it, so the contract pinned on M6 forever and starved M7/M8/M9. One curriculum edit fixes both rails. - M8 no longer falsely satisfied: build-shelter records locations.shelter only on real progress (setLocation moved below the no_progress guard). - M2_bed made monotonic: sleepInBed writes locations.bed when the bot places its own bed, so M2 stays met after the carried bed item is consumed. - Observability: new ink-free tui/format.js helper renders per-tick state / firing rail / active skill / blocked prerequisite / stall reason in the monitor header (fields bot.js already computes but never showed). - Harden the valid-skill-id guardrail: skillRegistryPrompt preserves the "NEVER invent" footer when truncating (a growing registry was dropping it), and fix the stale "tech-tree > autonomous" reflex chain in the escalation prompt. Tests: 494/494 passing; new build-shelter / invariants / format suites plus skill-graph, curriculum, skill-registry cases. lint-patch clean. Deferred audit findings recorded in plans/v0.4.0-vnext.md (local). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -17,6 +17,7 @@ const toolPlugin = toolPkg.plugin ?? toolPkg.default?.plugin ?? toolPkg.default
|
||||
import { info, warn } from "./log.js";
|
||||
import { digEscapeTunnel } from "./skills/recovery-tunnel-out.js";
|
||||
import { findNearestBlockByName } from "./perception.js";
|
||||
import { setLocation } from "./locations.js";
|
||||
|
||||
// Hard timeout wrapper. Mineflayer goals (pathfinder, pvp targeting) can hang
|
||||
// when the goal is unreachable; without a ceiling the whole reflex chain stops.
|
||||
@@ -364,6 +365,17 @@ export async function sleepInBed(bot) {
|
||||
// have shifted to an adjacent slot for the bed's second half).
|
||||
const placed = findNearestBlockByName(bot, BED_NAMES, { maxDistance: 4 });
|
||||
if (!placed) return { ok: false, detail: "placed bed not found after placement" };
|
||||
// M2 monotonicity: the bot just placed its OWN bed and the carried
|
||||
// item is consumed, so bedSecured()'s carried-item branch no longer
|
||||
// holds. Record the placed bed's location (mirrors choose-base /
|
||||
// place-chest / build-shelter) so the locations.bed branch keeps M2_bed
|
||||
// met and the contract stops looping gather.wool->craft.bed for a bed
|
||||
// that already exists. Recorded before sleep — the bed is in the world
|
||||
// regardless of whether sleeping succeeds; guarded so a store-write
|
||||
// hiccup never breaks the sleep path.
|
||||
try {
|
||||
setLocation("bed", { x: placed.position.x, y: placed.position.y, z: placed.position.z, radius: 1, note: "placed bed" });
|
||||
} catch {}
|
||||
await withTimeout(bot.sleep(placed), 10_000, "bot.sleep(placed)");
|
||||
return { ok: true, detail: { bedAt: placed.position, placed: true, name: carried.name } };
|
||||
} catch (e) {
|
||||
|
||||
+1
-1
@@ -805,7 +805,7 @@ function maybeAutoEscalate() {
|
||||
`You are the escalation cortex for an autonomous Minecraft bot. The bot's`,
|
||||
`script-driven reflex loop has produced no useful action for ${ESCALATE_AFTER_NOOPS} consecutive ticks`,
|
||||
`(~${Math.round((ESCALATE_AFTER_NOOPS * config.tickIntervalMs) / 1000)}s). The reflex chain is:`,
|
||||
` defend > eat > sleep > tech-tree > autonomous > idle`,
|
||||
` modes(self_preservation/hunger/shelter) > defend > eat > sleep > curriculum > idle (curriculum dispatches the Settlement Contract's chosen skill)`,
|
||||
`Snapshot:`,
|
||||
"```json",
|
||||
promptCtx,
|
||||
|
||||
+10
-1
@@ -181,7 +181,16 @@ const MILESTONES = [
|
||||
id: "shelter.torch",
|
||||
title: "Have torches on hand for the perimeter",
|
||||
isDone: (inv) => has(inv, "torch", 4),
|
||||
suggest: () => ({ skillId: "craft.torch" }),
|
||||
// Two-step like wood.planks-and-sticks: torches need coal (or
|
||||
// charcoal), but nothing else produces it — without this the
|
||||
// milestone pinned forever on craft.torch's missing_material. Mine
|
||||
// coal first, then craft. The contract's M6_lighting delegates
|
||||
// suggest() to this milestone, so this edit fixes both rails.
|
||||
suggest: (inv) => {
|
||||
const fuel = (inv?.coal ?? 0) + (inv?.charcoal ?? 0);
|
||||
if (fuel < 1) return { skillId: "gather.coal" };
|
||||
return { skillId: "craft.torch" };
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "village.base-site",
|
||||
|
||||
@@ -141,6 +141,28 @@ test("food.basic satisfied by high food bar even without food item", () => {
|
||||
assert.equal(got.milestone.id, "storage.chest");
|
||||
});
|
||||
|
||||
test("shelter.torch suggests gather.coal when no coal on hand (closes the M6 dead-end)", () => {
|
||||
const inv = {
|
||||
wooden_axe: 1, wooden_pickaxe: 1, wooden_sword: 1,
|
||||
stone_axe: 1, stone_pickaxe: 1, stone_sword: 1, furnace: 1,
|
||||
red_bed: 1, bread: 2,
|
||||
};
|
||||
const got = nextMilestone(snap(inv, { food: 20, locations: { chest: { x: 1, y: 64, z: 0 } } }));
|
||||
assert.equal(got.milestone.id, "shelter.torch");
|
||||
assert.equal(got.plan.skillId, "gather.coal");
|
||||
});
|
||||
|
||||
test("shelter.torch suggests craft.torch once coal is on hand", () => {
|
||||
const inv = {
|
||||
wooden_axe: 1, wooden_pickaxe: 1, wooden_sword: 1,
|
||||
stone_axe: 1, stone_pickaxe: 1, stone_sword: 1, furnace: 1,
|
||||
red_bed: 1, bread: 2, coal: 1,
|
||||
};
|
||||
const got = nextMilestone(snap(inv, { food: 20, locations: { chest: { x: 1, y: 64, z: 0 } } }));
|
||||
assert.equal(got.milestone.id, "shelter.torch");
|
||||
assert.equal(got.plan.skillId, "craft.torch");
|
||||
});
|
||||
|
||||
test("all done → null", () => {
|
||||
const inv = {
|
||||
oak_log: 16, oak_planks: 8, stick: 8,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
// Invariant predicate library — these are the "milestone done" truths the
|
||||
// Settlement Contract relies on. Locking them guards against the closed-loop
|
||||
// regressions the v0.4.1 audit surfaced (e.g. M2_bed must be able to close via
|
||||
// a recorded bed LOCATION once actions.js writes locations.bed, not only via a
|
||||
// transient carried-bed item).
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
worldFromSnapshot,
|
||||
bedSecured,
|
||||
foodSecure,
|
||||
stoneTier,
|
||||
locationExists,
|
||||
hasItem,
|
||||
} from "./invariants.js";
|
||||
|
||||
const w = (snap) => worldFromSnapshot(snap);
|
||||
|
||||
test("bedSecured: met by a carried bed item", () => {
|
||||
assert.equal(bedSecured().met(w({ inventory: { red_bed: 1 } })), true);
|
||||
});
|
||||
|
||||
test("bedSecured: met by a recorded bed LOCATION (M2 monotonicity after the bed is placed)", () => {
|
||||
// The carried item is gone (consumed by placement) but the location was
|
||||
// recorded — M2 must stay satisfied so the contract doesn't loop
|
||||
// gather.wool→craft.bed for a bed that physically exists.
|
||||
assert.equal(bedSecured().met(w({ inventory: {}, locations: { bed: { x: 1, y: 64, z: 1 } } })), true);
|
||||
});
|
||||
|
||||
test("bedSecured: unmet with neither a bed item nor a bed location", () => {
|
||||
assert.equal(bedSecured().met(w({ inventory: {}, locations: {} })), false);
|
||||
});
|
||||
|
||||
test("foodSecure: cooked staple, well-fed, or hasFood — but not raw materials", () => {
|
||||
assert.equal(foodSecure().met(w({ inventory: { bread: 1 } })), true);
|
||||
assert.equal(foodSecure().met(w({ inventory: {}, food: 18 })), true);
|
||||
assert.equal(foodSecure().met(w({ inventory: {}, hasFood: true })), true);
|
||||
assert.equal(foodSecure().met(w({ inventory: { cobblestone: 40 }, food: 10 })), false);
|
||||
});
|
||||
|
||||
test("stoneTier: needs all three stone tools AND a furnace", () => {
|
||||
assert.equal(stoneTier().met(w({ inventory: { stone_axe: 1, stone_pickaxe: 1, stone_sword: 1 } })), false);
|
||||
assert.equal(stoneTier().met(w({ inventory: { stone_axe: 1, stone_pickaxe: 1, stone_sword: 1, furnace: 1 } })), true);
|
||||
});
|
||||
|
||||
test("locationExists: pure key-presence over locations (no item required)", () => {
|
||||
assert.equal(locationExists("shelter").met(w({ locations: { shelter: { x: 0, y: 64, z: 0 } } })), true);
|
||||
assert.equal(locationExists("shelter").met(w({ locations: {} })), false);
|
||||
});
|
||||
|
||||
test("hasItem('torch', 4): the M6 lighting threshold", () => {
|
||||
assert.equal(hasItem("torch", 4, "torch").met(w({ inventory: { torch: 3 } })), false);
|
||||
assert.equal(hasItem("torch", 4, "torch").met(w({ inventory: { torch: 4 } })), true);
|
||||
});
|
||||
@@ -31,6 +31,7 @@ export const SKILL_GRAPH = Object.freeze({
|
||||
"gather.logs": { requires: [], produces: ["logs"] },
|
||||
"gather.wool": { requires: [], produces: ["wool"] },
|
||||
"gather.stone": { requires: [{ tool: "pickaxe" }], produces: ["cobblestone"] },
|
||||
"gather.coal": { requires: [{ tool: "pickaxe" }], produces: ["coal"] },
|
||||
"craft.planks": { requires: [{ item: "logs", min: 1 }], produces: ["planks"] },
|
||||
"craft.sticks": { requires: [{ item: "planks", min: 2 }], produces: ["stick"] },
|
||||
"craft.wooden-axe": { requires: [{ item: "planks", min: 3 }, { item: "stick", min: 2 }], produces: ["wooden_axe"] },
|
||||
|
||||
@@ -41,6 +41,24 @@ test("unknown skill is treated as runnable (known:false)", () => {
|
||||
assert.equal(r.known, false);
|
||||
});
|
||||
|
||||
test("gather.coal needs a pickaxe and produces coal (closes the M6 dead-end)", () => {
|
||||
assert.equal(canRun("gather.coal", world({})), false);
|
||||
assert.equal(canRun("gather.coal", world({ wooden_pickaxe: 1 })), true);
|
||||
assert.equal(canRun("gather.coal", world({ stone_pickaxe: 1 })), true);
|
||||
});
|
||||
|
||||
test("craft.torch is blocked without coal but runnable once coal is gathered", () => {
|
||||
assert.equal(canRun("craft.torch", world({ stick: 1 })), false);
|
||||
assert.equal(canRun("craft.torch", world({ stick: 1, coal: 1 })), true);
|
||||
// charcoal counts as coal (semantic group)
|
||||
assert.equal(canRun("craft.torch", world({ stick: 1, charcoal: 1 })), true);
|
||||
});
|
||||
|
||||
test("runnableFrontier includes gather.coal once a pickaxe is held", () => {
|
||||
assert.ok(!runnableFrontier(world()).includes("gather.coal"));
|
||||
assert.ok(runnableFrontier(world({ wooden_pickaxe: 1 })).includes("gather.coal"));
|
||||
});
|
||||
|
||||
test("axe matcher excludes pickaxe", () => {
|
||||
assert.equal(_internal.TOOL.axe("wooden_axe"), true);
|
||||
assert.equal(_internal.TOOL.axe("wooden_pickaxe"), false);
|
||||
|
||||
@@ -45,9 +45,14 @@ export function describeSkill(id) {
|
||||
}
|
||||
|
||||
// Human-readable block to drop into LLM system prompts. Groups by
|
||||
// namespace, lists "id — title (timeoutMs)". Capped at ~2KB to stay
|
||||
// well within the model's instruction window.
|
||||
export function skillRegistryPrompt({ limit = 2000 } = {}) {
|
||||
// namespace, lists "id — title". Capped at ~2KB to stay well within the
|
||||
// model's instruction window. When the list overflows the cap we truncate
|
||||
// the LIST, never the footer — the footer carries the load-bearing
|
||||
// guardrail ("NEVER invent new ids"), the whole reason this prompt exists.
|
||||
// A naive tail-slice (the pre-v0.4.1 behaviour) would silently drop that
|
||||
// guardrail once the registry grew past the cap, re-opening the exact v0.2
|
||||
// skill-id hallucination this module was built to close.
|
||||
export function skillRegistryPrompt({ limit = 3000 } = {}) {
|
||||
const { byNamespace } = get();
|
||||
const namespaces = Array.from(byNamespace.keys()).sort();
|
||||
const lines = ["Valid skill ids (USE ONLY THESE for avoid_skill / prefer_skill):"];
|
||||
@@ -58,10 +63,13 @@ export function skillRegistryPrompt({ limit = 2000 } = {}) {
|
||||
lines.push(` - ${s.id} — ${s.title ?? s.id}`);
|
||||
}
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("If no listed skill fits, set the field to null. NEVER invent new ids.");
|
||||
const text = lines.join("\n");
|
||||
return text.length > limit ? text.slice(0, limit - 4) + "\n..." : text;
|
||||
const body = lines.join("\n");
|
||||
const footer = "If no listed skill fits, set the field to null. NEVER invent new ids.";
|
||||
const full = `${body}\n\n${footer}`;
|
||||
if (full.length <= limit) return full;
|
||||
const sep = "\n...\n\n";
|
||||
const room = Math.max(0, limit - footer.length - sep.length);
|
||||
return `${body.slice(0, room)}${sep}${footer}`;
|
||||
}
|
||||
|
||||
// For tests / hot-reload scenarios.
|
||||
|
||||
@@ -58,8 +58,18 @@ test("registryPrompt: contains the real ids grouped by namespace", () => {
|
||||
assert.doesNotMatch(txt, /survive\.shelter[^-]/);
|
||||
});
|
||||
|
||||
test("registryPrompt: respects limit parameter", () => {
|
||||
test("registryPrompt: respects limit and preserves the NEVER-invent guardrail when truncating", () => {
|
||||
const short = skillRegistryPrompt({ limit: 200 });
|
||||
assert.ok(short.length <= 200, `expected <=200, got ${short.length}`);
|
||||
assert.ok(short.endsWith("..."));
|
||||
// The skill LIST is truncated (…), but the guardrail footer must always
|
||||
// survive — otherwise a growing registry silently stops telling the LLM
|
||||
// not to hallucinate skill ids.
|
||||
assert.match(short, /\.\.\./, "list should be truncated");
|
||||
assert.match(short, /NEVER invent/, "guardrail footer must survive truncation");
|
||||
});
|
||||
|
||||
test("registryPrompt: default limit fits the full registry incl. the guardrail footer", () => {
|
||||
const full = skillRegistryPrompt();
|
||||
assert.match(full, /NEVER invent/);
|
||||
assert.doesNotMatch(full, /\n\.\.\.\n/, "default prompt should not be truncated");
|
||||
});
|
||||
|
||||
@@ -172,13 +172,22 @@ export const skill = Object.freeze({
|
||||
}
|
||||
}
|
||||
|
||||
// Closed-loop integrity: a build that placed nothing AND skipped
|
||||
// nothing never established a shelter. Do NOT record a shelter
|
||||
// location in that case — M8_shelter's invariant locationExists(
|
||||
// "shelter") is mere key-presence with no compensating clear, so a
|
||||
// single all-throw build would falsely satisfy the milestone forever.
|
||||
// We record the location only on real progress: placed>0, or skipped>0
|
||||
// (idempotent resume — the blueprint was already satisfied by existing
|
||||
// blocks).
|
||||
if (placed === 0 && skipped === 0) {
|
||||
return { ok: false, code: "no_progress", detail: "could not place any blocks", worldDelta: null };
|
||||
}
|
||||
|
||||
// Record the shelter location so future skills can find it even if
|
||||
// base gets re-scored.
|
||||
setLocation(SHELTER_NAME, { x: center.x, y: center.y, z: center.z, radius: 2, note: `auto-built; ${placed} blocks placed` });
|
||||
|
||||
if (placed === 0 && skipped === 0) {
|
||||
return { ok: false, code: "no_progress", detail: "could not place any blocks", worldDelta: null };
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
code: "done",
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// build-shelter closed-loop integrity: the shelter LOCATION (which satisfies
|
||||
// M8_shelter's locationExists("shelter") invariant) must be recorded ONLY when
|
||||
// the build actually made progress. A build that places nothing and skips
|
||||
// nothing must NOT mark M8 done. Runs against the isolated test state dir
|
||||
// (config.js detects --test), with a fake bot carrying a real minecraft-data
|
||||
// registry so applyProfile/Movements construct without a live server.
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import mcDataLoader from "minecraft-data";
|
||||
|
||||
import { skill } from "./build-shelter.js";
|
||||
import { setLocation, getLocation, removeLocation } from "../locations.js";
|
||||
|
||||
const registry = mcDataLoader("1.21.4");
|
||||
|
||||
function makePos(x, y, z) {
|
||||
return { x, y, z, clone: () => makePos(x, y, z), offset: (dx, dy, dz) => makePos(x + dx, y + dy, z + dz) };
|
||||
}
|
||||
|
||||
// blockKind: (target) => block-or-null describing what bot.blockAt returns at
|
||||
// every coordinate. We use it to make the whole world either air (no
|
||||
// placement possible) or solid (every placement succeeds).
|
||||
function makeBot(blockKind, planks = 30) {
|
||||
return {
|
||||
registry,
|
||||
world: {},
|
||||
entity: { position: makePos(0, 64, 0) },
|
||||
pathfinder: { setMovements() {} },
|
||||
inventory: { items: () => (planks > 0 ? [{ name: "oak_planks", count: planks }] : []) },
|
||||
blockAt(p) { return blockKind(p); },
|
||||
async equip() { return true; },
|
||||
async placeBlock() { return true; },
|
||||
};
|
||||
}
|
||||
|
||||
test("failed build (placed 0, skipped 0) does NOT record a shelter location", async () => {
|
||||
removeLocation("shelter");
|
||||
setLocation("base", { x: 0, y: 64, z: 0, note: "test base" });
|
||||
|
||||
// Air everywhere → every findReferenceForPlacement returns null → nothing
|
||||
// placed, nothing skipped.
|
||||
const bot = makeBot(() => ({ name: "air", boundingBox: "empty" }));
|
||||
const res = await skill.execute({ bot, owned: null });
|
||||
|
||||
assert.equal(res.ok, false);
|
||||
assert.equal(res.code, "no_progress");
|
||||
assert.equal(getLocation("shelter"), null, "shelter location must NOT be recorded on a no-progress build");
|
||||
|
||||
removeLocation("base");
|
||||
});
|
||||
|
||||
test("successful build records the shelter location", async () => {
|
||||
removeLocation("shelter");
|
||||
setLocation("base", { x: 0, y: 64, z: 0, note: "test base" });
|
||||
|
||||
// Solid everywhere → every target has a reference block to place against.
|
||||
const bot = makeBot((p) => ({ name: "stone", boundingBox: "block", position: makePos(p.x, p.y, p.z) }));
|
||||
const res = await skill.execute({ bot, owned: null });
|
||||
|
||||
assert.equal(res.ok, true);
|
||||
assert.equal(res.code, "done");
|
||||
assert.ok(res.detail.placed > 0, "expected at least one block placed");
|
||||
const shelter = getLocation("shelter");
|
||||
assert.ok(shelter && shelter.x === 0 && shelter.z === 0, "shelter location recorded on success");
|
||||
|
||||
removeLocation("shelter");
|
||||
removeLocation("base");
|
||||
});
|
||||
@@ -0,0 +1,169 @@
|
||||
// gather.coal — find a nearby coal ore block, equip a pickaxe (best
|
||||
// available), path to it and mine it. Modelled on gather.stone: stone-tier
|
||||
// mining needs at least a wooden pickaxe, the preconditions enforce that.
|
||||
//
|
||||
// Why this exists: craft.torch hard-requires coal (or charcoal), but no other
|
||||
// skill produces either, so M6_lighting was a permanent dead-end that pinned
|
||||
// the Settlement Contract forever and starved M7/M8/M9. gather.coal is the
|
||||
// missing producer. coal_ore drops coal directly and collectBlock awaits the
|
||||
// pickup, so the strict ledger check (expectGain) is safe here.
|
||||
|
||||
import pathfinderPkg from "mineflayer-pathfinder";
|
||||
const { pathfinder, Movements } = pathfinderPkg;
|
||||
import collectBlockPkg from "mineflayer-collectblock";
|
||||
const collectBlockPlugin =
|
||||
collectBlockPkg.plugin ??
|
||||
collectBlockPkg.default?.plugin ??
|
||||
collectBlockPkg.default ??
|
||||
collectBlockPkg;
|
||||
import toolPkg from "mineflayer-tool";
|
||||
const toolPlugin = toolPkg.plugin ?? toolPkg.default?.plugin ?? toolPkg.default ?? toolPkg;
|
||||
|
||||
import { pickaxes } from "./groups.js";
|
||||
import { info, warn } from "../log.js";
|
||||
import { findNearestBlockByName } from "../perception.js";
|
||||
|
||||
const COAL_ORE_NAMES = ["coal_ore", "deepslate_coal_ore"];
|
||||
|
||||
let pluginLoaded = new WeakSet();
|
||||
function ensurePathfinder(bot) {
|
||||
if (pluginLoaded.has(bot)) return;
|
||||
bot.loadPlugin(pathfinder);
|
||||
pluginLoaded.add(bot);
|
||||
}
|
||||
|
||||
let toolLoaded = new WeakSet();
|
||||
function ensureTool(bot) {
|
||||
if (toolLoaded.has(bot)) return;
|
||||
bot.loadPlugin(toolPlugin);
|
||||
toolLoaded.add(bot);
|
||||
}
|
||||
let collectBlockLoaded = new WeakSet();
|
||||
function ensureCollectBlock(bot) {
|
||||
ensurePathfinder(bot);
|
||||
ensureTool(bot);
|
||||
if (collectBlockLoaded.has(bot)) return;
|
||||
bot.loadPlugin(collectBlockPlugin);
|
||||
collectBlockLoaded.add(bot);
|
||||
}
|
||||
|
||||
function setMovementsForGather(bot) {
|
||||
const m = new Movements(bot);
|
||||
m.canDig = true;
|
||||
m.allow1by1towers = false;
|
||||
bot.pathfinder.setMovements(m);
|
||||
}
|
||||
|
||||
const PICKAXE_PRIORITY = ["netherite_pickaxe", "diamond_pickaxe", "iron_pickaxe", "stone_pickaxe", "wooden_pickaxe"];
|
||||
async function equipBestPickaxe(bot) {
|
||||
for (const name of PICKAXE_PRIORITY) {
|
||||
const item = bot.inventory.items().find((i) => i.name === name);
|
||||
if (item) {
|
||||
try {
|
||||
await bot.equip(item, "hand");
|
||||
return name;
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
const coalBlacklist = new WeakMap();
|
||||
const BLACKLIST_TTL_MS = 5 * 60_000;
|
||||
|
||||
function getBlacklist(bot) {
|
||||
let m = coalBlacklist.get(bot);
|
||||
if (!m) {
|
||||
m = new Map();
|
||||
coalBlacklist.set(bot, m);
|
||||
}
|
||||
const now = Date.now();
|
||||
for (const [k, exp] of m) if (exp < now) m.delete(k);
|
||||
return m;
|
||||
}
|
||||
|
||||
export const skill = Object.freeze({
|
||||
id: "gather.coal",
|
||||
title: "Gather coal",
|
||||
timeoutMs: 90_000,
|
||||
// Closed-loop strict check: the milestone needs coal in hand, so we assert
|
||||
// the world actually moved (coal/charcoal increased) and refuse to report
|
||||
// "ok" if the dig left the inventory unchanged (runSkill → world_unchanged).
|
||||
expectGain: { matcher: (k) => k === "coal" || k === "charcoal", min: 1, label: "coal" },
|
||||
preconditions(ctx) {
|
||||
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
|
||||
const available = pickaxes(ctx.bot);
|
||||
if (available.size === 0) {
|
||||
return { ok: false, code: "unsupported_version", detail: "no pickaxes in registry" };
|
||||
}
|
||||
const owned = ctx.bot.inventory.items().some((i) => available.has(i.name));
|
||||
if (!owned) {
|
||||
return { ok: false, code: "missing_tool", detail: "no pickaxe in inventory" };
|
||||
}
|
||||
return { ok: true };
|
||||
},
|
||||
async execute(ctx) {
|
||||
const bot = ctx.bot;
|
||||
const blacklist = getBlacklist(bot);
|
||||
// Numeric-id search — callback matcher returns 0 under ViaBackwards. See runtime/perception.js.
|
||||
const target = findNearestBlockByName(bot, COAL_ORE_NAMES, {
|
||||
maxDistance: 32,
|
||||
predicate: (b) => !blacklist.has(`${b.position.x},${b.position.y},${b.position.z}`),
|
||||
});
|
||||
if (!target) {
|
||||
return { ok: false, code: "no_target", detail: "no reachable coal ore within 32 blocks", worldDelta: null };
|
||||
}
|
||||
|
||||
ensureCollectBlock(bot);
|
||||
setMovementsForGather(bot);
|
||||
const pickaxe = await equipBestPickaxe(bot);
|
||||
info("action", `gather.coal: ${target.name} at ${target.position.x},${target.position.y},${target.position.z} (tool=${pickaxe ?? "fists"})`);
|
||||
const targetPos = target.position.clone();
|
||||
try {
|
||||
try {
|
||||
await withTimeout(bot.lookAt(targetPos.offset(0.5, 0.5, 0.5), true), 2_000, "lookAt(coal)");
|
||||
} catch {}
|
||||
await withTimeout(bot.collectBlock.collect(target), 60_000, "collectCoal");
|
||||
const after = bot.blockAt(targetPos);
|
||||
if (after && COAL_ORE_NAMES.includes(after.name)) {
|
||||
warn("action", `gather.coal reported ok but block still at ${targetPos.x},${targetPos.y},${targetPos.z} — silent dig failure`);
|
||||
const key = `${targetPos.x},${targetPos.y},${targetPos.z}`;
|
||||
blacklist.set(key, Date.now() + BLACKLIST_TTL_MS);
|
||||
return {
|
||||
ok: false,
|
||||
code: "silent_dig_failure",
|
||||
detail: "block still exists after collect — protocol/anti-cheat issue",
|
||||
worldDelta: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
code: "done",
|
||||
detail: { blockType: target.name, at: targetPos },
|
||||
worldDelta: { minedAt: targetPos, blockType: target.name },
|
||||
};
|
||||
} catch (e) {
|
||||
warn("action", `gather.coal failed: ${e.message}`);
|
||||
const key = `${target.position.x},${target.position.y},${target.position.z}`;
|
||||
blacklist.set(key, Date.now() + BLACKLIST_TTL_MS);
|
||||
const msg = String(e?.message ?? "");
|
||||
const code = msg.includes("timed out") ? "timeout" : "failed";
|
||||
return { ok: false, code, detail: e.message, worldDelta: null };
|
||||
}
|
||||
},
|
||||
validate(ctx, result) {
|
||||
return result.ok && !!result.worldDelta?.blockType;
|
||||
},
|
||||
recover(ctx, result) {
|
||||
if (result.code === "no_target") return { hint: "wander", reason: "no coal ore within 32 blocks" };
|
||||
return null;
|
||||
},
|
||||
});
|
||||
@@ -35,6 +35,7 @@ import { skill as escapePitSafe } from "./escape-pit-safe.js";
|
||||
import { skill as diagPhysics } from "./diagnose-physics.js";
|
||||
import { skill as diagScan, matchSkill as diagMatch } from "./diagnose-scan.js";
|
||||
import { skill as gatherStone } from "./gather-stone.js";
|
||||
import { skill as gatherCoal } from "./gather-coal.js";
|
||||
import { skill as gatherWool } from "./gather-wool.js";
|
||||
import { skill as acquireFood } from "./acquire-food.js";
|
||||
import { skill as scoutFood } from "./scout-food.js";
|
||||
@@ -84,6 +85,7 @@ register(diagPhysics);
|
||||
register(diagScan);
|
||||
register(diagMatch);
|
||||
register(gatherStone);
|
||||
register(gatherCoal);
|
||||
register(gatherWool);
|
||||
register(acquireFood);
|
||||
register(scoutFood);
|
||||
|
||||
Reference in New Issue
Block a user