Files
mayatnikovandClaude Opus 4.7 29542f0559 fix(runtime): unstick scheduler + chop + sleep + bed/shelter/farm skills
Recovers the bot from the live-server symptoms reported 2026-05-26:
1) constant supervisor reconnects, 2) chop "clicks once and stops",
3) sleep does nothing without a bed and so blocks night-skipping for
other players, 4) curriculum reflex always fell through to wander.

Supervisor (#38):
- runtime/watch-filter.js: pure predicate excluding *.test.js + the
  supervisor itself; recursive:true so skills/ + social/ edits also
  restart. Burned a working main once when test files counted toward
  the rollback threshold.
- runtime/supervisor.js: watch-triggered restarts no longer count
  toward the crash-loop rollback path. Watcher is now recursive.

Chop / mine (#39):
- runtime/actions.js + runtime/skills/gather-stone.js: replaced raw
  pathfinder.goto + bot.dig with mineflayer-collectblock's
  bot.collectBlock.collect — handles approach, repositioning, LoS,
  dig and pickup as one primitive. Old version "swung once" because
  GoalGetToBlock often parked the bot in leaves above the log.

Sleep + bed (#40):
- runtime/actions.js: sleepInBed now ALSO places a carried bed on
  solid ground next to the bot and sleeps on it. Critical so the bot
  stops blocking player night-skipping the moment it owns a bed.

Bed pipeline (#41):
- runtime/skills/gather-wool.js: gather.wool skill — mines wool block
  if any nearby, otherwise shears or attacks the nearest sheep.
- runtime/skills/craft.js: craftBedSkill (any colour the bot has ≥3
  wool of, plus 3 planks, plus a table).
- runtime/curriculum.js: new milestone survive.bed sits between
  wood.tools and stone.32 so the bot gets a bed BEFORE everything else.
  Test fixture updated to include a red_bed in post-survive.bed stages.

Village / shelter / wheat (#42, #43):
- runtime/skills/build-shelter.js: village.build-shelter — real 3×3×3
  resumable hut blueprint around the recorded base, places one block
  per loop, idempotent so an interrupted build resumes correctly,
  marks each placed block in the owned-blocks ledger.
- runtime/skills/deposit-surplus.js: village.deposit-surplus opens
  the nearest chest and transfers surplus stacks while keeping a
  reserve of tools/food/bed.
- runtime/skills/farm-wheat.js: farm.wheat does one step per call
  (till adjacent-to-water grass, plant seeds, or harvest ripe wheat).
- runtime/curriculum.js: village.shelter milestone after base-site.

Scheduler glitch (root of "always wander"):
- runtime/bot.js: curriculum + locations are now computed BEFORE
  runTick. Previously they were stamped AFTER, so reflex.js saw
  snapshot.curriculum=undefined every tick and fell through to the
  wander fallback. Verified live: scheduler now dispatches
  gather.logs/gather.stone/craft.* by id via runSkill.

Eat-spam:
- runtime/reflex.js: eatReflex now checks inventory for actual food
  and updates lastEatAt on EVERY dispatch (not only successes), so a
  failed eat respects the 5 s cooldown instead of firing every tick.

npm test 123/123. Validated live on play.xmatic.team (curriculum
dispatched gather.logs via runSkill, recover hint switched to wander
when no log in range).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 11:12:21 +03:00

334 lines
11 KiB
JavaScript

// craft.* — thin skill wrappers around the existing actions.js crafting
// primitives. Each one is generated by makeCraftSkill so adding a new
// craftable is one entry in this file rather than a new module.
//
// All wood/stone crafts that need a workbench reuse actions.placeCraftingTable
// internally: the skill's preconditions guarantee the raw materials, then
// execute() defers to the actions.js implementation that handles
// table-placement, recipe lookup and bot.craft().
import {
craftPlanks,
craftSticks,
craftWoodenAxe,
craftWoodenPickaxe,
craftWoodenSword,
placeCraftingTable,
inv as invHelpers,
} from "../actions.js";
function totalPlanks(bot) {
return invHelpers.getAnyPlanksCount(bot);
}
function totalSticks(bot) {
return invHelpers.getItemCount(bot, "stick");
}
function totalLogs(bot) {
return invHelpers.getAnyLogCount(bot);
}
function count(bot, name) {
return invHelpers.getItemCount(bot, name);
}
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 asResult(res, doneCode = "done") {
if (res?.ok) {
return { ok: true, code: doneCode, detail: res.detail, worldDelta: { crafted: res.detail?.item ?? doneCode } };
}
const msg = String(res?.detail ?? "");
const code = msg.includes("no recipe")
? "no_recipe"
: msg.includes("timed out")
? "timeout"
: "failed";
return { ok: false, code, detail: res?.detail, worldDelta: null };
}
// --- direct wrappers around existing actions ---------------------------------
export const craftPlanksSkill = Object.freeze({
id: "craft.planks",
title: "Craft planks from logs",
timeoutMs: 20_000,
preconditions(ctx) {
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
if (totalLogs(ctx.bot) < 1) return { ok: false, code: "missing_material", detail: "no log in inventory" };
return { ok: true };
},
async execute(ctx, args = {}) {
return asResult(await craftPlanks(ctx.bot, args.count ?? 4));
},
});
export const craftSticksSkill = Object.freeze({
id: "craft.sticks",
title: "Craft sticks from planks",
timeoutMs: 20_000,
preconditions(ctx) {
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
if (totalPlanks(ctx.bot) < 2) return { ok: false, code: "missing_material", detail: "need 2 planks" };
return { ok: true };
},
async execute(ctx, args = {}) {
return asResult(await craftSticks(ctx.bot, args.count ?? 4));
},
});
export const craftWoodenAxeSkill = Object.freeze({
id: "craft.wooden-axe",
title: "Craft wooden axe",
timeoutMs: 30_000,
preconditions(ctx) {
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
if (totalPlanks(ctx.bot) < 3) return { ok: false, code: "missing_material", detail: "need 3 planks" };
if (totalSticks(ctx.bot) < 2) return { ok: false, code: "missing_material", detail: "need 2 sticks" };
return { ok: true };
},
async execute(ctx) {
return asResult(await craftWoodenAxe(ctx.bot));
},
});
export const craftWoodenPickaxeSkill = Object.freeze({
id: "craft.wooden-pickaxe",
title: "Craft wooden pickaxe",
timeoutMs: 30_000,
preconditions(ctx) {
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
if (totalPlanks(ctx.bot) < 3) return { ok: false, code: "missing_material", detail: "need 3 planks" };
if (totalSticks(ctx.bot) < 2) return { ok: false, code: "missing_material", detail: "need 2 sticks" };
return { ok: true };
},
async execute(ctx) {
return asResult(await craftWoodenPickaxe(ctx.bot));
},
});
export const craftWoodenSwordSkill = Object.freeze({
id: "craft.wooden-sword",
title: "Craft wooden sword",
timeoutMs: 30_000,
preconditions(ctx) {
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
if (totalPlanks(ctx.bot) < 2) return { ok: false, code: "missing_material", detail: "need 2 planks" };
if (totalSticks(ctx.bot) < 1) return { ok: false, code: "missing_material", detail: "need 1 stick" };
return { ok: true };
},
async execute(ctx) {
return asResult(await craftWoodenSword(ctx.bot));
},
});
// --- generic crafting (stone tools, furnace, chest, torch) -------------------
// Stone-tier and storage crafts share the same lookup-recipe-then-call-bot.craft
// shape as the wooden tools, but with different precondition counts and item
// names. We define a tiny factory.
//
// `requires` is a map from item name to required count. `needsTable: true`
// means we place / reuse a crafting table first (via actions.placeCraftingTable).
function makeRecipeSkill({ id, title, item, requires, needsTable, doneCode = "done" }) {
return Object.freeze({
id,
title,
timeoutMs: 30_000,
preconditions(ctx) {
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
for (const [name, n] of Object.entries(requires)) {
const have = name === "planks"
? totalPlanks(ctx.bot)
: count(ctx.bot, name);
if (have < n) {
return { ok: false, code: "missing_material", detail: `need ${n} ${name} (have ${have})` };
}
}
return { ok: true };
},
async execute(ctx) {
const bot = ctx.bot;
let tableBlock = null;
if (needsTable) {
const tableRes = await placeCraftingTable(bot);
if (!tableRes.ok) {
const msg = String(tableRes.detail ?? "");
const code = msg.includes("timed out") ? "timeout" : "missing_table";
return { ok: false, code, detail: tableRes.detail, worldDelta: null };
}
tableBlock = tableRes.block;
}
const reg = bot?.registry;
const itemId = reg?.itemsByName?.[item]?.id;
if (itemId == null) {
return { ok: false, code: "unsupported_version", detail: `unknown item ${item}`, worldDelta: null };
}
const recipes = bot.recipesFor(itemId, null, 1, tableBlock);
const recipe = recipes[0];
if (!recipe) {
return { ok: false, code: "no_recipe", detail: `no recipe for ${item}`, worldDelta: null };
}
try {
await withTimeout(bot.craft(recipe, 1, tableBlock), 15_000, `craft(${item})`);
return { ok: true, code: doneCode, detail: { item }, worldDelta: { crafted: item } };
} catch (e) {
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?.crafted;
},
});
}
export const craftStoneAxeSkill = makeRecipeSkill({
id: "craft.stone-axe",
title: "Craft stone axe",
item: "stone_axe",
requires: { cobblestone: 3, stick: 2 },
needsTable: true,
});
export const craftStonePickaxeSkill = makeRecipeSkill({
id: "craft.stone-pickaxe",
title: "Craft stone pickaxe",
item: "stone_pickaxe",
requires: { cobblestone: 3, stick: 2 },
needsTable: true,
});
export const craftStoneSwordSkill = makeRecipeSkill({
id: "craft.stone-sword",
title: "Craft stone sword",
item: "stone_sword",
requires: { cobblestone: 2, stick: 1 },
needsTable: true,
});
export const craftFurnaceSkill = makeRecipeSkill({
id: "craft.furnace",
title: "Craft furnace",
item: "furnace",
requires: { cobblestone: 8 },
needsTable: true,
});
export const craftChestSkill = makeRecipeSkill({
id: "craft.chest",
title: "Craft chest",
item: "chest",
requires: { planks: 8 },
needsTable: true,
});
// Bed: 3 wool of one colour + 3 planks → 1 bed of that colour. We look
// for any colour we have ≥3 of, ditto planks, and craft that pairing.
// All bed recipes require a crafting table.
const BED_COLORS = [
"white", "orange", "magenta", "light_blue", "yellow", "lime", "pink",
"gray", "light_gray", "cyan", "purple", "blue", "brown", "green",
"red", "black",
];
function countByName(bot, name) {
return bot.inventory.items().reduce((s, i) => (i.name === name ? s + i.count : s), 0);
}
function bedColorWeCanCraft(bot) {
// Need 3 wool of a single colour. (Mixed-colour wool can't combine.)
for (const c of BED_COLORS) {
if (countByName(bot, `${c}_wool`) >= 3) return c;
}
return null;
}
export const craftBedSkill = Object.freeze({
id: "craft.bed",
title: "Craft a bed",
timeoutMs: 30_000,
preconditions(ctx) {
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
const color = bedColorWeCanCraft(ctx.bot);
if (!color) return { ok: false, code: "missing_material", detail: "need 3 wool of one colour" };
if (totalPlanks(ctx.bot) < 3) return { ok: false, code: "missing_material", detail: "need 3 planks" };
return { ok: true };
},
async execute(ctx) {
const bot = ctx.bot;
const color = bedColorWeCanCraft(bot);
const item = `${color}_bed`;
const tableRes = await placeCraftingTable(bot);
if (!tableRes.ok) {
const msg = String(tableRes.detail ?? "");
const code = msg.includes("timed out") ? "timeout" : "missing_table";
return { ok: false, code, detail: tableRes.detail, worldDelta: null };
}
const reg = bot?.registry;
const itemId = reg?.itemsByName?.[item]?.id;
if (itemId == null) {
return { ok: false, code: "unsupported_version", detail: `no ${item} in registry`, worldDelta: null };
}
const recipes = bot.recipesFor(itemId, null, 1, tableRes.block);
const recipe = recipes[0];
if (!recipe) {
return { ok: false, code: "no_recipe", detail: `no recipe for ${item}`, worldDelta: null };
}
try {
await withTimeout(bot.craft(recipe, 1, tableRes.block), 15_000, `craft(${item})`);
return { ok: true, code: "done", detail: { item }, worldDelta: { crafted: item } };
} catch (e) {
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?.crafted;
},
});
// Torch: 1 stick + 1 coal (or charcoal) → 4 torches. We accept either
// fuel via precondition shortcut: if no coal AND no charcoal, fail with
// missing_material so the curriculum surfaces the blocker rather than
// silently fail at recipe lookup.
export const craftTorchSkill = Object.freeze({
id: "craft.torch",
title: "Craft torches",
timeoutMs: 20_000,
preconditions(ctx) {
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
if (totalSticks(ctx.bot) < 1) return { ok: false, code: "missing_material", detail: "need 1 stick" };
if (count(ctx.bot, "coal") < 1 && count(ctx.bot, "charcoal") < 1) {
return { ok: false, code: "missing_material", detail: "need 1 coal or charcoal" };
}
return { ok: true };
},
async execute(ctx) {
const bot = ctx.bot;
const reg = bot?.registry;
const itemId = reg?.itemsByName?.["torch"]?.id;
if (itemId == null) {
return { ok: false, code: "unsupported_version", detail: "no torch in registry", worldDelta: null };
}
const recipes = bot.recipesFor(itemId, null, 1, null);
const recipe = recipes[0];
if (!recipe) {
return { ok: false, code: "no_recipe", detail: "no recipe for torch (need coal+stick)", worldDelta: null };
}
try {
await withTimeout(bot.craft(recipe, 1, null), 15_000, "craft(torch)");
return { ok: true, code: "done", detail: { item: "torch" }, worldDelta: { crafted: "torch" } };
} catch (e) {
return { ok: false, code: "failed", detail: e.message, worldDelta: null };
}
},
});