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>
This commit was merged in pull request #29.
This commit is contained in:
Yuriy Mayatnikov
2026-05-28 11:29:39 +03:00
committed by GitHub
co-authored by Claude Opus 4.7 mayatnikov
parent 15b6c11002
commit c910457817
31 changed files with 2236 additions and 61 deletions
+149
View File
@@ -0,0 +1,149 @@
// Settlement Contract (L3) — the global goal as a typed, invariant-checked
// chain of milestones (research §2). This replaces the two competing
// progression rails (storyline quest + raw curriculum) with ONE ordered
// contract whose "done" is a fact about the world, not a guess.
//
// Each milestone:
// id stable string
// title human label (TUI / diary)
// invariants [{ id, describe, met(world) }] — milestone is "met" iff all hold
// suggest (world) -> { skillId, args? } | null — next concrete action
// urgency? (world) -> number — utility boost so survival-critical
// milestones (food) can preempt a lower-indexed unmet milestone
//
// The early tech-tree milestones delegate `suggest` to the proven
// deterministic curriculum (runtime/curriculum.js) so we reuse its careful
// chop→craft→tool chain instead of duplicating it. The contract owns ordering,
// invariant truth, observability and the late-game milestones curriculum lacks.
import { nextMilestone as curriculumNext } from "../curriculum.js";
import {
alive,
foodSecure,
bedSecured,
stoneTier,
locationExists,
hasItem,
has,
WOODEN_TOOLS,
totalMatching,
} from "./invariants.js";
// curriculum's plan for the current snapshot. Prefer the plan bot.js already
// precomputed onto snapshot.curriculum (single source, no double-walk); fall
// back to recomputing when it is absent (unit tests, late-game). Returns null
// when curriculum is exhausted — the late-game contract takes over.
function curriculumPlan(world) {
const pre = world.snapshot?.curriculum?.plan;
if (pre && pre.skillId) return pre;
try {
return curriculumNext(world.snapshot)?.plan ?? null;
} catch {
return null;
}
}
const FOOD_MOBS = new Set(["cow", "pig", "chicken", "sheep", "rabbit", "mooshroom"]);
function hasVisibleFoodTarget(world) {
const passives = world.nearbyEntities?.passives ?? [];
if (passives.some((e) => FOOD_MOBS.has(e.name))) return true;
return (world.nearbyEntities?.droppedItems?.length ?? 0) > 0;
}
// Wooden tools acquired, OR already advanced to stone tier (monotonic: don't
// regress to "go chop wood" after the bot burned its logs into tools).
const woodenOrStoneTier = {
id: "tool_tier",
describe: "wooden tools (or already stone tier)",
met: (w) =>
WOODEN_TOOLS.every((n) => has(w.inventory, n)) ||
totalMatching(w.inventory, (k) => /^stone_(axe|pickaxe|sword)$/.test(k)) > 0,
};
// A wheat farm is established. We mark it via a `farm` location (set by the
// farm skill) or by carrying harvested wheat as a fallback proxy.
const farmEstablished = {
id: "farm",
describe: "a wheat farm location or harvested wheat",
met: (w) => !!w.locations?.farm || has(w.inventory, "wheat", 3),
};
export const SETTLEMENT_CONTRACT = Object.freeze([
{
id: "M0_alive",
title: "Stay alive",
invariants: [alive()],
suggest: () => null, // survival layer (modes/manifesto) owns HP emergencies
},
{
id: "M1_wood_tools",
title: "Wooden tools",
invariants: [woodenOrStoneTier],
suggest: curriculumPlan,
},
{
id: "M2_bed",
title: "A bed to skip the night",
invariants: [bedSecured()],
suggest: curriculumPlan,
},
{
id: "M3_stone_tools",
title: "Stone tools + furnace",
invariants: [stoneTier()],
suggest: curriculumPlan,
},
{
id: "M4_food_security",
title: "Secure food",
invariants: [foodSecure()],
// Direct suggest (NOT curriculum): when food urgency preempts a lower
// milestone, the strictly-ordered curriculum would still return the
// wood step. We want the food action now.
suggest: (w) => ({ skillId: hasVisibleFoodTarget(w) ? "survive.acquire-food" : "survive.scout-food" }),
// Starving preempts lower-indexed progression: go eat/hunt now.
urgency: (w) => (w.food < 8 ? 100 : w.food < 12 ? 20 : 0),
},
{
id: "M5_storage",
title: "A personal chest",
invariants: [locationExists("chest")],
suggest: curriculumPlan,
},
{
id: "M6_lighting",
title: "Torches for the perimeter",
invariants: [hasItem("torch", 4, "torch")],
suggest: curriculumPlan,
},
{
id: "M7_base_site",
title: "Pick a base site",
invariants: [locationExists("base")],
suggest: curriculumPlan,
},
{
id: "M8_shelter",
title: "Build a shelter",
invariants: [locationExists("shelter")],
suggest: curriculumPlan,
},
// ---- beyond the curriculum: late-game settlement work ----
{
id: "M9_farm",
title: "Start a wheat farm",
invariants: [farmEstablished],
suggest: (w) => {
// Deposit first if we're drowning in surplus and have a chest.
const distinct = Object.keys(w.inventory ?? {}).length;
if (distinct >= 30 && w.locations?.chest) return { skillId: "village.deposit-surplus" };
return { skillId: "farm.wheat" };
},
},
]);
export function listContractMilestones() {
return SETTLEMENT_CONTRACT.map((m) => ({ id: m.id, title: m.title }));
}
export const _internal = { woodenOrStoneTier, farmEstablished, curriculumPlan };
+93
View File
@@ -0,0 +1,93 @@
// GoalManager (L3) — the single progression authority.
//
// Walks the Settlement Contract, evaluates each milestone's invariants against
// the world, and selects which milestone to pursue now. Selection is a utility
// argmax over the UNMET milestones:
//
// score(m) = -index(m) + urgency(m, world)
//
// With no urgency this is just "lowest unmet milestone wins" (strict ordered
// progression). urgency lets a survival-critical milestone (food when starving)
// preempt a lower-indexed one — the DEPS-style "consider how easy/urgent a
// sub-goal is" idea, expressed as a hand-tuned utility (research §C, DEPS).
//
// The GoalManager does NOT dispatch and never calls the LLM. It returns a
// suggestion the scheduler consumes; the survival/emergency layer (modes,
// manifesto L0) still preempts above it.
import { SETTLEMENT_CONTRACT } from "./contract.js";
import { checkInvariants, worldFromSnapshot } from "./invariants.js";
import { prerequisitesMet } from "./skill-graph.js";
export function createGoalManager({ contract = SETTLEMENT_CONTRACT } = {}) {
// Evaluate every milestone; returns the per-milestone invariant status plus
// the selected current milestone and its suggested skill.
function evaluate(world) {
const evaluated = contract.map((m, index) => {
const check = checkInvariants(m, world);
return {
index,
id: m.id,
title: m.title,
met: check.met,
unmet: check.unmet,
evidence: check.evidence,
urgency: typeof m.urgency === "function" ? (m.urgency(world) || 0) : 0,
_m: m,
};
});
const completed = evaluated.filter((e) => e.met).length;
const total = evaluated.length;
const unmet = evaluated.filter((e) => !e.met);
if (unmet.length === 0) {
return { done: true, completed, total, milestone: null, suggestedSkill: null, ranked: [], evaluated };
}
// Utility argmax. Tie-break by lower index (more foundational first).
const ranked = unmet
.map((e) => ({ ...e, score: -e.index + e.urgency }))
.sort((a, b) => b.score - a.score || a.index - b.index);
const current = ranked[0];
let suggestedSkill = null;
try {
suggestedSkill = current._m.suggest(world) ?? null;
} catch {
suggestedSkill = null;
}
// Annotate the suggestion with skill-graph prerequisite status (Plan4MC).
// Observability + a guard surface: if prereqs are unmet the curriculum
// chain should already be steering toward them, but we expose the gap.
if (suggestedSkill?.skillId) {
const pre = prerequisitesMet(suggestedSkill.skillId, world);
if (!pre.ok) suggestedSkill = { ...suggestedSkill, blockedBy: pre.missing };
}
const reason = current.urgency > 0 && current.index > unmet[0].index
? `urgent:${current.id}(${current.urgency}) preempts ${unmet[0].id}`
: `lowest unmet: ${current.id}`;
return {
done: false,
completed,
total,
milestone: { id: current.id, title: current.title, unmet: current.unmet },
suggestedSkill,
reason,
ranked: ranked.map((r) => ({ id: r.id, score: r.score, urgency: r.urgency })),
evaluated,
};
}
// Convenience: build the world from a runtime snapshot (+optional ledger)
// and evaluate. This is what the scheduler calls each tick.
function next(snapshot, extra = {}) {
const world = worldFromSnapshot(snapshot, extra);
return evaluate(world);
}
return { evaluate, next };
}
+97
View File
@@ -0,0 +1,97 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { createGoalManager } from "./goal-manager.js";
import { SETTLEMENT_CONTRACT } from "./contract.js";
import { worldFromSnapshot, checkInvariants } from "./invariants.js";
function snap(extra = {}) {
return {
connected: true,
position: { x: 0, y: 64, z: 0 },
health: 20,
food: 20,
hasFood: false,
isDay: true,
inventory: {},
locations: {},
nearbyEntities: { passives: [], droppedItems: [] },
...extra,
};
}
const ALL_TOOLS = {
wooden_axe: 1, wooden_pickaxe: 1, wooden_sword: 1,
stone_axe: 1, stone_pickaxe: 1, stone_sword: 1, furnace: 1,
white_bed: 1, torch: 8, bread: 5,
};
test("fresh spawn selects M1 wood tools, suggests gather.logs", () => {
const gm = createGoalManager();
const r = gm.next(snap());
assert.equal(r.done, false);
assert.equal(r.milestone.id, "M1_wood_tools");
assert.equal(r.suggestedSkill.skillId, "gather.logs");
});
test("starving preempts lower milestones with the food skill (not curriculum wood)", () => {
const gm = createGoalManager();
const r = gm.next(snap({ food: 5 }));
assert.equal(r.milestone.id, "M4_food_security");
// no visible target → scout, and crucially NOT gather.logs
assert.equal(r.suggestedSkill.skillId, "survive.scout-food");
assert.match(r.reason, /urgent/);
});
test("starving with a visible chicken hunts it", () => {
const gm = createGoalManager();
const r = gm.next(snap({ food: 5, nearbyEntities: { passives: [{ name: "chicken", distance: 4 }], droppedItems: [] } }));
assert.equal(r.milestone.id, "M4_food_security");
assert.equal(r.suggestedSkill.skillId, "survive.acquire-food");
});
test("not-quite-starving (food 10) does NOT preempt wood; mild urgency only", () => {
const gm = createGoalManager();
// food 10 → M4 urgency 20, M1 unmet at index 1 → score(M1)=-1, score(M4)=-4+20=16 → M4 still wins.
// To assert ordered behaviour we use food 13 (urgency 0): wood wins.
const r = gm.next(snap({ food: 13 }));
assert.equal(r.milestone.id, "M1_wood_tools");
});
test("with wood+stone+bed+food, lowest unmet is M5 storage → craft.chest", () => {
const gm = createGoalManager();
const r = gm.next(snap({ inventory: { ...ALL_TOOLS, torch: 0 }, food: 20 }));
// torch removed so M6 lighting also unmet, but storage (M5) is lower.
assert.equal(r.milestone.id, "M5_storage");
assert.equal(r.suggestedSkill.skillId, "craft.chest");
});
test("everything done → done:true, completed == total", () => {
const gm = createGoalManager();
const r = gm.next(snap({
inventory: ALL_TOOLS,
food: 20,
hasFood: true,
locations: { chest: { x: 1 }, base: { x: 2 }, shelter: { x: 3 }, farm: { x: 4 } },
}));
assert.equal(r.done, true);
assert.equal(r.completed, r.total);
assert.equal(r.milestone, null);
});
test("progress fraction increases as milestones complete", () => {
const gm = createGoalManager();
const empty = gm.next(snap());
const advanced = gm.next(snap({ inventory: ALL_TOOLS, food: 20, hasFood: true }));
assert.ok(advanced.completed > empty.completed);
assert.equal(advanced.total, SETTLEMENT_CONTRACT.length);
});
test("checkInvariants reports which invariant is unmet", () => {
const m = SETTLEMENT_CONTRACT.find((x) => x.id === "M3_stone_tools");
const world = worldFromSnapshot(snap({ inventory: { stone_axe: 1, stone_pickaxe: 1, stone_sword: 1 } }));
const c = checkInvariants(m, world);
// missing furnace → unmet
assert.equal(c.met, false);
assert.ok(c.unmet.includes("stone_tier"));
});
+177
View File
@@ -0,0 +1,177 @@
// Invariant predicate library (L3).
//
// The research's core diagnosis: the bot picks plausible tasks but never
// asserts whether the world actually moved toward a settlement, so "progress"
// is replaced by noise. The fix is a typed contract whose milestones each
// carry INVARIANTS — boolean predicates over an authoritative world view — so
// "are we done with this milestone" is a fact about the world, not a guess.
//
// A predicate is a plain object: { id, describe, met(world) -> boolean }.
// `world` is the normalised view produced by worldFromSnapshot(): it exposes
// inventory (name->count), locations, health/food, daylight and an optional
// InventoryLedger. Predicates are PURE — they never touch the bot or disk.
// ---- world view ------------------------------------------------------------
export function worldFromSnapshot(snapshot, extra = {}) {
const s = snapshot ?? {};
return {
snapshot: s,
inventory: s.inventory ?? {},
locations: s.locations ?? {},
health: s.health ?? 20,
food: s.food ?? 20,
hasFood: !!s.hasFood,
isDay: s.isDay !== false,
position: s.position ?? null,
nearbyBlocks: s.nearbyBlocks ?? {},
nearbyEntities: s.nearbyEntities ?? {},
closestHostile: s.closestHostile ?? null,
ledger: extra.ledger ?? null,
};
}
// ---- inventory helpers (shared with the contract) --------------------------
export function totalMatching(inv, matcher) {
const f =
typeof matcher === "function"
? matcher
: matcher instanceof RegExp
? (k) => matcher.test(k)
: (k) => k === matcher;
let sum = 0;
for (const [k, n] of Object.entries(inv ?? {})) if (f(k)) sum += n;
return sum;
}
export function totalLogs(inv) {
return totalMatching(inv, (k) => k.endsWith("_log") || k.endsWith("_stem"));
}
export function totalPlanks(inv) {
return totalMatching(inv, (k) => k.endsWith("_planks"));
}
export function totalCobble(inv) {
return (inv?.cobblestone ?? 0) + (inv?.cobbled_deepslate ?? 0);
}
export function totalWool(inv) {
return totalMatching(inv, (k) => k.endsWith("_wool"));
}
export function maxSingleColourWool(inv) {
let best = 0;
for (const [k, n] of Object.entries(inv ?? {})) {
if (k.endsWith("_wool") && n > best) best = n;
}
return best;
}
export function hasAnyBed(inv) {
return totalMatching(inv, (k) => k.endsWith("_bed")) > 0;
}
export function has(inv, name, n = 1) {
return (inv?.[name] ?? 0) >= n;
}
export const WOODEN_TOOLS = ["wooden_axe", "wooden_pickaxe", "wooden_sword"];
export const STONE_TOOLS = ["stone_axe", "stone_pickaxe", "stone_sword"];
export const COOKED_FOODS = [
"bread", "cooked_beef", "cooked_chicken", "cooked_porkchop",
"cooked_mutton", "cooked_rabbit", "baked_potato", "apple",
"carrot", "potato", "cooked_cod", "cooked_salmon",
];
// ---- predicate builders ----------------------------------------------------
export function alive() {
return { id: "alive", describe: "health > 0", met: (w) => w.health > 0 };
}
export function healthAtLeast(n) {
return { id: `health>=${n}`, describe: `health at least ${n}`, met: (w) => w.health >= n };
}
export function foodAtLeast(n) {
return { id: `food>=${n}`, describe: `hunger at least ${n}`, met: (w) => w.food >= n };
}
// "Food security": carrying edible food, or well-fed, or holding a cooked
// staple. We cannot introspect chest contents from the snapshot, so this is
// the observable proxy for research M1's `food_stock>=5_in_chest`.
export function foodSecure() {
return {
id: "food_secure",
describe: "carrying edible food or well-fed",
met: (w) => w.hasFood || w.food >= 18 || COOKED_FOODS.some((n) => has(w.inventory, n)),
};
}
export function hasAllItems(names) {
return {
id: `has_all:${names.join(",")}`,
describe: `carrying all of ${names.join(", ")}`,
met: (w) => names.every((n) => has(w.inventory, n)),
};
}
export function hasItem(matcher, n = 1, label = null) {
return {
id: `has:${label ?? String(matcher)}>=${n}`,
describe: `at least ${n}× ${label ?? String(matcher)}`,
met: (w) => totalMatching(w.inventory, matcher) >= n,
};
}
export function woodenTier() {
return {
id: "wooden_tier",
describe: "wooden axe + pickaxe + sword",
met: (w) => WOODEN_TOOLS.every((n) => has(w.inventory, n)),
};
}
export function stoneTier() {
return {
id: "stone_tier",
describe: "stone axe + pickaxe + sword + furnace",
met: (w) => STONE_TOOLS.every((n) => has(w.inventory, n)) && has(w.inventory, "furnace"),
};
}
export function bedSecured() {
return {
id: "bed",
describe: "a bed on hand or a placed bed location",
met: (w) => hasAnyBed(w.inventory) || !!w.locations.bed,
};
}
// A named location exists in locations.json (set by the skill that builds it:
// village.choose-base → base, build-shelter → shelter, place-chest → chest).
export function locationExists(kind) {
return {
id: `loc:${kind}`,
describe: `a known ${kind} location`,
met: (w) => !!w.locations?.[kind],
};
}
// ---- checker ---------------------------------------------------------------
// Evaluate every invariant of a milestone against the world. Returns
// { met, unmet: [ids], evidence: { [id]: bool } } so the GoalManager can pick
// the lowest unmet milestone and the TUI can show *which* invariant is open.
export function checkInvariants(milestone, world) {
const invs = milestone?.invariants ?? [];
const evidence = {};
const unmet = [];
for (const inv of invs) {
let ok = false;
try {
ok = !!inv.met(world);
} catch {
ok = false;
}
evidence[inv.id] = ok;
if (!ok) unmet.push(inv.id);
}
return { met: unmet.length === 0, unmet, evidence };
}
+89
View File
@@ -0,0 +1,89 @@
// Skill dependency graph (Plan4MC-style, research §C). A static, declarative
// model of "what does this skill need, what does it produce". The contract
// already SEQUENCES the early game via the curriculum, so this graph is the
// queryable prerequisite layer on top: the GoalManager annotates each suggested
// skill with whether its prerequisites currently hold (surfaced for the TUI and
// as a guard against suggesting a skill that physically cannot succeed here).
//
// Requirement kinds:
// { item: <semantic-group|exact>, min } — need N of an item / group
// { tool: "pickaxe" | "axe" | "sword" } — need any tier of that tool
// Semantic groups: logs (*_log/_stem), planks (*_planks), sticks, cobblestone,
// wool (*_wool), coal, bed (*_bed). Anything else is matched as an exact name.
import { totalMatching, has } from "./invariants.js";
const GROUP = {
logs: (k) => k.endsWith("_log") || k.endsWith("_stem"),
planks: (k) => k.endsWith("_planks"),
wool: (k) => k.endsWith("_wool"),
cobblestone: (k) => k === "cobblestone" || k === "cobbled_deepslate",
coal: (k) => k === "coal" || k === "charcoal",
};
const TOOL = {
pickaxe: (k) => k.endsWith("_pickaxe"),
axe: (k) => k.endsWith("_axe") && !k.endsWith("_pickaxe"),
sword: (k) => k.endsWith("_sword"),
};
export const SKILL_GRAPH = Object.freeze({
"gather.logs": { requires: [], produces: ["logs"] },
"gather.wool": { requires: [], produces: ["wool"] },
"gather.stone": { requires: [{ tool: "pickaxe" }], produces: ["cobblestone"] },
"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"] },
"craft.wooden-pickaxe": { requires: [{ item: "planks", min: 3 }, { item: "stick", min: 2 }], produces: ["wooden_pickaxe"] },
"craft.wooden-sword": { requires: [{ item: "planks", min: 2 }, { item: "stick", min: 1 }], produces: ["wooden_sword"] },
"craft.stone-axe": { requires: [{ item: "cobblestone", min: 3 }, { item: "stick", min: 2 }], produces: ["stone_axe"] },
"craft.stone-pickaxe": { requires: [{ item: "cobblestone", min: 3 }, { item: "stick", min: 2 }], produces: ["stone_pickaxe"] },
"craft.stone-sword": { requires: [{ item: "cobblestone", min: 2 }, { item: "stick", min: 1 }], produces: ["stone_sword"] },
"craft.furnace": { requires: [{ item: "cobblestone", min: 8 }], produces: ["furnace"] },
"craft.chest": { requires: [{ item: "planks", min: 8 }], produces: ["chest"] },
"craft.torch": { requires: [{ item: "coal", min: 1 }, { item: "stick", min: 1 }], produces: ["torch"] },
"craft.bed": { requires: [{ item: "wool", min: 3 }, { item: "planks", min: 3 }], produces: ["bed"] },
"village.choose-base": { requires: [], produces: ["loc:base"] },
"village.build-shelter": { requires: [{ item: "planks", min: 1 }], produces: ["loc:shelter"] },
"village.place-chest": { requires: [{ item: "chest", min: 1 }], produces: ["loc:chest"] },
"farm.wheat": { requires: [], produces: [] },
});
function itemCount(inv, name) {
const g = GROUP[name];
return g ? totalMatching(inv, g) : (inv?.[name] ?? 0);
}
function hasTool(inv, kind) {
const t = TOOL[kind];
if (!t) return false;
return Object.keys(inv ?? {}).some((k) => t(k) && (inv[k] ?? 0) > 0);
}
// { ok, missing: [{ item|tool, min, have }] } for a skill given the world.
export function prerequisitesMet(skillId, world) {
const node = SKILL_GRAPH[skillId];
if (!node) return { ok: true, missing: [], known: false };
const inv = world?.inventory ?? {};
const missing = [];
for (const req of node.requires) {
if (req.tool) {
if (!hasTool(inv, req.tool)) missing.push({ tool: req.tool });
} else if (req.item) {
const have = itemCount(inv, req.item);
if (have < (req.min ?? 1)) missing.push({ item: req.item, min: req.min ?? 1, have });
}
}
return { ok: missing.length === 0, missing, known: true };
}
export function canRun(skillId, world) {
return prerequisitesMet(skillId, world).ok;
}
// All skills whose prerequisites currently hold (Plan4MC "frontier").
export function runnableFrontier(world) {
return Object.keys(SKILL_GRAPH).filter((id) => canRun(id, world));
}
export const _internal = { GROUP, TOOL, itemCount, hasTool, has };
+56
View File
@@ -0,0 +1,56 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { prerequisitesMet, canRun, runnableFrontier, _internal } from "./skill-graph.js";
function world(inv = {}) {
return { inventory: inv };
}
test("gather.logs needs nothing", () => {
assert.equal(canRun("gather.logs", world()), true);
});
test("gather.stone needs a pickaxe (any tier)", () => {
assert.equal(canRun("gather.stone", world({})), false);
assert.equal(canRun("gather.stone", world({ wooden_pickaxe: 1 })), true);
assert.equal(canRun("gather.stone", world({ stone_pickaxe: 1 })), true);
});
test("craft.planks needs a log (semantic group)", () => {
assert.equal(canRun("craft.planks", world({})), false);
assert.equal(canRun("craft.planks", world({ birch_log: 1 })), true);
assert.equal(canRun("craft.planks", world({ mangrove_stem: 2 })), true);
});
test("craft.furnace needs 8 cobblestone", () => {
assert.equal(canRun("craft.furnace", world({ cobblestone: 7 })), false);
assert.equal(canRun("craft.furnace", world({ cobblestone: 8 })), true);
assert.equal(canRun("craft.furnace", world({ cobbled_deepslate: 8 })), true);
});
test("prerequisitesMet reports the missing requirement detail", () => {
const r = prerequisitesMet("craft.wooden-pickaxe", world({ stick: 2 }));
assert.equal(r.ok, false);
assert.deepEqual(r.missing, [{ item: "planks", min: 3, have: 0 }]);
});
test("unknown skill is treated as runnable (known:false)", () => {
const r = prerequisitesMet("explore.far", world());
assert.equal(r.ok, true);
assert.equal(r.known, false);
});
test("axe matcher excludes pickaxe", () => {
assert.equal(_internal.TOOL.axe("wooden_axe"), true);
assert.equal(_internal.TOOL.axe("wooden_pickaxe"), false);
assert.equal(_internal.TOOL.pickaxe("stone_pickaxe"), true);
});
test("runnableFrontier grows as inventory fills", () => {
const empty = runnableFrontier(world());
const stocked = runnableFrontier(world({ oak_planks: 8, stick: 4, cobblestone: 8, wooden_pickaxe: 1 }));
assert.ok(stocked.length > empty.length);
assert.ok(stocked.includes("gather.stone"));
assert.ok(stocked.includes("craft.furnace"));
});
+78
View File
@@ -0,0 +1,78 @@
// Village Score (L5 eval) — one number for "is the bot actually building a
// settlement, or just walking?" (research §2). The research's formula mixes
// milestones, food stock, fence closure, lit tiles, uptime, distinct skills
// and dialog quality. We compute the subset that is *observable* today; fence
// polygon / lit-tile fraction stay at 0 until those skills exist (the score is
// honest about what it can measure rather than faking precision).
//
// Pure: snapshot + a few derived inputs in, { score, components } out. Score is
// normalised to 0..1 so a dashboard / TUI can show a single percentage.
const TWO_HOURS_MS = 2 * 60 * 60 * 1000;
const DISTINCT_SKILL_TARGET = 12;
function clamp01(n) {
if (!Number.isFinite(n)) return 0;
return n < 0 ? 0 : n > 1 ? 1 : n;
}
function milestoneFraction(contract) {
if (!contract || !contract.total) return 0;
return clamp01(contract.completed / contract.total);
}
function foodSecurity(snapshot) {
if (snapshot?.hasFood) return 1;
return clamp01((snapshot?.food ?? 0) / 18);
}
function baseEstablished(snapshot) {
const loc = snapshot?.locations ?? {};
const want = ["base", "shelter", "chest"];
const have = want.filter((k) => loc[k]).length;
return clamp01(have / want.length);
}
function distinctSkillsSucceeded(metrics) {
if (!metrics) return 0;
const n = Object.values(metrics).filter((m) => (m?.ok ?? 0) > 0).length;
return clamp01(n / DISTINCT_SKILL_TARGET);
}
function uptimeFraction(uptimeMs) {
return clamp01((uptimeMs ?? 0) / TWO_HOURS_MS);
}
function survival(snapshot) {
return clamp01((snapshot?.health ?? 0) / 20);
}
const WEIGHTS = Object.freeze({
milestones: 0.35,
food: 0.15,
base: 0.15,
distinctSkills: 0.15,
uptime: 0.10,
survival: 0.10,
});
export function computeVillageScore(snapshot, { contract, uptimeMs = 0, metrics = null } = {}) {
const components = {
milestones: milestoneFraction(contract),
food: foodSecurity(snapshot),
base: baseEstablished(snapshot),
distinctSkills: distinctSkillsSucceeded(metrics),
uptime: uptimeFraction(uptimeMs),
survival: survival(snapshot),
};
let score = 0;
for (const [k, w] of Object.entries(WEIGHTS)) score += w * components[k];
return {
score: Math.round(clamp01(score) * 1000) / 1000,
components,
milestonesCompleted: contract?.completed ?? 0,
milestonesTotal: contract?.total ?? 0,
};
}
export const _internal = { clamp01, WEIGHTS, milestoneFraction, foodSecurity, baseEstablished };
+52
View File
@@ -0,0 +1,52 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { computeVillageScore, _internal } from "./village-score.js";
function snap(extra = {}) {
return { connected: true, health: 20, food: 20, hasFood: false, locations: {}, ...extra };
}
test("empty/fresh world scores low", () => {
const r = computeVillageScore(snap({ health: 20, food: 5 }), {
contract: { completed: 0, total: 10 },
uptimeMs: 0,
metrics: {},
});
assert.ok(r.score < 0.2, `expected low score, got ${r.score}`);
});
test("a fully established settlement scores high", () => {
const metrics = {};
for (let i = 0; i < 12; i++) metrics[`skill.${i}`] = { ok: 3, fail: 0 };
const r = computeVillageScore(
snap({ health: 20, food: 20, hasFood: true, locations: { base: {}, shelter: {}, chest: {} } }),
{ contract: { completed: 10, total: 10 }, uptimeMs: 3 * 60 * 60 * 1000, metrics },
);
assert.ok(r.score > 0.9, `expected high score, got ${r.score}`);
assert.equal(r.components.milestones, 1);
assert.equal(r.components.base, 1);
});
test("score is monotonic in milestone completion", () => {
const base = { uptimeMs: 0, metrics: {} };
const low = computeVillageScore(snap(), { ...base, contract: { completed: 1, total: 10 } });
const high = computeVillageScore(snap(), { ...base, contract: { completed: 8, total: 10 } });
assert.ok(high.score > low.score);
});
test("score stays within 0..1", () => {
const r = computeVillageScore(snap({ health: 999, food: 999 }), {
contract: { completed: 100, total: 10 },
uptimeMs: 1e12,
metrics: { a: { ok: 999 } },
});
assert.ok(r.score >= 0 && r.score <= 1);
});
test("clamp01 helper", () => {
assert.equal(_internal.clamp01(-1), 0);
assert.equal(_internal.clamp01(2), 1);
assert.equal(_internal.clamp01(0.5), 0.5);
assert.equal(_internal.clamp01(NaN), 0);
});