Files
pepa-pi-bot/runtime/skills/chop-logs.js
T
mayatnikovandClaude Opus 4.7 d960db4819 feat(runtime): persistent memory — world-journal + scenario-memory
Closes a structural gap: the bot now actually REMEMBERS what it
discovered and what it tried. Two stores live under state/<host>/ and
are wired in automatically.

runtime/world-journal.js
- Append-only JSONL of discovered points (chopped, placed, base,
  shelter, farm, dead_end). Indexed by 16-block spatial grid; O(neighbors)
  nearest() lookups; 6 h age prune; 10k line ceiling with trim.
- leanestQuadrant({x,z}) reports the quadrant the bot has the FEWEST
  markers in — used by explore.far to circle rather than retread.
- summary() exposed for the stuck-incident proposal body.

runtime/scenario-memory.js
- Sliding window of (skillId, situationHash, code, ok, detail) tuples.
- situationHash() is a coarse fingerprint (16x8x16 cell + day/night +
  food/hp bucket + inv key set + closest hostile). So "same kind of
  place + same kind of state" matches.
- shouldSkip({skillId, situation}) → true after ≥3 failures within 30
  min UNLESS a more-recent success in the same situation un-locks it.
- recentTailFor() exposed for the stuck-incident body.

Wiring (runtime/bot.js):
- dispatchAction captures situationHash BEFORE the action runs and
  records (skillId, situation, code, ok) after — failures are attributed
  to the dispatch-time state, not the partial-effect state.
- worldDelta fields (choppedAt, minedAt, placedAt, baseAt, shelterAt,
  plantedAt, harvestedAt, tilledAt) auto-flow into the journal.
- no_target + silent_dig_failure also write dead_end markers.

Scheduler / skills now consume memory:
- reflex.js curriculum reflex calls memory.shouldSkip — if the same
  (skill, situation) failed 3+ times recently, auto-converts to a
  wander hint so the bot leaves and tries elsewhere.
- explore.far calls journal.leanestQuadrant when multiple cardinal
  directions are walkable and prefers the less-explored one.
- gather.logs walks to the nearest known "chopped" bucket within 96
  blocks before falling through to findBlock — chunks with confirmed
  trees are more likely to yield another.

stuck-incident body now includes journal byKind + last 12 scenario
entries so Pi can write a structural fix, not just a guard clause.

Architecturally: this is the foundation for "bot rewrites itself".
The proposals Pi now receives carry real signal about what was tried
and what's around, instead of a single snapshot in isolation.

10 new tests (world-journal × 5, scenario-memory × 5). npm test 134/134.

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

100 lines
3.3 KiB
JavaScript

// gather.logs — find the nearest log block matching the server's log
// registry, path to it, mine it. Wraps the existing actions.js primitive
// while exposing the survival-skill contract (preconditions, timeout,
// structured worldDelta, recovery hint).
import pathfinderPkg from "mineflayer-pathfinder";
const { pathfinder, goals } = pathfinderPkg;
import { chopNearestTree } from "../actions.js";
import { logs as logBlocks } from "./groups.js";
import { info } from "../log.js";
let pluginLoaded = new WeakSet();
function ensurePathfinder(bot) {
if (pluginLoaded.has(bot)) return;
bot.loadPlugin(pathfinder);
pluginLoaded.add(bot);
}
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));
}
export const skill = Object.freeze({
id: "gather.logs",
title: "Gather logs",
timeoutMs: 60_000,
preconditions(ctx) {
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
const known = logBlocks(ctx.bot);
if (known.size === 0) {
return { ok: false, code: "unsupported_version", detail: "no log blocks in registry" };
}
return { ok: true };
},
async execute(ctx) {
// Journal-aware approach: if we previously chopped a tree (or saw a
// tree marker) within 96 blocks, walk to that bucket first — the
// chunk has been confirmed to contain trees, so the next chop is
// likely to succeed there even if findBlock at the current position
// returned nothing.
const bot = ctx.bot;
const here = bot.entity?.position;
if (here && ctx?.journal?.nearest) {
const near = ctx.journal.nearest({ kind: "chopped", x: here.x, z: here.z, radius: 96, limit: 1 });
if (near.length && near[0].distance > 8) {
ensurePathfinder(bot);
const t = near[0].at;
info("action", `gather.logs: journal hint → walk to known tree area ${t.x},${t.y},${t.z} (${near[0].distance.toFixed(0)}m)`);
try {
await withTimeout(
bot.pathfinder.goto(new goals.GoalNear(t.x, t.y, t.z, 6)),
25_000,
"gotoTreeArea",
);
} catch {} // ignore, fall through to chop attempt
}
}
const res = await chopNearestTree(ctx.bot);
if (res.ok) {
return {
ok: true,
code: "done",
detail: res.detail,
worldDelta: {
choppedAt: res.detail?.at ?? null,
logType: res.detail?.logType ?? null,
},
};
}
const msg = String(res.detail ?? "");
// res.code can come straight from actions.js (silent_dig_failure),
// otherwise we classify from the detail string.
const code = res.code
? res.code
: (msg.includes("no reachable log") || msg.includes("no log within"))
? "no_target"
: msg.includes("timed out")
? "timeout"
: "failed";
return { ok: false, code, detail: res.detail, worldDelta: null };
},
validate(ctx, result) {
return result.ok && !!result.worldDelta?.logType;
},
recover(ctx, result) {
// Tell the caller: if there was no reachable log, switching to wander
// for ~60 s is the right next move — same heuristic the autonomous
// reflex already uses.
if (result.code === "no_target") {
return { hint: "wander", reason: "no log within 32 blocks" };
}
return null;
},
});