- README: update lede, architecture block, self-improvement section, status.
Mentions knowledge.db, coach/advice loop, persona narration, and the new
PR-based auto-patch flow.
- scripts/auto-patch.js: replace cherry-pick-to-main with `git push` +
`gh pr create`. The operator is now the only one who can merge into main
(enforced by branch protection rules on the remote). Legacy direct-merge
path remains behind PEPA_AUTO_PATCH_MERGE=cherry-pick for emergencies.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Major iteration. The bot now:
1. Maintains a per-server SQLite knowledge.db with structured memory:
recipes, mob_intel, block_intel, lessons, deaths, postmortems, poi,
wiki_pages, chat_log, code_changes. Seeded from docs/.
2. Captures every death event into the `deaths` table with full context
(last skill, hostile, recent dispatches, snapshot). A periodic coach
loop (≤3 Pi calls/hour) extracts generalised lessons from batches of
unanalysed deaths and writes them to the `lessons` table.
3. Honours learned lessons at dispatch time. curriculumReflex and
defendReflex consult knowledge.topAdvice before action: if a
high-confidence lesson says "avoid <skill>" or "prefer <alternative>",
the dispatcher swaps or backs off. Closes the learning loop.
4. Narrates its actions in Russian MC chat (≤8 lines/hour, ≥75s gap):
skill starts, threat sightings, dusk/dawn, respawn, milestones.
5. Includes pre-v0.2.0 WIP in the baseline commit: pathfinder watchdog
refinements that avoid interrupting collectBlock, metric-driven
reflex recovery, persistent skill metrics, new skills (flee,
acquire-food, place-chest, sleep), gather.logs hostile-proximity
bail-out (auto-patch).
See docs/v0.2.0-self-learning.md for the rc.2/final roadmap.
237/237 tests pass. better-sqlite3 dep added; the subsystem
gracefully no-ops when the driver is missing.
This closes the learning loop. Lessons in knowledge.db now actually
influence behaviour:
- runtime/coach/advice.js: consult({plannedSkillId, snapshot}) reads
knowledge.topAdvice() and returns 'override' / 'avoid' / 'proceed'.
When a lesson says "avoid <skill>" with prefer="survive.flee" (etc.),
the dispatcher swaps in the alternative.
- runtime/reflex.js:
* curriculumReflex now consults advice before dispatch; on 'avoid'
backs off the planned skill + sets wander hint; on 'override'
dispatches the lesson's preferred alternative.
* defendReflex (dist≤4 melee branch) consults advice too — so a
creeper at 4m honours the starter rule "attack creeper → flee".
Failure outcomes feed back via markApplied so confidence stays
grounded.
SAFE_OVERRIDES whitelist contains only known runSkill targets
(survive.flee, survive.sleep, survive.eat, recovery.tunnel-out,
explore.far/wander, village.build-shelter); unknown prefers fall back
to plain 'avoid'.
7 advice tests; total suite 237 green.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Major iteration: self-learning agent with knowledge base, post-mortem
coach, and persona narration. See docs/v0.2.0-self-learning.md for the
full design. This commit only adds the scaffolding (design + deps);
subsequent commits add the modules.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Baseline for the v0.2.0 self-learning iteration. All 205 tests pass on this
state. Subsequent commits in this branch layer the knowledge base,
post-mortem coach, and persona narration on top.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Problem (live 2026-05-26 screenshot): player drops a block in front of
the bot mid-path. mineflayer-pathfinder computes the path once when
goto() is called and never recomputes for world changes. Bot pushes
forward against the new block until the 30–60 s goto timeout fires,
visible as the bot just standing there pressing W.
Fix — runtime/pathfinder-watchdog.js: per-bot poll loop (2 s tick) that
runs while bot.pathfinder.goal is non-null. Tracks horizontal position.
If movement < 0.5 blocks for > 6 s after an initial 1.5 s grace,
forces a replan: setGoal(null) + setGoal(<same goal>) on a 250 ms
delay. That makes the planner rebuild the path against the current
world, so it routes around the new block — or, with canDig=true in our
profiles, digs through it. Capped at 3 replans per goal so a genuinely
unreachable target still bubbles up to the caller's timeout.
Side benefit: catches mineflayer-pathfinder issue #222 ("path hangs
on unreachable goal") much earlier than our 45 s goto wrappers.
Wired into bot.js on the "spawn" event and stopped on gracefulExit.
7 new unit tests cover the polling math + replan cap. 197/197 green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Replaces the canned-template "yo" path for greetings / status / addressed
banter with a Pi roundtrip that takes a real persona, the bot's current
in-game context, the operator's diary tail, AND the last 8 chat turns
with THIS specific player. Per-player cooldown (8 s) + per-message
chat-rate cooldown survive the existing throttle so a chatty player
can't drain Pi tokens.
runtime/social/chat-history.js — append/recent per player into
state/<host>/chat/<player>.jsonl, 1000-line rolling cap. Each entry
stores { ts, dir, text, snap? } where snap is a compact position +
activeSkill + milestone at the time of the turn, so Pi can later say
"помнишь когда мы тогда у воды лес рубили". Survives restarts and
auto-patch cherry-picks.
runtime/social/reply-pi.js — Russian-first system prompt locking the
bot as "pepa_bot, автономный игрок-фермер" on play.xmatic.team, one-
line answers, no emojis, no AI/bot self-mentions, no sycophancy. Spawns
`pi -p`, sanitises the response (strips pepa: prefix, code fences,
quotes, multi-line), caps at 200 chars before sending into MC chat.
Graceful: timeout/parse-fail → returns null, caller falls through to
the existing template path so the bot never goes mute.
bot.js handleChat:
- Skip messages from our own username (defensive — never reply to self).
- Record every inbound line into chat-history.
- For non-COMMAND_LIKE / non-UNSAFE intents, try piReply first; on
success, send + record outbound; on null/throw, fall through to the
templated generateReply.
14 new unit tests (sanitiseReply edge cases, history rotation, snap
compaction, prompt content). 190/190 green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three live-verification surfaces on top of v0.1.0:
1. cmd:screenshot { reason?, frames? } → runtime/viewer.takeScreenshot
- Headless POV render via prismarine-viewer.headless to
state/<host>/screenshots/<ISO>-<reason>.mp4 (1 frame ≈ ~10 KB).
- Lazy-loads the heavy GL stack on first call so the bot doesn't pay
the cost on startup or in TUI-only sessions.
- Returns { ok, path, error } over IPC LOG event.
- Known limitation: needs node-canvas. node-canvas v3 (current npm
default) is incompatible with prismarine-viewer's API; v2 doesn't
build under Node 24 (node-pre-gyp fail). So today the feature is
wired and the IPC contract is stable, but the underlying render
fails fast with "createCanvas is not a function". A future cleanup
can either fork the renderer or pin a Node 20 toolchain.
2. cmd:force-incident { kind?, reason? } → filePostCritique path
- Operator-triggered demo of the critic → proposal → auto-improve →
auto-patch chain. Was previously only observable when the bot
genuinely got stuck. Now a single IPC call exercises the full
loop on demand.
- Verified live 2026-05-26: critic call returned a real, useful
critique ("attack zombie returns done while target is alive →
blocks gather.logs"), proposal landed with all sections including
the Critic block, auto-improve picked it up within 10 s.
3. prismarine-viewer + canvas added to dependencies so npm install
builds the deps once and the IPC surface is always available.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Five concrete patterns from Voyager and Mindcraft, applied in our shape
without abandoning the git-as-evolution-substrate that makes pepa
distinct. Plus a first multi-agent surface so two bots from the same
repo can share intent.
1. runtime/critic.js (Voyager critic.txt)
- Spawns `pi -p` with a JSON-only critic prompt before a proposal is
written. {reasoning, success, critique}.
- success=true short-circuits the proposal (bot recovered between
detector tripping and now), saving Pi tokens on false positives.
- critique is spliced into the proposal body via attachCritique() so
the downstream auto-patcher has a sharp spec.
- Graceful: pi missing / timeout / unparseable JSON → proposal still
filed without the critic block.
2. scripts/lint-patch.js (Mindcraft coder._lintCode)
- Pre-flight gate between Pi commit and npm test: node --check, dynamic
import (catches missing named exports), regex extraction of
runSkill("id") calls cross-checked against the live registry.
- Cheaper than npm test, fails fast with a clear reason.
3. runtime/stuck-incident.renderActionTemplate (Voyager action_template.txt)
- All proposal bodies now follow the same fixed-section layout: Task /
Last result / Execution error / State / Metrics / Journal /
Scenarios / Critique / Fix / Edit scope / Forbidden.
4. runtime/skill-library.js (Mindcraft skill_library.getRelevantSkillDocs)
- Word-overlap ranking (Mindcraft's offline fallback) — zero deps,
deterministic. auto-patch.js injects top-3 similar skills into the
Pi prompt as "look at these patterns".
5. runtime/modes.js (Mindcraft modes.js)
- Declarative {name, interrupts, on, active, update(ctx)} chain that
runs BEFORE the curriculum each tick.
- Ships self_preservation (low HP → eat/flee), hunger (food<14 → eat),
night_shelter (night + bed in hand → sleep). Cleaner than ad-hoc
lastFleeAttempt cooldowns in reflex.js.
6. runtime/social/conversation.js + cmd:conv-say/conv-recent/conv-list
- File-JSONL topic channel so two bots from the same repo (different
usernames, different host dirs under state/) can append turns and
read peers. Skeleton — multi-agent collaboration on top later.
Differentiator preserved: every Pi-written skill still lands on main via
auto-patch.js (real git branch + smoke gate + cherry-pick). Voyager
keeps skills in a Chroma JSON, Mindcraft keeps them in RAM — pepa keeps
them as versioned source code reviewable in `git log`.
package.json: 0.0.1 → 0.1.0. 174/174 tests pass. README + AGENTS updated.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Root cause of "bot just stands still": every gather.* skill was using
bot.findBlock({ matching: (b) => names.includes(b.name) }), and under
mineflayer 1.21.4 + ViaBackwards the Block objects fed into the
callback have a wrong .name field (Block.type / numeric id is still
correct — this is mineflayer issue #2347). Every search returned null,
every skill reported "no_target", reflex looped wander → tunnel-out
forever. The bot's logs said "dispatch ok" while the operator watched
it pace in circles.
Proven live with a new diag.match skill on play.xmatic.team:
findBlocks({matching: numericIds}) → 50 hits
findBlocks({matching: (b) => b.name === ...}) → 0 hits ← the bug
findBlock({matching: (b) => b.name === ...}) → null ← the bug
findBlock({matching: numericIds}) → dark_oak_log @ (606,62,110)
After this fix the same bot from the same spawn dispatches gather.logs
and reaches the chop loop ("chop: dark_oak_log at 606,62,110 (tool=fists)")
instead of returning "no reachable log within 64 blocks".
Changes:
- runtime/perception.js (new): findBlocksByName / findNearestBlockByName
centralise the numeric-id workaround for any future skill.
- runtime/actions.js: chopNearestTree, sleepInBed, placeCraftingTable now
use perception. Also load mineflayer-tool plugin alongside collectblock
(collectblock 1.6 hard-requires bot.tool to dispatch a dig).
- gather-stone, gather-wool, deposit-surplus rewritten to numeric-id
search. gather-wool also loads mineflayer-tool.
- diagnose-scan.js (new): two diagnostic skills — diag.scan reports
findBlocks counts per radius for common blocks; diag.match cross-tests
the four matcher styles so this regression can be re-proven on demand.
- runtime/skills/index.js: registers diag.scan + diag.match.
Memory: project_findblock_callback_broken_under_viabackwards.md.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When Pi writes a multi-file runtime patch, the supervisor's file watcher
can fire between two consecutive writes, kill the bot mid-edit, and load
a half-saved file with a SyntaxError. Loop until the operator stops it.
scripts/auto-patch.js now creates state/auto-patch.lock with its PID
right after the branch checkout (before spawning pi -p), and removes
it on every exit path. runtime/supervisor.js defers any watch-triggered
restart while the lock holder is alive, polling every 2 s; once the
lock drops it waits 1.5 s for the final write to settle, then runs
\`node --check\` on the changed file and only restarts if it parses.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pi-authored follow-up from a second auto-patch cycle — the original
"does not count jumping in place as escape" test forgot to provide a
dig() mock, so the in-place jump path crashed when the test exercised
escape-pit's "dig above" fallback. Adding the mock makes the test
actually verify the assertion it claims.
138/138 tests now.
Co-Authored-By: pepa_bot self-improvement loop <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two bugs the live self-improvement run exposed:
1) Auto-patch was spawned with detached:false, so when supervisor
restarted bot.js (file change after Pi's commit landed on the
auto branch), the auto-patch child was killed mid-way — Pi's
commit lived in the auto branch but never got cherry-picked.
Recovered manually this round via reflog + cherry-pick. Now
detached:true + child.unref() + a per-run log at
state/_auto-patch-last.log so the operator can read Pi's full
output later.
2) Pi's recovery-tunnel-out.test.js was created but not in npm test
script; tests would have stayed unrun forever. Added.
Also commits the Pi-authored skill (eb29591 cherry-picked):
- runtime/skills/recovery-tunnel-out.js (+ test)
- improvements to runtime/actions.js + runtime/skills/explore-far.js
- wired into runtime/skills/index.js
npm test 137/137.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closes the self-improvement loop: when escape-pit + wedged-jump +
blind fallback all run 3× in a row without freeing the bot, fire a
dedicated proposal at the auto-improver. Pi gets the full context
(journal byKind, last 12 scenario-memory entries, current slim
snapshot) and is asked to either improve escapePit() (dig forward +
down + side, not only up) OR add a brand-new recovery.tunnel-out skill.
- runtime/stuck-incident.js: new checkWedged() path with separate
cooldown (10 min) from the no-progress path. noteResult() ingests
every dispatched action's detail.mode to count wedged completions.
- runtime/bot.js: dispatchAction calls stuckIncident.noteResult(res)
after each result; tick() calls checkWedged() and files the proposal
via writeProposal({editScope:[runtime/actions.js, runtime/skills/,
runtime/reflex.js]}).
This is the architectural piece: a bot wedged in a 1×1 hole now
generates a proposal that Pi can act on (with edit-scope guard rails
+ npm test smoke gate from PR #19), instead of looping wedged-jump
forever.
Verified live: bot now also picks direction from journal —
"explore.far: journal says leanest quadrant=NE → prefer N" — first
time the bot uses persistent memory to choose where to go next.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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>
When probe-cardinal shows all 4 directions blocked (the bot is in a
1×1 pit, surrounded by leaves, or in a corridor corner), don't just
hold forward+jump — actually dig the block above the bot's head,
jump into the new gap, repeat up to 3 times. Both wander and
explore.far now call escapePit() in this branch.
Observed live: bot fell into a pit at (623,71,106) after first
explore.far and looped wedged-jump→still-wedged→wedged-jump for 60s
before this fix. With escape-pit, the bot now actually breaks out.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Ground-truth finding (diag.physics):
forward N:0.03 E:3.38 S:0 W:3.26 → forward WORKS in unobstructed dirs
jump ΔY=1.25 → jump WORKS (vanilla height)
dig untested (no soft block within 6 of spawn)
So the bot CAN move and jump — the previous "stands still" symptom was
our wander/explore code picking blocked random angles and trusting a
pathfinder that times out on this server's terrain. Each retry just
picked another random direction, often the same blocked one.
- runtime/actions.js wander: probe 4 cardinal yaws for 800ms each,
measure actual Δ, commit to the best one for the remaining budget.
Falls back to "wedged-jump" (forward+jump 2.5s) only when ALL four
cardinals are <0.5 blocks.
- runtime/skills/explore-far.js: same probe-then-go shape, scaled to a
~48-block long walk in the best direction. Replaces the static
NE/SE/SW/NW quadrant rotation that ignored what was actually
walkable.
- runtime/movement-profiles.js: canDig back to true on gather/travel/
flee. The earlier "everything false" defensive default was based on
a wrong hypothesis (silent dig failure) — diag.physics + server-side
inspection (no anti-cheat plugin, spawn-protection=0) showed dig is
fine.
- runtime/compat.test.js: assertions follow profile defaults.
- runtime/skills/diagnose-physics.js: forward probe now tries 4
cardinals and returns trials + bestDir + bestDist so it can be used
to debug "wedged" reports later.
Verified live: bot now actually walks 47 blocks north after
probe.cardinal showed N:2.4 free. First end-to-end real movement on
play.xmatic.team since this session started.
npm test 124/124.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two-pronged response to user-confirmed "bot stands still, doesn't actually
chop" on play.xmatic.team:
1. Pin protocol — .env now sets MC_VERSION=1.21.4. minecraft-data has
wrong packet ID mappings for protocol 775 (server 26.1.2 via
ViaBackwards 5.9.1) — see mineflayer#3888 and #3717. 1.21.5 also has
an enchants decoder bug that breaks bot.dig. 1.21.4 is the last
protocol mineflayer 4.37.1 can speak cleanly through VIA.
2. Don't trust dig success — runtime/actions.js chopNearestTree and
runtime/skills/gather-stone.js now lookAt(face center)+forceLook,
await collectBlock, then re-read the target block. If the log/stone
is STILL there, return ok:false code:"silent_dig_failure" and
blacklist the position. Prevents the curriculum from reporting
"wood.16 in progress" while the world hasn't actually changed.
3. Defensive default — runtime/movement-profiles.js: canDig=false on
every profile until dig is confirmed working live. Otherwise
pathfinder schedules paths through must-dig blocks and the bot loops.
4. Ground-truth probe — runtime/skills/diagnose-physics.js dispatches
forward/jump/dig probes and writes the result to the diary. New
IPC command cmd:run-skill lets the operator (or a future curriculum
trigger) fire any skill on demand; it waits for the current action
to finish before dispatching. /tmp/pepa-runskill.mjs is a one-shot
client.
Live probe on play.xmatic.team confirmed: forward Δ=0.003 over 2s
(BROKEN — server rejects movement packets), jump ΔY=0.42 (likely
physics jitter, not a real jump). Strongly suggests an anti-cheat
plugin gating bot-style movements server-side — beyond protocol pin.
npm test 124/124.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Follow-up to the iteration-1 fixes. Live smoke on play.xmatic.team
revealed the bot was spawning into a tree-less plain (no log within
32 blocks of spawn), looping wander→gather→no_target→wander
forever inside a 16-block box.
- runtime/actions.js: chopNearestTree search radius 32 → 64 (still no
trees on this spawn, but a normal biome will be served well by it).
wander now has a blind-walk fallback when pathfinder times out
(look+forward+jump for 3 s) so the bot at least unsticks from leaves
or pillars. Pathfinder timeout reduced 30 s → 15 s.
- runtime/skills/explore-far.js: new explore.far skill — walks ~48
blocks in a quadrant (NE/SE/SW/NW, rotating per call) so successive
hints actually circle the spawn instead of bouncing in place. Blind
walk fallback included.
- runtime/reflex.js: when the scheduler is told to wander twice in a
row by gather.* recover hints, it now dispatches explore.far instead
so the bot actually leaves the patch it's stuck in. Resets the
consecutiveWanderHints counter on any success.
- runtime/reflex.js (sleep): no longer dispatches when the bot has
neither a bed in inventory NOR a known shelter/base location —
saved one dispatch + 5-min cooldown per restart at night.
- runtime/reflex.js (eat): inventory check + lastEatAt always updated
fix the eat-spam loop observed live (every tick fired "eat" → "no
food in inventory" → again).
- runtime/skills/chop-logs.js: recognise "no log within ..." as
no_target so the recover hint switches the bot to wander/explore.
npm test 124/124.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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>
Operator PRDs and scratch implementation notes live under plans/ and
should not be committed to the repo.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
OpenClaw is a different paradigm than our Pi-based bridge — messaging-first,
marketplace of pre-built skills (astraopenclaw/minecraft-agent already exists),
self-extension via skill authoring. The operator wants to run an OpenClaw
instance side-by-side with pepa-pi-bot to compare which approach gets to a
visible village faster.
prompts/openclaw-seed.md: single founding-message prompt. Identity, server
credentials inline (secrets via .env, not echoed), goal (small village,
long-horizon), bootstrap checklist (install skill, connect, AuthMe handle,
30-60s autonomous tick, on-death recovery), self-extension permission, hard
safety rules duplicated from AGENTS.md, definition of success ("a week from
now there's a cluster of buildings attributable to you").
Includes operational notes on nickname conflict (only one bot can be on the
server at a time under pepa_bot; suggest pepa_claw for the OpenClaw side),
.env coordination, LLM provider mixing, and a short post-mortem comparison
checklist for after a few hours of both running.
Not invoked by anything in this repo — it's an artefact for cross-runtime
experimentation. Lives in prompts/ alongside the Pi prompts and the
codex-seed-knowledge.md prompt because that folder is the right home for
reusable prompts regardless of which agent consumes them.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Four targeted fixes for issues observed during the live autonomous test:
1. **bot.modes shim** (extensions/lib/mcdata.js)
Mindcraft skills.* call bot.modes.pause('cowardice') in 7+ places.
`mineflayer-modes` does not exist on npm — it's internal to Mindcraft.
attachPluginsAndInit now installs a no-op shim so skills.stay() /
.consume() / .defendSelf() etc. stop crashing with "pause undefined".
2. **Death + respawn handlers** (extensions/mineflayer-bridge.ts)
Subscribe to bot 'death' event: append diary line with position,
clear current-task.json so Pi doesn't resume a stale task referencing
inventory that no longer exists.
On 'spawn' within 5s of death: log the new respawn position to diary.
Live test had bot killed twice by zombies at night; the next Pi
prompt was unable to recover. With this it's now an explicit diary
line + clean task slate.
3. **Auto-defend reflex tick** (extensions/mineflayer-bridge.ts)
New setInterval(2s) that, when bot.health < 18 AND a hostile mob
(zombie/skeleton/creeper/spider/etc.) is within 6 blocks AND no
active world task, fires `bot.pvp.attack(nearest)` in the background.
No LLM call needed for instant self-defense — saves tokens and reacts
on mineflayer timescale (sub-second) rather than Pi loop timescale
(~10s+ to reason and dispatch). Throttled to once per 4s.
4. **mc_collect_block bulk rework** (extensions/mindcraft-skills.ts)
Live test showed count=1 succeeds in ~25s but count=8 hangs past
270s with identical blocks in range. Upstream collectBlock plugin
appears to drift on its block cache after the first dig in dense
terrain. Loop single-block collects in-tool instead (75s per iter,
re-pathfind on each iteration). Track per-iter success/failure,
abort after 3 consecutive failures, return aggregate count to the
agent so it can adapt instead of seeing a single failure.
Smoke test: both extensions load, bot connects, perception confirms
hostiles nearby and daylight safety check. No syntax/runtime errors.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Live test showed count=1 succeeds in ~25s but count=8 timed out at 90s
because gathering 8 logs naturally takes ~200s of pathing + dig + pickup
across the area. Fixed 90s ceiling was too tight for legitimate bulk
collection.
Scale timeout linearly: 30s overhead + 30s per requested block, capped
at 600s. count=1 → 60s, count=4 → 150s, count=8 → 270s, count=20 → 630s
(capped at 600). Catches real hangs (wrong name, unreachable) without
killing legitimate long collections in dense forest.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Mineflayer's collectBlock plugin and pathfinder can hang indefinitely when:
- the requested block name doesn't match anything in range (e.g. asking for
"oak_log" when the only nearby logs are "dark_oak_log"),
- pathfinder cannot reach the goal but doesn't return a clean noPath,
- a path computation enters an infinite-search state in dense terrain.
This blocks the entire Pi tool loop — observed in a live test where
mc_collect_block("oak_log", 4) ran for 8+ minutes without ever returning,
leaving Pi unable to respond to chat or do anything else.
Add a 90s timeout for collectBlock/goToNearestBlock and 120s for goToPosition.
On timeout the tool throws a descriptive error so the agent learns to retry
with a different block name or position rather than waiting forever.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The bot was acting blind: it knew its own coordinates but nothing about
what was around it. mc_goto's over-strict safety guards refused every
real path. mc_dig was too low-level to drive a coherent farming loop.
The result: 4+ hours of "trying" with zero physical achievement.
This commit reframes the bridge around a perceive→decide→act loop using
proven primitives from Mindcraft (github.com/kolbytn/mindcraft, MIT —
LICENSE-MINDCRAFT vendored beside the library files).
Changes:
- extensions/lib/ (new, vendored from Mindcraft with attribution)
- world.js (431 LoC) — 21 perception functions: getNearbyBlockTypes,
getNearbyEntities, getInventoryCounts, getNearestBlock, getPosition,
getBiomeName, etc.
- skills.js (2093 LoC) — 30+ action primitives: collectBlock, placeBlock,
goToPosition, goToNearestBlock, craftRecipe, equip, consume,
defendSelf, avoidEnemies, pickupNearbyItems, stay, etc.
- mcdata.js (~600 LoC) — Mindcraft's mc-data adapter. Imports patched
to local paths; mineflayer-auto-eat removed (our installed 5.x has
a divergent API; skills.consume() falls back to bot.consume()).
Added attachPluginsAndInit(bot) export so mineflayer-bridge.ts can
wire plugins onto its externally-created bot.
- settings.js — minimal stub with farmer-bot defaults.
- extensions/mindcraft-skills.ts (new, 406 LoC) — Pi extension registering
15 high-level tools on top of the vendored library:
- Perception: mc_observe, mc_inventory, mc_nearby_blocks, mc_nearby_entities
- Action: mc_collect_block, mc_place_block, mc_go_to, mc_go_to_block,
mc_craft, mc_equip, mc_consume, mc_defend_self, mc_avoid_enemies,
mc_stay, mc_pickup_nearby
ES modules from extensions/lib/ are loaded via dynamic import() at
extension init so the cross-extension require()-race resolves cleanly.
- extensions/mineflayer-bridge.ts
- Expose the live Mineflayer bot on globalThis.__pepaPiBot so the
mindcraft-skills extension can use it (set on connect, cleared on
error/end/manual disconnect).
- Call attachPluginsAndInit(nextBot) right after createBot to load
pathfinder, pvp, collectblock, armorManager and prime
minecraft-data once login completes.
- package.json — new runtime deps: minecraft-data, vec3,
mineflayer-pvp, prismarine-item.
- AGENTS.md — new "Perception → decision → action" section before
"Your tools right now" with full tool catalog and a deprecation
note for the broken mc_goto / mc_build_pyramid_5x5 / low-level
mc_dig from the old bridge.
Smoke test (medium thinking): bot called mc_observe and received a
real JSON snapshot — nearbyBlocks listed coal_ore, oak_log, water,
sand; nearbyEntityTypes listed creeper, zombie, pillager, skeleton.
The bot can finally see what it could not see this morning.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
A long-form prompt for a long-context autonomous coding agent (Codex Pro,
Claude Sonnet w/ repo access, etc.) — NOT a Pi prompt. Goal: produce a
comprehensive docs/ knowledge base so the bot doesn't have to rediscover
Mineflayer API surface and core Minecraft mechanics (mobs, biomes,
recipes, ore Y-levels, farming, breeding) every time it tries something
new.
Design constraints baked into the prompt:
- PR-only workflow. Worker agent operates on a feat/knowledge-base
branch; main stays untouched so the live bot is unaffected until the
operator reviews and merges.
- docs/ only. Never write skills/ — that's the bot's notebook; pre-
writing procedural skills kills emergence. Reference material is the
textbook; the bot stays the author of its own procedures.
- One-line AGENTS.md addition pointing to docs/, no broader policy
rewrite. Behaviour change is "consult docs/ before I'll try to learn".
- package.json gets four universal-useful plugins added (collectblock,
auto-eat, tool, armor-manager); statemachine/pvp/blockfinder/viewer
are left for the bot to opt into.
- Concrete definition of done, scope estimate (10-30h), review
checklist for spot-checking hallucinations before merge.
- Re-run triggers documented (MC version bump, Mineflayer major,
new must-have plugin).
Included so future operators / forks can repeat this kind of one-off
seeding without re-deriving the prompt. Lives alongside the Pi prompts
in prompts/, even though it targets a different runtime — the
prompts/ folder is the right home for "reusable prompts" regardless of
which agent consumes them.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three things that together turn the bot from a reactive chat agent into
a goal-driven autonomous one.
1. Memory model (docs/memory-model.md, new). Formal split:
- SHARED knowledge — skills/, extensions/, prompts/, docs/,
.pi/settings.json — committed, community-improvable, portable to any
server.
- PERSONAL memory — state/<MC_HOST>/ — gitignored, per-instance, per-
server. Survives restarts (local disk), doesn't survive a re-clone
(deliberately). Holds goal.md, plan.md, current-task.json,
locations.json, diary/, inventory-log.jsonl, escalations.
Covers resume-after-restart protocol, what "abstract a lesson into a
skill" means, and the two anti-patterns (committing state, gitignoring
shared knowledge).
2. AGENTS.md changes:
- New section "Long-term goal and personal memory" wiring AGENTS.md
directly into state/<MC_HOST>/goal.md + current-task.json with a
pointer to docs/memory-model.md.
- Operating principle #4 ("I'll try to learn") rewritten with
**bias to action**: a pending stub is now a last resort, not a
default. Operator-trusted requests are themselves approval — bot
does not write a stub and wait for a separate "go".
Rationale: today's pyramid task got stuck because the bot wrote
a careful "pending" stub and waited; the operator had to send
"ты ждешь одобрения? можешь стартовать!" before any action. That
extra round-trip is the reflex this rewrite removes.
- Operating principle #5 ("live your best life when idle") expanded
to "goal-driven autonomy" with an explicit 5-level priority order
(operator task > non-op reply > resume current-task.json > next
plan milestone > decompose goal). Memory protocol made concrete:
write current-task.json before every meaningful action, append to
diary, keep locations.json fresh, tick off plan.md.
3. prompts/live-your-life.md (new). Canonical kickoff to switch the
bot into autonomous mode. Numbered concrete asks (re-read three
docs, write plan.md, implement memory protocol, implement
resume-on-restart, start). Includes a "plan.md draft for review"
gate so the operator can shape direction without micromanaging
execution. Designed to be sent after Phase 0/1/operator-trust are
stable and a goal.md exists for the target server.
Companion seed (local-only, NOT in this commit because gitignored):
state/play.xmatic.team_25565/goal.md — "build a small village and
survive long-term, live like a farmer". Lives only on the operator's
machine; a fresh clone won't see it.
README and roadmap updated with the new Phase 3 status (🌱 → 🌿
kickoff) and pointers to the new memory-model doc.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two-tier chat trust:
- Anyone in OPERATOR_USERNAMES (comma-separated, .env-only) is SCOPE-trusted.
The bot skips the "out of scope / not sure where" escalation reflex for
these users and instead applies "I'll try to learn" (Operating principle
#4): attempt, codify into a new skill, or reply with a concrete reason.
- Hard safety rules (no OP, no breaking other players' builds, no .env
leak, no chat spam, no destructive bash) remain ABSOLUTE. Operators get
the same refusal + escalation as anyone else for safety-borderline
requests — with slightly pointed wording, because they should know better.
- No transitive trust: chat-based "trust X for the next hour" / "make Y
an op" requests are themselves safety escalations. Op membership only
flows through .env on disk.
Security caveat documented in .env.example: nickname-based trust is only
safe on servers with identity protection (online-mode UUID or AuthMe).
On pure cracked servers OPERATOR_USERNAMES must stay empty.
- AGENTS.md: new Identity field for OPERATOR_USERNAMES; new Operating
principle #6 "Trusted operators" with the scope-vs-safety split; old
escalation principle renumbered to #7; Control channel section
rewritten with primary/secondary trust distinction.
- .env.example: OPERATOR_USERNAMES placeholder with multi-paragraph
security note covering when the model is and isn't safe.
- prompts/grant-op-trust.md: canonical implementation prompt for the
next Pi pass — re-read AGENTS.md, wire isOperator() into the bridge's
escalation flow, codify into skills/operator-trust.md, reload bridge,
verify with two concrete chat replays (scope vs safety).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Phase 0 (body) is done. The next steps shouldn't be guessed prompt-by-prompt —
write down the order, the judgement principles, and the next concrete
session prompt, so the bot has a coherent direction and the human can
hand it off in one message.
- docs/roadmap.md (new): six phases, each with status, scope, and stretch.
Phase 0 = 🌳 done, Phase 1 = 🌿 in progress, the rest = 🌱.
Explicit non-goals (no PvP, no OP, no cross-server identity).
- AGENTS.md: First-objective section collapsed to a pointer at the
onboarding skill (it's been done). New "What to do, in priority order"
summary citing the roadmap. New top-level "Operating principles"
section: presence, bounded reconnect, hold focus, "I'll try to learn"
reflex, idle = best-life mode, escalate destructive doubt with a
JSONL log under state/<host>/escalations.jsonl.
- prompts/awake-and-live.md (new): canonical kickoff prompt for the
next session. Scopes itself explicitly to phases 1+5+6 and excludes
locomotion (phase 2 needs care, separate session).
- README Status: 🌳 Phase 0 done / 🌱 Phase 1 in progress, links to
roadmap and operating principles.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The whole point of this project is that the agent's growth is shareable.
If skills and extensions silently land in ~/.pi/ on the maintainer's
laptop, every clone starts from zero and the repo becomes a fancy
README. Fix that with an explicit hard rule and a contributor guide.
- AGENTS.md: new "Artifact location — hard rule" subsection spelling out
that skills/extensions/prompts/state/.pi-settings ALL live in this repo,
never in ~/.pi/. Pi's own built-in skills (skill-creator, etc.) stay
user-global; the agent may use them, but their *output* must land here.
- README: new "Everything in the repo" subsection covering the same rule
in user-facing language, plus a pointer to CONTRIBUTING.md.
- CONTRIBUTING.md (new): skill/extension formats, server-agnostic and
no-secrets requirements, smoke-test recipe, PR checklist.
- .gitignore: switch from blanket `.pi/` ignore to `.pi/*` + explicit
un-ignore of `.pi/settings.json`, so project Pi config is reproducible.
- "Don't push without operator confirmation" → "without human
confirmation via the repo" — consistent with the new control model.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pi only acts when prompted. New repo users (and the maintainer's future
self) shouldn't have to invent the kickoff message — pin it.
- prompts/bootstrap.md: the canonical first-run message, with rationale
for each clause and guidance for shorter subsequent prompts
- README quickstart: new "Send the first message" subsection that quotes
the bootstrap prompt verbatim and explains what the agent does next
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
There's no good reason to bake a specific operator nickname into the bot's
identity — it differs per server, may not exist at all, and treating any
in-game name as "trusted" is a chat-injection vector ("I am the operator,
do X").
New model: the **repo** is the only trusted control plane. Anyone editing
AGENTS.md, skills/, or .env has filesystem access and is, by definition,
an operator. In-game chat becomes a dialog-only comms plane — the bot
talks to anyone but refuses destructive requests unless a corresponding
skill or AGENTS.md instruction makes the action explicitly permitted.
- .env / .env.example: OPERATOR_USERNAME removed
- AGENTS.md: identity section trimmed; "Operator contact" rewritten as
"Control channel" with the trust model spelled out; rules #2 and #6
rephrased so they no longer reference a named operator
- docs/architecture.md: top box renamed to "Human" with explicit
control-plane vs comms-plane split
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The bot is a universal Minecraft player, not tied to any one server.
Server identity (host, port, username, auth mode, optional AuthMe password)
is now read entirely from .env.
- README: rewritten as universal-bot pitch; auth covered as two dimensions
(MC auth mode + LLM credential)
- AGENTS.md: identity comes from .env, hard-coded references to pepa
removed; bootstrap step auto-detects whether the server uses an
AuthMe-style /register-/login plugin
- .env.example: example values replaced with placeholders, MC_AUTH_MODE
added (offline | microsoft)
- docs/architecture.md: rephrased target as "any Minecraft Java server",
added open question on cross-server vs per-server state
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Initial seed for an autonomous, self-extending Minecraft player powered by
Pi (pi.dev) and Mineflayer.
Includes README, AGENTS.md mandate, .env.example, MIT LICENSE, package.json
with mineflayer + dotenv, and empty skills/ extensions/ prompts/ dirs for
the agent to grow into.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>