Compare commits

3 Commits
Author SHA1 Message Date
mayatnikov 98e60eab5b chore(dev): add v0.4.1 sampling artifacts (live-eval + samples log)
Pre-cleanup snapshot before local removal.
2026-06-22 21:42:48 +03:00
mayatnikovandClaude Opus 4.8 cd63edfeaf feat(v0.4.1): make the Settlement Contract honest end-to-end
Patches each link of the closed-loop chain (world-truth -> invariant ->
dispatch -> worldDelta -> milestone) so the contract can no longer advance
on a lie or stall on an unreachable milestone, and surfaces the result on
the monitor.

- Unblock M6_lighting: add gather.coal producer (mirrors gather.stone,
  strict expectGain), register it, add the skill-graph node, and make
  curriculum.shelter.torch two-step (gather coal -> craft torch). craft.torch
  needed coal but no skill produced it, so the contract pinned on M6 forever
  and starved M7/M8/M9. One curriculum edit fixes both rails.
- M8 no longer falsely satisfied: build-shelter records locations.shelter
  only on real progress (setLocation moved below the no_progress guard).
- M2_bed made monotonic: sleepInBed writes locations.bed when the bot places
  its own bed, so M2 stays met after the carried bed item is consumed.
- Observability: new ink-free tui/format.js helper renders per-tick
  state / firing rail / active skill / blocked prerequisite / stall reason
  in the monitor header (fields bot.js already computes but never showed).
- Harden the valid-skill-id guardrail: skillRegistryPrompt preserves the
  "NEVER invent" footer when truncating (a growing registry was dropping it),
  and fix the stale "tech-tree > autonomous" reflex chain in the escalation
  prompt.

Tests: 494/494 passing; new build-shelter / invariants / format suites plus
skill-graph, curriculum, skill-registry cases. lint-patch clean. Deferred
audit findings recorded in plans/v0.4.0-vnext.md (local).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-29 12:33:45 +03:00
mayatnikovandClaude Opus 4.8 5613f75a77 chore(v0.4.1): open branch — disable auto-improve self-patcher by default
Carry the uncommitted off-switch into v0.4.1 and bump version to 0.4.1.

- runtime/auto-improve.js: PEPA_AUTO_IMPROVE=off skips the self-patcher,
  which committed LLM diffs and checked out branches (observed 2026-05-28
  checking out a stale local `main`). Direction is operator-drained
  improvement_requests, not auto-apply — proposals still written to disk.
- package.json: 0.4.0 -> 0.4.1

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-29 11:17:12 +03:00
21 changed files with 1052 additions and 16 deletions
+127
View File
@@ -0,0 +1,127 @@
# pepa-pi-bot — live evaluation run
**Date:** 2026-05-29 · **Branch:** `v0.4.1` (pkg 0.4.1, ahead 1 of `origin/v0.4.1`)
**Operator agent:** Claude Code (coordinator + watcher + analyst, single session)
**Monitoring window:** 60 min from confirmed connect.
> Constraints honored: no branch/worktree/commit/push/PR; no source edits; secrets never printed;
> single bot instance; chat never used as a control plane; server config untouched.
---
## 1. Run setup
| Field | Value |
|---|---|
| Bot already running at start? | **No**`ps` showed `NO_BOT_PROCESS`, `tmux ls` → no sessions, no stale `bot.sock`/`supervisor.pid`/`auto-patch.lock`. |
| Started by this run? | **Yes**`tmux new-session -d -s pepa-live-eval -c <repo> 'PEPA_AUTO_IMPROVE=off npm run bot'`. |
| tmux session | `pepa-live-eval` |
| Launch command time | 2026-05-29 **09:50:43Z** (12:50:43 MSK) |
| Confirmed connect (T0) | 2026-05-29 **09:50:46Z**`mc: spawned at (606.46, 51, 88.31)` as `pepa_bot` v1.21.4 |
| Planned window end | ~2026-05-29 **10:50:46Z** (13:50:46 MSK) |
| auto-improve self-patcher | **OFF** — log: `auto-improve: disabled via PEPA_AUTO_IMPROVE=off — proposals written but not auto-applied` (branch-default behaviour; protects repo from autonomous commits during eval). |
| State dir | `state/play.xmatic.team_25565/` · log `logs/2026-05-29.log` |
| Sampler | `dev/v0.4.1/sampler.sh``dev/v0.4.1/samples-2026-05-29.log` (snapshot every 30s, 5-min chunks) |
**Pre-run baseline (skill-metrics, all-time cumulative) — the headline failure rates going in:**
- `survive.pillar-up` 0 ok / **199 fail** (`no_progress`) — never succeeds.
- `recovery.tunnel-out` 38 ok / **187 fail** (`wedged`).
- `village.relocate` 0 ok / **6 fail** (`stuck_in_place`).
- `explore.far` 2208 ok / 1536 fail (`timeout`); `gather.logs` 55 ok / 122 fail.
- `craft.planks` 1 ok / 0 fail. world-journal baseline = 14 lines. knowledge.db: 41 deaths (all ≤05-27), 3 open improvement_requests (incl. id6 "no reliable un-wedge skill").
- **Last run ended (05-28 09:43Z) boxed in stone at ~(606,51,90)** thrashing pillar-up/tunnel-out/relocate at 0-block progress — and **today the bot resumed at the identical spot (606,51,88)**.
---
## 2. Server health
- `docker ps`: container **`minecraft`** Up 25h (**healthy**), ports `25565`, `8100`.
- `mc-monitor status`: `version=Paper 26.1.2 online=0 max=10` (online=0 before bot connect — consistent).
- Paper 26.1.2 (protocol 775) + ViaVersion/ViaBackwards; offline mode; world spawn `-451 74 -783`, `respawn_radius 0` (operator-set 05-28, **not modified by this run**).
---
## 3. Timeline checkpoints
Position truth = `current-task.json.position` + `reflex: idle: hp/food/pos` heartbeat; progress truth = `world-journal.jsonl` growth + inventory delta (NOT log "ok" strings — pepa logs are known to lie).
| # | Time (UTC) | Position (x,y,z) | hp/food | runtimeState / active skill | milestone / storyline | world-journal Δ | last result / no-progress | verdict |
|---|---|---|---|---|---|---|---|---|
| C1 | 09:5109:55 | (606,47,88)→(610,45,89) — pinned | ~320 → falling | recovering · `survive.pillar-up``wander``dig-in` | storyline 1 orient_self / M0 | 0 | `pillar-up → no_progress` ("blockUpdate did not fire within 5000ms"); `tunnel-out`/escape-pit "moved 0.00" | **REGRESSION** — identical stone-box wedge death-spiral as 05-28 |
| ⚑ | **09:55:38** | **OPERATOR TELEPORT** | — | — | — | — | `spreadplayers 1003 439 0 8 false pepa_bot` → server "Spread 1 entity around 1003.5,439.5"; bot `forced move → (998,64,436)` | **INTERVENTION** (operator-directed) |
| † | 09:56:00 | (988,64,436) | 3.5→0 | death | — | 0 | `mc: died` cause=hostile **zombie** (id=54); arrived with ~3.5 hp from the wedge-site skeleton → respawn at world spawn | death (post-teleport) |
| C1 | 09:57 | **(-450,72,-782)** base/spawn | ~11 | working · `explore.far` (advisor→`survive.flee`) | storyline 2 first_wood | 0 | `gather.logs → no_target` ("no reachable log within 64 blocks"); zombie near | **NEUTRAL** — unstuck, alive, mobile on surface, seeking wood |
| C2 | 09:5710:04 | base → walking N: (-453,72,-781) → (-449,60,-703) (~79b N) | died→20→~20 | working · `explore.far` / advisor `survive.flee` | storyline 2 first_wood / M0M1 | 0 | **3 deaths in 3.5 min**: zombie@base (id55 09:57), skeleton@(-465,51) (id56 09:59); then alive+mobile 09:59→10:04; `gather.logs → no_target` (no trees ≤64b) | **MIXED** — mobility restored (real horizontal Δ), but 3 deaths + world-journal Δ=0 (zero tech-tree progress); base is hostile + treeless |
| C3 | 10:0510:10 | walking N: (-449,62,-516) → (-462,62,-53) (~460b N; ~730b N total from base) | healthy (no plunge) | working · `explore.far` (brief `flee from drowned`) | storyline 2 first_wood / M0M1 | 0 | `explore.far → done moved~46` ×many (real travel); `dig-in fail "unsafe below: water"`, `sleep fail "no bed"`; **0 new deaths** | **POSITIVE mobility / NEGATIVE progress** — sustained long-distance travel, survived; still no wood in ~730b (treeless corridor / detection range) |
| C4 | 10:1110:16 | (-462,61,88) → (-467,62,558) (~470b); then respawn → base (-450,72,-782) | died→20 | working · `explore.far``attack drowned``flee` | storyline 2 first_wood / M0M1 | 0 | `attack drowned ok` ×2 then `flee from drowned fail "No path"`; **4th death id57 drowned @(-467,62,558)** 10:16:00 → respawn base, resumes explore.far | **UNPRODUCTIVE LOOP** — confirms explore→die→respawn cycle; 4 deaths total, still Δ0 (no wood) |
| C5 | 10:1710:22 | oscillating ~15b around base: (-439,70,-778) ↔ (-455,70,-769) | died→20 | recovering · `explore.far`(fail)→`tunnel-out`/`pillar-up` | storyline 2 first_wood / M0M1 | 0 | `explore.far → failed`; tunnel-out `moved 37b dug`; **5th death id58 skeleton @(-423,58,-782)** near base 10:19:54 | **REGRESSION** — degraded from long-march to short-range thrash + death at base; 5 deaths; still Δ0 |
| C6 | 10:2310:28 | long-march again: (-448,62,-735) → (-448,61,-219) (~516b, x≈-448 corridor) | healthy | working · `explore.far` ×many | storyline 2 first_wood / M0M1 | 0 | `explore.far → done` repeatedly; **0 new deaths**; run-total dispatch mix: explore.far ×64, gather.logs only ×3 (all `no_target`) | **NEUTRAL mobility / NEGATIVE progress** — confirms explore.far-dominated corridor wandering (base↔lake), never detects wood |
| C7 | 10:2910:38 | corridor to z+544 then respawn → base; now (-436,65,-780) | died→20 | recovering · `explore.far``recovery.tunnel-out` | storyline 2 first_wood / M0M1 | 0 | **6th death id59 guardian @(-445,59,72)** 10:31 (corridor crosses ocean/monument); back to base thrashing tunnel-out | **REGRESSION/loop** — 6 deaths (now incl. guardian); run z-range -782↔+544 (~1326b corridor), no wood anywhere |
| C8 | 10:3910:48 | oscillating near base: (-445..-438, 5965, -780) | healthy | working · `explore.far` near base | storyline 2 first_wood / M0M1 | 0 | **0 new deaths** (~17 min survived since guardian); still no wood/craft/place; 6 deaths total | **NEUTRAL** — survived but zero progress; loop persists near base |
| C9 | 10:4810:52 | base: `explore.far``dig-in``tunnel-out` @ (-441,63,-780) | healthy | recovering · `recovery.tunnel-out` | storyline 2 first_wood / M0M1 | 0 | `tunnel-out N/E failed: dig(stone) timed out after 25s` (×many); 0 new deaths | **REGRESSION** — window ends in the SAME wedge/dig-timeout loop it began in |
**Window closed 10:52:00Z (~61 min after T0). Run total: 9 sampler chunks, 6 deaths, world-journal Δ=0, villageScore never left M0/M1.**
Run-wide dispatch outcomes: `explore.far` 65 ok / 14 fail (hollow — pure travel) · `survive.dig-in` 7/11 · `survive.pillar-up` **0/8** · `sleep` **0/7** · `gather.logs` **0/6** (all `no_target`) · `survive.flee` **0/4** · `village.relocate` 0/1 · `recovery.escape-pit-safe` 0/1 · combat: attack drowned 2 ok, attack creeper 1 ok, flee zombie/drowned 1 ok each. No milestone/contract advance line ever logged.
---
## 4. Progress assessment
**Verdict: NO survival/village/contract progress.** Over the full 60 min the settlement contract never advanced off **M0/M1** and `world-journal.jsonl` stayed at **14 lines (Δ=0)** — zero logs chopped, zero blocks placed, zero food acquired, no base/shelter/chest/bed written. No milestone completed; villageScore did not move.
**What did improve (post-teleport):** the operator teleport broke the initial stone-box wedge, and for ~40 min the bot showed that **locomotion and reflex are functional**`explore.far` returned 65 ok and the bot covered a ~1326-block corridor, fought/fled mobs, and survived ~17-min stretches. So pathfinding, movement, mob reflexes and the (honest) contract telemetry all work.
**What did not:** that mobility converted into **futile corridor wandering** (base ↔ ocean/monument at x≈-448) with no resource acquisition, **6 deaths**, and the window **ended back in the same wedge/dig-timeout loop at base** it started in. The `explore.far` "successes" are hollow — lots of `ok` with zero world change, exactly the "logs say ok while nothing advances" trap; the v0.4.1 honest contract correctly reports Δ=0.
**Bottom line:** the bot is alive and mobile but **structurally unable to bootstrap** — it cannot get the first wood, cannot secure its respawn, and cannot dig/place its way out of a wedge on this server. These are bot-side defects, not a location problem; the teleport confirmed that relocation alone does not help (it died at the destination and respawned right back at the bad base).
## 5. Interventions
**1× teleport — operator-directed.** At 09:55:38Z the operator explicitly instructed "move the bot now." Evidence already justified it independently: the bot had resumed at the identical 05-28 stone-box location and, across chunk 1 (09:5109:55), was pinned at (606,47,88)→(610,45,89) cycling `survive.pillar-up → no_progress` ("blockUpdate did not fire within 5000ms") and escape-pit/tunnel-out at "moved 0.00 horizontally", world-journal Δ=0 — a verbatim repeat of the un-winnable wedge loop (pillar-up 0/199, tunnel-out 38/187, relocate 0/6 lifetime).
- **Command class:** `spreadplayers` (surface-safe, no explicit-Y air drop). Exact:
`execute in minecraft:overworld run spreadplayers 1003 439 0 8 false pepa_bot` via `docker exec -u 1000 minecraft mc-send-to-console`.
- **Server ack:** `Spread 1 entity/entities around 1003.5, 439.5`.
- **Before:** wedged at ~(606,47,88), online=1, ~3.5 hp (skeleton had been hitting it while wedged).
- **After (immediate):** `forced move 518b → (998,64,436)` (surface, y=64). Then **21s later the bot was killed by a zombie** at (988,64,436) — it arrived already at ~3.5 hp — `mc: died … cause=hostile zombie (id=54)`. Respawn point = world spawn ⇒ it respawned at **(-450,72,-782)** = the operator-chosen base in `locations.json`.
- **Net result:** out of the stone-box death-spiral; now alive (~11 hp post-respawn), mobile on the surface at its own base, running `explore.far`/`survive.flee`/`gather.logs`. The destination (1003,439) was reached for ~21s but not held; the bot's respawn anchored it at its designated base instead. **No second teleport issued** — re-dropping it into the spot where a zombie just killed it would be reckless, and the base is its intended settlement site.
- **Note:** `spreadplayers` placed it on a valid surface block (no fall damage); the death was a pre-existing-low-HP + hostile-mob outcome, not a teleport placement fault.
## 6. Failure patterns
Evidence first, then code-grounded root cause (from a parallel read of the runtime source — see `dev/v0.4.1/` analysis).
1. **Wedge / dig-timeout loop (opened and closed the run).** Symptoms: `survive.pillar-up → no_progress "Event blockUpdate:(x) did not fire within 5000ms"`, `recovery.tunnel-out … "dig(stone) timed out after 25s"` / `"Digging aborted"`, `"dug but moved only 0.00 horizontally"`. Run counts: pillar-up 0/8, tunnel-out fails dominant. **Root cause (corrects the brief's `canDig=false` assumption — runtime sets `canDig=true`): a protocol-level break.** Under ViaVersion/ViaBackwards (1.21.4 client ↔ Paper 26.1.2), `bot.placeBlock`/`bot.dig` await a `blockUpdate:<pos>` confirmation packet that the pinned protocol never delivers (mineflayer `place_block.js`/`digging.js`), so places time out and digs hang→abort. **Every escape skill (pillar-up, tunnel-out, dig-in, escape-pit-safe) is built on these two broken primitives**, so a boxed-in bot has no working way out.
2. **No-wood deadlock (the master bottleneck).** `gather.logs` 0/6, all `no_target "no reachable log within 64 blocks"`. **Root cause:** `storyline.first_wood.suggestSkill` (`runtime/goal/storyline.js:173-181`) gates `gather.logs` on a **16-block** `nearbyBlocks` scan (`perceive.js:65`) while the chopper actually reaches **64** (`actions.js:456`) → in the 1664 band the gate sees `trees===0` and emits `explore.far` instead. `explore.far`'s `searchFor:"logs"` arg is **dead code**; direction comes from a "leanest quadrant" heuristic that steers *away* from catalogued trees, into the ocean; each call only commits ~48 blocks. M1 (wood tools) is the lowest unmet contract gate and `gather.logs` is its only action ⇒ **the whole tech tree cannot bootstrap.** (The old ViaBackwards findBlock name-vs-id bug is already fixed — not the cause.)
3. **Death→respawn loop.** 6 deaths (zombie×2, skeleton×2, drowned×1, guardian×1); every death respawns at world spawn **(-451,-783)** = the operator base, which is treeless/underground/water-adjacent. **Root cause:** the bot **never sets a respawn point** (no bed — bed is gated *below* M1 wood; no `/spawnpoint`), and there is **no "return to base" navigation** anywhere. Only food carries `urgency` in the contract; deaths and wedging have **no preemption path**, so the bot has no way to break out.
4. **Weak combat + hazardous exploration.** Empty inventory ⇒ **fists-only** melee (`actions.js:132`), no armor. Flee window too narrow for ranged mobs (fires at ≤8 m; skeletons shoot from farther) → eats arrows while `explore.far` keeps walking. `explore.far` has **no water/night/gear guard**, so it blind-walks into the ocean/monument at night → drowned + guardian deaths. `survive.dig-in` refused ("unsafe below: water") and would have failed the cap anyway (pattern 1).
5. **Hollow success / honest contract.** `explore.far` 65 `ok` with **zero** world change is the "logs lie" trap; the v0.4.1 honest worldDelta/contract correctly keeps villageScore at 0 — the instrumentation is trustworthy, the behaviour is not.
## 7. Follow-up recommendations
Prioritized, code-grounded. **None applied this run** (no source edited per constraints) — captured for follow-up.
**P0 — make dig/place succeed (or self-verify) under ViaBackwards.** In `runtime/skills/pillar-up.js` (`placeBlockAtFeet`), `runtime/skills/dig-in.js` (`attemptCap`), `runtime/skills/recovery-tunnel-out.js` (`digOne`): on `blockUpdate did not fire` / `dig … timed out` / `Digging aborted`, **re-read `bot.blockAt(pos)` after a ~300600 ms settle and treat the op as successful iff the cached block actually changed** instead of throwing. Likely converts much of pillar-up 0/199 and tunnel-out 149-fail into successes. Verify in-game (position-Δ / block-break), not by log strings.
**P0 — align the `first_wood` gate with the 64-block chopper reach.** `runtime/goal/storyline.js:173-181` (and `first_tools` 215-220): try `gather.logs` whenever the bot has no wood and fall back to `explore.far` only on a real `no_target` result, rather than on the 16-block precheck. Restores the wood loop in any biome with trees within 64.
**P0 — secure the respawn point.** In `runtime/bot.js` spawn/death wiring: when standing at a safe base, run `/spawnpoint` once; and add a pre-M1 "secure spawn / first-wood reachable" guard so deaths stop teleporting the bot back to the treeless world-spawn.
**P1 — make exploration tree-seeking and ocean-avoiding.** `runtime/skills/explore-far.js`: consume the (currently dead) `searchFor` arg; bias the cardinal choice with `biome-affordances.js` (`hasTrees && !isUnlivable`), hard-avoid ocean headings, and down-rank `leanestQuadrant`. Mirror in `runtime/skills/relocate.js`. Add a hazard/time/gear guard (no blind 48-block walk into water or at night without gear), and widen flee distance for ranged hostiles in `runtime/reflex.js:237`.
**P1 — add a death/wedge urgency override to the contract.** `runtime/goal/contract.js`: spike urgency after N deaths or repeated wedge-detector fires → route to relocate-to-treed-biome / dig-to-surface instead of re-suggesting the unreachable `gather.logs`. Today only food has urgency.
**P2 — housekeeping.** (a) Demote radius-16 `nearbyBlocks` dispatch gates elsewhere (storyline crops/beds/storage, curriculum) or widen `perceive.js:65`. (b) Reconcile the two state dirs (`state/play.xmatic.team` vs `…_25565`) and fix the empty `{"locations":[]}` shape (`runtime/locations.js`). (c) Give `recovery.escape-pit-safe` a non-dig/non-place fallback for the empty-inventory wedge (it currently just surrenders).
## 8. Final state
- **Bot: STILL RUNNING.** `supervisor.js` pid **83544**, `bot.js` pid **83545**; tmux session **`pepa-live-eval`** (window created 12:50:45 MSK). auto-improve **OFF** (`PEPA_AUTO_IMPROVE=off`).
- **Latest observed (10:52:00Z):** `recovery.tunnel-out in_progress` at **(-441, 63, -780)** near base, `tunnel-out … dig(stone) timed out after 25s` — i.e. it closed the window in the same wedge/dig-timeout loop it opened in.
- **Run totals:** 6 deaths · world-journal Δ=0 · villageScore M0/M1 (no advance) · 1 operator teleport.
- **Left running, not stopped** (operator runs/stops the bot himself). To stop: `npm run stop` (then wait ~30 s before relaunch). Sampler artifacts: `dev/v0.4.1/samples-2026-05-29.log`, baseline `dev/v0.4.1/skill-metrics-baseline.json`.
- **Repo untouched:** no branch/worktree/commit/push/PR; no source edited; no secrets printed; server config unchanged (no world-spawn/op/gamerule/whitelist/restart). The only server-console action was the single `spreadplayers` teleport of `pepa_bot`.
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env bash
# Live-eval sampler for pepa-pi-bot. Runs ONE chunk then exits (so the agent is
# re-invoked between chunks to checkpoint + decide intervention).
# Args: $1=chunk-number $2=duration-seconds(default 300) $3=sample-interval-seconds(default 30)
# READ-ONLY: only reads bot state/logs; never writes into the bot's state dir.
set -u
D=/Users/timmy/Projects/pepa-pi-bot/state/play.xmatic.team_25565
OUT=/Users/timmy/Projects/pepa-pi-bot/dev/v0.4.1/samples-2026-05-29.log
CHUNK="${1:-0}"
DUR="${2:-300}"
INT="${3:-30}"
LOG="$D/logs/$(date -u +%F).log"
WJ="$D/world-journal.jsonl"
wjcount() { wc -l < "$WJ" 2>/dev/null | tr -d ' '; }
WJ_BASE="$(wjcount)"; WJ_BASE="${WJ_BASE:-0}"
task_line() {
node -e '
const fs=require("fs");
try{
const t=JSON.parse(fs.readFileSync(process.argv[1],"utf8"));
const p=t.position? [t.position.x,t.position.y,t.position.z].map(n=>Math.round(n)).join(","):"?";
process.stdout.write(`label=${t.label||"?"} status=${t.status||"?"} pos=(${p}) ts=${t.ts||"?"}`);
}catch(e){ process.stdout.write("label=? (no current-task)"); }
' "$D/current-task.json" 2>/dev/null
}
end=$(( $(date +%s) + DUR ))
{
echo ""
echo "########## CHUNK ${CHUNK} START $(date -u +%FT%TZ) (dur=${DUR}s int=${INT}s wj_base=${WJ_BASE}) ##########"
} >> "$OUT"
while :; do
now=$(date +%s); [ "$now" -ge "$end" ] && break
TS=$(date -u +%FT%TZ)
CT="$(task_line)"
HB=$(grep -aE 'reflex: idle: hp=' "$LOG" 2>/dev/null | tail -1 | sed -E 's/.*reflex: idle: //')
DISP=$(grep -aE 'dispatch: (\xe2\x86\x92|\xe2\x86\x90|->|<-)|skill: .* (\xe2\x86\x92|->) ' "$LOG" 2>/dev/null | tail -1 | sed -E 's/^([0-9T:.-]+Z) \[[a-z]+\] //')
STK=$(grep -aE 'pathfinder: stuck|wedged:|Digging aborted|stuck_in_place|no_progress|Took to long|silent_dig' "$LOG" 2>/dev/null | tail -1 | sed -E 's/^([0-9T:.-]+Z) \[[a-z]+\] //')
CONN=$(grep -aE 'mc: kicked|mc: connection ended|mc: spawned at|runtime: pepa runtime starting|child exited|died|respawn|disabled via PEPA_AUTO_IMPROVE|auto-improve: watching' "$LOG" 2>/dev/null | tail -1 | sed -E 's/^([0-9T:.-]+Z) \[[a-z]+\] //')
WJN="$(wjcount)"; WJN="${WJN:-0}"
WJL=$(tail -1 "$WJ" 2>/dev/null)
{
echo "--- ${TS} (chunk ${CHUNK}) ---"
echo " task : ${CT}"
echo " hb : ${HB:-<none>}"
echo " disp : ${DISP:-<none>}"
echo " stuck: ${STK:-<none>}"
echo " wj : lines=${WJN} delta=$(( WJN - WJ_BASE )) last=${WJL:-<none>}"
echo " conn : ${CONN:-<none>}"
} >> "$OUT"
now=$(date +%s); rem=$(( end - now ))
[ "$rem" -le 0 ] && break
if [ "$rem" -lt "$INT" ]; then sleep "$rem"; else sleep "$INT"; fi
done
echo "########## CHUNK ${CHUNK} DONE $(date -u +%FT%TZ) (wj_now=$(wjcount)) ##########" >> "$OUT"
+266
View File
@@ -0,0 +1,266 @@
{
"gather.logs": {
"ok": 55,
"fail": 122,
"lastTs": 1779952694275,
"lastCode": "timeout",
"lastDurationMs": 62051,
"totalDurationMs": 7620662
},
"wander": {
"ok": 120,
"fail": 400,
"lastTs": 1779960695691,
"lastCode": "done",
"lastDurationMs": 174520,
"totalDurationMs": 6269071
},
"explore.far": {
"ok": 2208,
"fail": 1536,
"lastTs": 1779961085424,
"lastCode": "timeout",
"lastDurationMs": 90021,
"totalDurationMs": 46115701
},
"recovery.tunnel-out": {
"ok": 38,
"fail": 187,
"lastTs": 1779961436417,
"lastCode": "wedged",
"lastDurationMs": 2588,
"totalDurationMs": 4106772
},
"attack zombie": {
"ok": 34,
"fail": 66,
"lastTs": 1779952608404,
"lastCode": "hostile_still_near",
"lastDurationMs": 3291,
"totalDurationMs": 190060
},
"flee from zombie": {
"ok": 4,
"fail": 94,
"lastTs": 1779951420083,
"lastCode": "timeout",
"lastDurationMs": 37053,
"totalDurationMs": 2830611
},
"attack drowned": {
"ok": 10,
"fail": 15,
"lastTs": 1779881719294,
"lastCode": "hostile_still_near",
"lastDurationMs": 3344,
"totalDurationMs": 40858
},
"flee from drowned": {
"ok": 0,
"fail": 64,
"lastTs": 1779888953259,
"lastCode": "timeout",
"lastDurationMs": 30089,
"totalDurationMs": 1914257
},
"survive.flee": {
"ok": 4,
"fail": 71,
"lastTs": 1779960760403,
"lastCode": "stuck",
"lastDurationMs": 11079,
"totalDurationMs": 1742016
},
"flee from skeleton": {
"ok": 2,
"fail": 65,
"lastTs": 1779948570425,
"lastCode": "timeout",
"lastDurationMs": 37011,
"totalDurationMs": 2033525
},
"flee from spider": {
"ok": 4,
"fail": 25,
"lastTs": 1779951627557,
"lastCode": "done",
"lastDurationMs": 7225,
"totalDurationMs": 815204
},
"attack skeleton": {
"ok": 11,
"fail": 9,
"lastTs": 1779948471101,
"lastCode": "no_target",
"lastDurationMs": 704,
"totalDurationMs": 45795
},
"flee from creeper": {
"ok": 3,
"fail": 44,
"lastTs": 1779948015270,
"lastCode": "timeout",
"lastDurationMs": 37025,
"totalDurationMs": 1368266
},
"attack creeper": {
"ok": 17,
"fail": 21,
"lastTs": 1779949854216,
"lastCode": "done",
"lastDurationMs": 2029,
"totalDurationMs": 41966
},
"flee from enderman": {
"ok": 1,
"fail": 21,
"lastTs": 1779952594115,
"lastCode": "timeout",
"lastDurationMs": 37020,
"totalDurationMs": 649095
},
"attack spider": {
"ok": 7,
"fail": 269,
"lastTs": 1779951473733,
"lastCode": "hostile_still_near",
"lastDurationMs": 3528,
"totalDurationMs": 54422
},
"attack enderman": {
"ok": 0,
"fail": 2,
"lastTs": 1779883311290,
"lastCode": "hostile_still_near",
"lastDurationMs": 3371,
"totalDurationMs": 4120
},
"flee from witch": {
"ok": 0,
"fail": 2,
"lastTs": 1779878325865,
"lastCode": "timeout",
"lastDurationMs": 30008,
"totalDurationMs": 60053
},
"survive.pillar-up": {
"ok": 0,
"fail": 199,
"lastTs": 1779961367632,
"lastCode": "no_progress",
"lastDurationMs": 12158,
"totalDurationMs": 5515785
},
"survive.acquire-food": {
"ok": 0,
"fail": 123,
"lastTs": 1779948857447,
"lastCode": "already_have",
"lastDurationMs": 1,
"totalDurationMs": 68883
},
"survive.sleep": {
"ok": 0,
"fail": 4,
"lastTs": 1779948392381,
"lastCode": "daytime",
"lastDurationMs": 0,
"totalDurationMs": 1
},
"explore.wander": {
"ok": 90,
"fail": 77,
"lastTs": 1779952509376,
"lastCode": "failed",
"lastDurationMs": 18316,
"totalDurationMs": 2556361
},
"diag.scan": {
"ok": 2,
"fail": 0,
"lastTs": 1779952108067,
"lastCode": "scan_done",
"lastDurationMs": 1175,
"totalDurationMs": 2764
},
"village.relocate": {
"ok": 0,
"fail": 6,
"lastTs": 1779961426942,
"lastCode": "stuck_in_place",
"lastDurationMs": 56464,
"totalDurationMs": 586374
},
"survive.scout-food": {
"ok": 1,
"fail": 44,
"lastTs": 1779949085516,
"lastCode": "already_have",
"lastDurationMs": 1,
"totalDurationMs": 326284
},
"survive.eat": {
"ok": 3,
"fail": 0,
"lastTs": 1779946551109,
"lastCode": "done",
"lastDurationMs": 1630,
"totalDurationMs": 4901
},
"eat": {
"ok": 3,
"fail": 0,
"lastTs": 1779946560105,
"lastCode": "done",
"lastDurationMs": 1637,
"totalDurationMs": 4896
},
"gather.wool": {
"ok": 0,
"fail": 15,
"lastTs": 1779951016664,
"lastCode": "no_path",
"lastDurationMs": 30030,
"totalDurationMs": 439630
},
"craft.planks": {
"ok": 1,
"fail": 0,
"lastTs": 1779950947695,
"lastCode": "done",
"lastDurationMs": 85,
"totalDurationMs": 85
},
"diag.physics": {
"ok": 3,
"fail": 0,
"lastTs": 1779952458860,
"lastCode": "done",
"lastDurationMs": 6835,
"totalDurationMs": 20477
},
"survive.dig-in": {
"ok": 4,
"fail": 6,
"lastTs": 1779961089100,
"lastCode": "no_progress",
"lastDurationMs": 672,
"totalDurationMs": 165764
},
"sleep": {
"ok": 0,
"fail": 2,
"lastTs": 1779961091425,
"lastCode": "other",
"lastDurationMs": 1,
"totalDurationMs": 3
},
"recovery.escape-pit-safe": {
"ok": 0,
"fail": 1,
"lastTs": 1779960794335,
"lastCode": "no_strategy",
"lastDurationMs": 1,
"totalDurationMs": 1
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "pepa-pi-bot",
"version": "0.4.0",
"version": "0.4.1",
"private": true,
"description": "An autonomous, self-extending Minecraft player powered by Pi and Mineflayer.",
"license": "MIT",
@@ -17,7 +17,7 @@
"tui:legacy": "tsx tui/tui.tsx",
"propose:apply": "node scripts/propose-apply.js",
"stop": "bash scripts/stop.sh",
"test": "node --test runtime/skills/contract.test.js runtime/skills/groups.test.js runtime/skills/compat.test.js runtime/skills/recovery-tunnel-out.test.js runtime/skills/pillar-up.test.js runtime/skills/dig-in.test.js runtime/skills/_common.test.js runtime/skills/flee.test.js runtime/skills/worlddelta.test.js runtime/curriculum.test.js runtime/social/social.test.js runtime/social/conversation.test.js runtime/social/chat-history.test.js runtime/social/reply-pi.test.js runtime/stuck-incident.test.js runtime/compat.test.js runtime/reflex.test.js runtime/base-site.test.js runtime/locations.test.js runtime/watch-filter.test.js runtime/world-journal.test.js runtime/scenario-memory.test.js runtime/critic.test.js runtime/skill-library.test.js runtime/skill-registry.test.js runtime/modes.test.js runtime/pathfinder-watchdog.test.js runtime/anti-loop.test.js runtime/services/inventory-ledger.test.js runtime/services/motion.test.js runtime/manifesto/needs.test.js runtime/manifesto/state.test.js runtime/goal/storyline.test.js runtime/goal/goal-manager.test.js runtime/goal/village-score.test.js runtime/goal/skill-graph.test.js runtime/awareness/events.test.js runtime/awareness/wedge-detector.test.js runtime/biome-affordances.test.js runtime/knowledge/knowledge.test.js runtime/llm/provider.test.js runtime/coach/postmortem.test.js runtime/coach/advice.test.js runtime/coach/reflect.test.js runtime/coach/fast-advisor.test.js runtime/coach/advisor-trigger.test.js runtime/coach/trigger-tuner.test.js runtime/persona/chatter.test.js scripts/edit-scope.test.js scripts/lint-patch.test.js"
"test": "node --test runtime/skills/contract.test.js runtime/skills/groups.test.js runtime/skills/compat.test.js runtime/skills/recovery-tunnel-out.test.js runtime/skills/pillar-up.test.js runtime/skills/dig-in.test.js runtime/skills/_common.test.js runtime/skills/flee.test.js runtime/skills/worlddelta.test.js runtime/skills/build-shelter.test.js runtime/curriculum.test.js runtime/social/social.test.js runtime/social/conversation.test.js runtime/social/chat-history.test.js runtime/social/reply-pi.test.js runtime/stuck-incident.test.js runtime/compat.test.js runtime/reflex.test.js runtime/base-site.test.js runtime/locations.test.js runtime/watch-filter.test.js runtime/world-journal.test.js runtime/scenario-memory.test.js runtime/critic.test.js runtime/skill-library.test.js runtime/skill-registry.test.js runtime/modes.test.js runtime/pathfinder-watchdog.test.js runtime/anti-loop.test.js runtime/services/inventory-ledger.test.js runtime/services/motion.test.js runtime/manifesto/needs.test.js runtime/manifesto/state.test.js runtime/goal/storyline.test.js runtime/goal/goal-manager.test.js runtime/goal/village-score.test.js runtime/goal/skill-graph.test.js runtime/goal/invariants.test.js runtime/awareness/events.test.js runtime/awareness/wedge-detector.test.js runtime/biome-affordances.test.js runtime/knowledge/knowledge.test.js runtime/llm/provider.test.js runtime/coach/postmortem.test.js runtime/coach/advice.test.js runtime/coach/reflect.test.js runtime/coach/fast-advisor.test.js runtime/coach/advisor-trigger.test.js runtime/coach/trigger-tuner.test.js runtime/persona/chatter.test.js tui/format.test.js scripts/edit-scope.test.js scripts/lint-patch.test.js"
},
"dependencies": {
"better-sqlite3": "^11.10.0",
+12
View File
@@ -17,6 +17,7 @@ const toolPlugin = toolPkg.plugin ?? toolPkg.default?.plugin ?? toolPkg.default
import { info, warn } from "./log.js";
import { digEscapeTunnel } from "./skills/recovery-tunnel-out.js";
import { findNearestBlockByName } from "./perception.js";
import { setLocation } from "./locations.js";
// Hard timeout wrapper. Mineflayer goals (pathfinder, pvp targeting) can hang
// when the goal is unreachable; without a ceiling the whole reflex chain stops.
@@ -364,6 +365,17 @@ export async function sleepInBed(bot) {
// have shifted to an adjacent slot for the bed's second half).
const placed = findNearestBlockByName(bot, BED_NAMES, { maxDistance: 4 });
if (!placed) return { ok: false, detail: "placed bed not found after placement" };
// M2 monotonicity: the bot just placed its OWN bed and the carried
// item is consumed, so bedSecured()'s carried-item branch no longer
// holds. Record the placed bed's location (mirrors choose-base /
// place-chest / build-shelter) so the locations.bed branch keeps M2_bed
// met and the contract stops looping gather.wool->craft.bed for a bed
// that already exists. Recorded before sleep — the bed is in the world
// regardless of whether sleeping succeeds; guarded so a store-write
// hiccup never breaks the sleep path.
try {
setLocation("bed", { x: placed.position.x, y: placed.position.y, z: placed.position.z, radius: 1, note: "placed bed" });
} catch {}
await withTimeout(bot.sleep(placed), 10_000, "bot.sleep(placed)");
return { ok: true, detail: { bedAt: placed.position, placed: true, name: carried.name } };
} catch (e) {
+9
View File
@@ -113,6 +113,15 @@ let pollTimer = null;
export function startAutoImprover() {
if (pollTimer) return;
// Off-switch: the self-patcher commits LLM-generated diffs and checks out
// branches, which can leave the working tree on the wrong branch mid-run
// (observed 2026-05-28: it checked out a stale local `main`). The research
// direction is operator-drained improvement_requests, not auto-apply — so
// set PEPA_AUTO_IMPROVE=off to keep proposals on disk without patching.
if (String(process.env.PEPA_AUTO_IMPROVE ?? "").toLowerCase() === "off") {
info("auto-improve", "disabled via PEPA_AUTO_IMPROVE=off — proposals written but not auto-applied");
return;
}
info("auto-improve", `watching ${PROPOSALS_DIR} (cooldown=${COOLDOWN_MS / 1000}s, max ${MAX_TOTAL_PER_HOUR}/hr)`);
pollTimer = setInterval(tick, 2000);
}
+1 -1
View File
@@ -805,7 +805,7 @@ function maybeAutoEscalate() {
`You are the escalation cortex for an autonomous Minecraft bot. The bot's`,
`script-driven reflex loop has produced no useful action for ${ESCALATE_AFTER_NOOPS} consecutive ticks`,
`(~${Math.round((ESCALATE_AFTER_NOOPS * config.tickIntervalMs) / 1000)}s). The reflex chain is:`,
` defend > eat > sleep > tech-tree > autonomous > idle`,
` modes(self_preservation/hunger/shelter) > defend > eat > sleep > curriculum > idle (curriculum dispatches the Settlement Contract's chosen skill)`,
`Snapshot:`,
"```json",
promptCtx,
+10 -1
View File
@@ -181,7 +181,16 @@ const MILESTONES = [
id: "shelter.torch",
title: "Have torches on hand for the perimeter",
isDone: (inv) => has(inv, "torch", 4),
suggest: () => ({ skillId: "craft.torch" }),
// Two-step like wood.planks-and-sticks: torches need coal (or
// charcoal), but nothing else produces it — without this the
// milestone pinned forever on craft.torch's missing_material. Mine
// coal first, then craft. The contract's M6_lighting delegates
// suggest() to this milestone, so this edit fixes both rails.
suggest: (inv) => {
const fuel = (inv?.coal ?? 0) + (inv?.charcoal ?? 0);
if (fuel < 1) return { skillId: "gather.coal" };
return { skillId: "craft.torch" };
},
},
{
id: "village.base-site",
+22
View File
@@ -141,6 +141,28 @@ test("food.basic satisfied by high food bar even without food item", () => {
assert.equal(got.milestone.id, "storage.chest");
});
test("shelter.torch suggests gather.coal when no coal on hand (closes the M6 dead-end)", () => {
const inv = {
wooden_axe: 1, wooden_pickaxe: 1, wooden_sword: 1,
stone_axe: 1, stone_pickaxe: 1, stone_sword: 1, furnace: 1,
red_bed: 1, bread: 2,
};
const got = nextMilestone(snap(inv, { food: 20, locations: { chest: { x: 1, y: 64, z: 0 } } }));
assert.equal(got.milestone.id, "shelter.torch");
assert.equal(got.plan.skillId, "gather.coal");
});
test("shelter.torch suggests craft.torch once coal is on hand", () => {
const inv = {
wooden_axe: 1, wooden_pickaxe: 1, wooden_sword: 1,
stone_axe: 1, stone_pickaxe: 1, stone_sword: 1, furnace: 1,
red_bed: 1, bread: 2, coal: 1,
};
const got = nextMilestone(snap(inv, { food: 20, locations: { chest: { x: 1, y: 64, z: 0 } } }));
assert.equal(got.milestone.id, "shelter.torch");
assert.equal(got.plan.skillId, "craft.torch");
});
test("all done → null", () => {
const inv = {
oak_log: 16, oak_planks: 8, stick: 8,
+56
View File
@@ -0,0 +1,56 @@
// Invariant predicate library — these are the "milestone done" truths the
// Settlement Contract relies on. Locking them guards against the closed-loop
// regressions the v0.4.1 audit surfaced (e.g. M2_bed must be able to close via
// a recorded bed LOCATION once actions.js writes locations.bed, not only via a
// transient carried-bed item).
import { test } from "node:test";
import assert from "node:assert/strict";
import {
worldFromSnapshot,
bedSecured,
foodSecure,
stoneTier,
locationExists,
hasItem,
} from "./invariants.js";
const w = (snap) => worldFromSnapshot(snap);
test("bedSecured: met by a carried bed item", () => {
assert.equal(bedSecured().met(w({ inventory: { red_bed: 1 } })), true);
});
test("bedSecured: met by a recorded bed LOCATION (M2 monotonicity after the bed is placed)", () => {
// The carried item is gone (consumed by placement) but the location was
// recorded — M2 must stay satisfied so the contract doesn't loop
// gather.wool→craft.bed for a bed that physically exists.
assert.equal(bedSecured().met(w({ inventory: {}, locations: { bed: { x: 1, y: 64, z: 1 } } })), true);
});
test("bedSecured: unmet with neither a bed item nor a bed location", () => {
assert.equal(bedSecured().met(w({ inventory: {}, locations: {} })), false);
});
test("foodSecure: cooked staple, well-fed, or hasFood — but not raw materials", () => {
assert.equal(foodSecure().met(w({ inventory: { bread: 1 } })), true);
assert.equal(foodSecure().met(w({ inventory: {}, food: 18 })), true);
assert.equal(foodSecure().met(w({ inventory: {}, hasFood: true })), true);
assert.equal(foodSecure().met(w({ inventory: { cobblestone: 40 }, food: 10 })), false);
});
test("stoneTier: needs all three stone tools AND a furnace", () => {
assert.equal(stoneTier().met(w({ inventory: { stone_axe: 1, stone_pickaxe: 1, stone_sword: 1 } })), false);
assert.equal(stoneTier().met(w({ inventory: { stone_axe: 1, stone_pickaxe: 1, stone_sword: 1, furnace: 1 } })), true);
});
test("locationExists: pure key-presence over locations (no item required)", () => {
assert.equal(locationExists("shelter").met(w({ locations: { shelter: { x: 0, y: 64, z: 0 } } })), true);
assert.equal(locationExists("shelter").met(w({ locations: {} })), false);
});
test("hasItem('torch', 4): the M6 lighting threshold", () => {
assert.equal(hasItem("torch", 4, "torch").met(w({ inventory: { torch: 3 } })), false);
assert.equal(hasItem("torch", 4, "torch").met(w({ inventory: { torch: 4 } })), true);
});
+1
View File
@@ -31,6 +31,7 @@ export const SKILL_GRAPH = Object.freeze({
"gather.logs": { requires: [], produces: ["logs"] },
"gather.wool": { requires: [], produces: ["wool"] },
"gather.stone": { requires: [{ tool: "pickaxe" }], produces: ["cobblestone"] },
"gather.coal": { requires: [{ tool: "pickaxe" }], produces: ["coal"] },
"craft.planks": { requires: [{ item: "logs", min: 1 }], produces: ["planks"] },
"craft.sticks": { requires: [{ item: "planks", min: 2 }], produces: ["stick"] },
"craft.wooden-axe": { requires: [{ item: "planks", min: 3 }, { item: "stick", min: 2 }], produces: ["wooden_axe"] },
+18
View File
@@ -41,6 +41,24 @@ test("unknown skill is treated as runnable (known:false)", () => {
assert.equal(r.known, false);
});
test("gather.coal needs a pickaxe and produces coal (closes the M6 dead-end)", () => {
assert.equal(canRun("gather.coal", world({})), false);
assert.equal(canRun("gather.coal", world({ wooden_pickaxe: 1 })), true);
assert.equal(canRun("gather.coal", world({ stone_pickaxe: 1 })), true);
});
test("craft.torch is blocked without coal but runnable once coal is gathered", () => {
assert.equal(canRun("craft.torch", world({ stick: 1 })), false);
assert.equal(canRun("craft.torch", world({ stick: 1, coal: 1 })), true);
// charcoal counts as coal (semantic group)
assert.equal(canRun("craft.torch", world({ stick: 1, charcoal: 1 })), true);
});
test("runnableFrontier includes gather.coal once a pickaxe is held", () => {
assert.ok(!runnableFrontier(world()).includes("gather.coal"));
assert.ok(runnableFrontier(world({ wooden_pickaxe: 1 })).includes("gather.coal"));
});
test("axe matcher excludes pickaxe", () => {
assert.equal(_internal.TOOL.axe("wooden_axe"), true);
assert.equal(_internal.TOOL.axe("wooden_pickaxe"), false);
+15 -7
View File
@@ -45,9 +45,14 @@ export function describeSkill(id) {
}
// Human-readable block to drop into LLM system prompts. Groups by
// namespace, lists "id — title (timeoutMs)". Capped at ~2KB to stay
// well within the model's instruction window.
export function skillRegistryPrompt({ limit = 2000 } = {}) {
// namespace, lists "id — title". Capped at ~2KB to stay well within the
// model's instruction window. When the list overflows the cap we truncate
// the LIST, never the footer — the footer carries the load-bearing
// guardrail ("NEVER invent new ids"), the whole reason this prompt exists.
// A naive tail-slice (the pre-v0.4.1 behaviour) would silently drop that
// guardrail once the registry grew past the cap, re-opening the exact v0.2
// skill-id hallucination this module was built to close.
export function skillRegistryPrompt({ limit = 3000 } = {}) {
const { byNamespace } = get();
const namespaces = Array.from(byNamespace.keys()).sort();
const lines = ["Valid skill ids (USE ONLY THESE for avoid_skill / prefer_skill):"];
@@ -58,10 +63,13 @@ export function skillRegistryPrompt({ limit = 2000 } = {}) {
lines.push(` - ${s.id}${s.title ?? s.id}`);
}
}
lines.push("");
lines.push("If no listed skill fits, set the field to null. NEVER invent new ids.");
const text = lines.join("\n");
return text.length > limit ? text.slice(0, limit - 4) + "\n..." : text;
const body = lines.join("\n");
const footer = "If no listed skill fits, set the field to null. NEVER invent new ids.";
const full = `${body}\n\n${footer}`;
if (full.length <= limit) return full;
const sep = "\n...\n\n";
const room = Math.max(0, limit - footer.length - sep.length);
return `${body.slice(0, room)}${sep}${footer}`;
}
// For tests / hot-reload scenarios.
+12 -2
View File
@@ -58,8 +58,18 @@ test("registryPrompt: contains the real ids grouped by namespace", () => {
assert.doesNotMatch(txt, /survive\.shelter[^-]/);
});
test("registryPrompt: respects limit parameter", () => {
test("registryPrompt: respects limit and preserves the NEVER-invent guardrail when truncating", () => {
const short = skillRegistryPrompt({ limit: 200 });
assert.ok(short.length <= 200, `expected <=200, got ${short.length}`);
assert.ok(short.endsWith("..."));
// The skill LIST is truncated (…), but the guardrail footer must always
// survive — otherwise a growing registry silently stops telling the LLM
// not to hallucinate skill ids.
assert.match(short, /\.\.\./, "list should be truncated");
assert.match(short, /NEVER invent/, "guardrail footer must survive truncation");
});
test("registryPrompt: default limit fits the full registry incl. the guardrail footer", () => {
const full = skillRegistryPrompt();
assert.match(full, /NEVER invent/);
assert.doesNotMatch(full, /\n\.\.\.\n/, "default prompt should not be truncated");
});
+12 -3
View File
@@ -172,13 +172,22 @@ export const skill = Object.freeze({
}
}
// Closed-loop integrity: a build that placed nothing AND skipped
// nothing never established a shelter. Do NOT record a shelter
// location in that case — M8_shelter's invariant locationExists(
// "shelter") is mere key-presence with no compensating clear, so a
// single all-throw build would falsely satisfy the milestone forever.
// We record the location only on real progress: placed>0, or skipped>0
// (idempotent resume — the blueprint was already satisfied by existing
// blocks).
if (placed === 0 && skipped === 0) {
return { ok: false, code: "no_progress", detail: "could not place any blocks", worldDelta: null };
}
// Record the shelter location so future skills can find it even if
// base gets re-scored.
setLocation(SHELTER_NAME, { x: center.x, y: center.y, z: center.z, radius: 2, note: `auto-built; ${placed} blocks placed` });
if (placed === 0 && skipped === 0) {
return { ok: false, code: "no_progress", detail: "could not place any blocks", worldDelta: null };
}
return {
ok: true,
code: "done",
+69
View File
@@ -0,0 +1,69 @@
// build-shelter closed-loop integrity: the shelter LOCATION (which satisfies
// M8_shelter's locationExists("shelter") invariant) must be recorded ONLY when
// the build actually made progress. A build that places nothing and skips
// nothing must NOT mark M8 done. Runs against the isolated test state dir
// (config.js detects --test), with a fake bot carrying a real minecraft-data
// registry so applyProfile/Movements construct without a live server.
import { test } from "node:test";
import assert from "node:assert/strict";
import mcDataLoader from "minecraft-data";
import { skill } from "./build-shelter.js";
import { setLocation, getLocation, removeLocation } from "../locations.js";
const registry = mcDataLoader("1.21.4");
function makePos(x, y, z) {
return { x, y, z, clone: () => makePos(x, y, z), offset: (dx, dy, dz) => makePos(x + dx, y + dy, z + dz) };
}
// blockKind: (target) => block-or-null describing what bot.blockAt returns at
// every coordinate. We use it to make the whole world either air (no
// placement possible) or solid (every placement succeeds).
function makeBot(blockKind, planks = 30) {
return {
registry,
world: {},
entity: { position: makePos(0, 64, 0) },
pathfinder: { setMovements() {} },
inventory: { items: () => (planks > 0 ? [{ name: "oak_planks", count: planks }] : []) },
blockAt(p) { return blockKind(p); },
async equip() { return true; },
async placeBlock() { return true; },
};
}
test("failed build (placed 0, skipped 0) does NOT record a shelter location", async () => {
removeLocation("shelter");
setLocation("base", { x: 0, y: 64, z: 0, note: "test base" });
// Air everywhere → every findReferenceForPlacement returns null → nothing
// placed, nothing skipped.
const bot = makeBot(() => ({ name: "air", boundingBox: "empty" }));
const res = await skill.execute({ bot, owned: null });
assert.equal(res.ok, false);
assert.equal(res.code, "no_progress");
assert.equal(getLocation("shelter"), null, "shelter location must NOT be recorded on a no-progress build");
removeLocation("base");
});
test("successful build records the shelter location", async () => {
removeLocation("shelter");
setLocation("base", { x: 0, y: 64, z: 0, note: "test base" });
// Solid everywhere → every target has a reference block to place against.
const bot = makeBot((p) => ({ name: "stone", boundingBox: "block", position: makePos(p.x, p.y, p.z) }));
const res = await skill.execute({ bot, owned: null });
assert.equal(res.ok, true);
assert.equal(res.code, "done");
assert.ok(res.detail.placed > 0, "expected at least one block placed");
const shelter = getLocation("shelter");
assert.ok(shelter && shelter.x === 0 && shelter.z === 0, "shelter location recorded on success");
removeLocation("shelter");
removeLocation("base");
});
+169
View File
@@ -0,0 +1,169 @@
// gather.coal — find a nearby coal ore block, equip a pickaxe (best
// available), path to it and mine it. Modelled on gather.stone: stone-tier
// mining needs at least a wooden pickaxe, the preconditions enforce that.
//
// Why this exists: craft.torch hard-requires coal (or charcoal), but no other
// skill produces either, so M6_lighting was a permanent dead-end that pinned
// the Settlement Contract forever and starved M7/M8/M9. gather.coal is the
// missing producer. coal_ore drops coal directly and collectBlock awaits the
// pickup, so the strict ledger check (expectGain) is safe here.
import pathfinderPkg from "mineflayer-pathfinder";
const { pathfinder, Movements } = pathfinderPkg;
import collectBlockPkg from "mineflayer-collectblock";
const collectBlockPlugin =
collectBlockPkg.plugin ??
collectBlockPkg.default?.plugin ??
collectBlockPkg.default ??
collectBlockPkg;
import toolPkg from "mineflayer-tool";
const toolPlugin = toolPkg.plugin ?? toolPkg.default?.plugin ?? toolPkg.default ?? toolPkg;
import { pickaxes } from "./groups.js";
import { info, warn } from "../log.js";
import { findNearestBlockByName } from "../perception.js";
const COAL_ORE_NAMES = ["coal_ore", "deepslate_coal_ore"];
let pluginLoaded = new WeakSet();
function ensurePathfinder(bot) {
if (pluginLoaded.has(bot)) return;
bot.loadPlugin(pathfinder);
pluginLoaded.add(bot);
}
let toolLoaded = new WeakSet();
function ensureTool(bot) {
if (toolLoaded.has(bot)) return;
bot.loadPlugin(toolPlugin);
toolLoaded.add(bot);
}
let collectBlockLoaded = new WeakSet();
function ensureCollectBlock(bot) {
ensurePathfinder(bot);
ensureTool(bot);
if (collectBlockLoaded.has(bot)) return;
bot.loadPlugin(collectBlockPlugin);
collectBlockLoaded.add(bot);
}
function setMovementsForGather(bot) {
const m = new Movements(bot);
m.canDig = true;
m.allow1by1towers = false;
bot.pathfinder.setMovements(m);
}
const PICKAXE_PRIORITY = ["netherite_pickaxe", "diamond_pickaxe", "iron_pickaxe", "stone_pickaxe", "wooden_pickaxe"];
async function equipBestPickaxe(bot) {
for (const name of PICKAXE_PRIORITY) {
const item = bot.inventory.items().find((i) => i.name === name);
if (item) {
try {
await bot.equip(item, "hand");
return name;
} catch {}
}
}
return null;
}
function withTimeout(promise, ms, label) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms / 1000}s`)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
const coalBlacklist = new WeakMap();
const BLACKLIST_TTL_MS = 5 * 60_000;
function getBlacklist(bot) {
let m = coalBlacklist.get(bot);
if (!m) {
m = new Map();
coalBlacklist.set(bot, m);
}
const now = Date.now();
for (const [k, exp] of m) if (exp < now) m.delete(k);
return m;
}
export const skill = Object.freeze({
id: "gather.coal",
title: "Gather coal",
timeoutMs: 90_000,
// Closed-loop strict check: the milestone needs coal in hand, so we assert
// the world actually moved (coal/charcoal increased) and refuse to report
// "ok" if the dig left the inventory unchanged (runSkill → world_unchanged).
expectGain: { matcher: (k) => k === "coal" || k === "charcoal", min: 1, label: "coal" },
preconditions(ctx) {
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
const available = pickaxes(ctx.bot);
if (available.size === 0) {
return { ok: false, code: "unsupported_version", detail: "no pickaxes in registry" };
}
const owned = ctx.bot.inventory.items().some((i) => available.has(i.name));
if (!owned) {
return { ok: false, code: "missing_tool", detail: "no pickaxe in inventory" };
}
return { ok: true };
},
async execute(ctx) {
const bot = ctx.bot;
const blacklist = getBlacklist(bot);
// Numeric-id search — callback matcher returns 0 under ViaBackwards. See runtime/perception.js.
const target = findNearestBlockByName(bot, COAL_ORE_NAMES, {
maxDistance: 32,
predicate: (b) => !blacklist.has(`${b.position.x},${b.position.y},${b.position.z}`),
});
if (!target) {
return { ok: false, code: "no_target", detail: "no reachable coal ore within 32 blocks", worldDelta: null };
}
ensureCollectBlock(bot);
setMovementsForGather(bot);
const pickaxe = await equipBestPickaxe(bot);
info("action", `gather.coal: ${target.name} at ${target.position.x},${target.position.y},${target.position.z} (tool=${pickaxe ?? "fists"})`);
const targetPos = target.position.clone();
try {
try {
await withTimeout(bot.lookAt(targetPos.offset(0.5, 0.5, 0.5), true), 2_000, "lookAt(coal)");
} catch {}
await withTimeout(bot.collectBlock.collect(target), 60_000, "collectCoal");
const after = bot.blockAt(targetPos);
if (after && COAL_ORE_NAMES.includes(after.name)) {
warn("action", `gather.coal reported ok but block still at ${targetPos.x},${targetPos.y},${targetPos.z} — silent dig failure`);
const key = `${targetPos.x},${targetPos.y},${targetPos.z}`;
blacklist.set(key, Date.now() + BLACKLIST_TTL_MS);
return {
ok: false,
code: "silent_dig_failure",
detail: "block still exists after collect — protocol/anti-cheat issue",
worldDelta: null,
};
}
return {
ok: true,
code: "done",
detail: { blockType: target.name, at: targetPos },
worldDelta: { minedAt: targetPos, blockType: target.name },
};
} catch (e) {
warn("action", `gather.coal failed: ${e.message}`);
const key = `${target.position.x},${target.position.y},${target.position.z}`;
blacklist.set(key, Date.now() + BLACKLIST_TTL_MS);
const msg = String(e?.message ?? "");
const code = msg.includes("timed out") ? "timeout" : "failed";
return { ok: false, code, detail: e.message, worldDelta: null };
}
},
validate(ctx, result) {
return result.ok && !!result.worldDelta?.blockType;
},
recover(ctx, result) {
if (result.code === "no_target") return { hint: "wander", reason: "no coal ore within 32 blocks" };
return null;
},
});
+2
View File
@@ -35,6 +35,7 @@ import { skill as escapePitSafe } from "./escape-pit-safe.js";
import { skill as diagPhysics } from "./diagnose-physics.js";
import { skill as diagScan, matchSkill as diagMatch } from "./diagnose-scan.js";
import { skill as gatherStone } from "./gather-stone.js";
import { skill as gatherCoal } from "./gather-coal.js";
import { skill as gatherWool } from "./gather-wool.js";
import { skill as acquireFood } from "./acquire-food.js";
import { skill as scoutFood } from "./scout-food.js";
@@ -84,6 +85,7 @@ register(diagPhysics);
register(diagScan);
register(diagMatch);
register(gatherStone);
register(gatherCoal);
register(gatherWool);
register(acquireFood);
register(scoutFood);
+107
View File
@@ -0,0 +1,107 @@
// Pure, ink-free helpers for the monitor header.
//
// bot.js stamps a rich observability bundle onto every STATUS snapshot
// (runtimeState, lastReflex.name, activeSkill, noProgressReason, reflexPaused)
// and the GoalManager annotates contract.suggestedSkill.blockedBy — but none
// of it was rendered, so the operator could not answer "what is the bot doing,
// why, and what is blocked?" from the screen. These helpers assemble that into
// colour-tagged segments. Kept in a plain .js module (no React/ink import) so
// `node --test` can unit-test the formatting without booting the TUI.
//
// A "segment" is { text, color?, dimColor?, bold? }. The monitor maps each to
// an <ink Text>; tests join `.text` and assert on substrings + segment colour.
const STATE_COLORS = Object.freeze({
emergency: "red",
recovering: "yellow",
working: "green",
planning: "magenta",
social: "cyan",
idle: "gray",
});
// computeState can return any of the STATES strings; unknown/new states render
// in a neutral colour rather than being blanked out.
export function stateColor(state) {
if (!state) return "gray";
return STATE_COLORS[String(state).toLowerCase()] ?? "white";
}
// blockedBy is an array of { item, min, have } | { tool } OBJECTS (from
// goal-manager.js via skill-graph.prerequisitesMet) — NOT strings. Map to the
// missing names so we never render "[object Object]". Returns null when there
// is nothing blocked.
export function formatBlockedBy(blockedBy) {
if (!Array.isArray(blockedBy) || blockedBy.length === 0) return null;
const names = blockedBy
.map((b) => {
const name = b?.item ?? b?.tool;
if (!name) return null;
return b?.min && b.min > 1 ? `${name}×${b.min}` : name;
})
.filter(Boolean);
return names.length ? names.join("+") : null;
}
// Build the "what / why / blocked / stalled" status line for the header.
// Reads only fields already present on the broadcast snapshot.
export function formatStatusSegments(snapshot = {}) {
const segs = [];
const push = (text, opts = {}) => {
if (text != null && text !== "") segs.push({ text, ...opts });
};
const state = snapshot.runtimeState;
if (state) push(String(state), { bold: true, color: stateColor(state) });
if (snapshot.reflexPaused === true) push(" PAUSED", { bold: true, color: "red" });
// why — which rail fired this tick (mode:…, curriculum, defend, …)
const why = snapshot.lastReflex?.name;
if (why) {
push(" via ", { dimColor: true });
push(String(why), { color: "white" });
}
// doing — the skill currently/last dispatched
const doing = snapshot.activeSkill;
if (doing) {
push(" · ", { dimColor: true });
push(String(doing), { color: "cyan" });
}
// blocked — the suggested skill cannot run because a prerequisite is
// missing (e.g. craft.torch needs coal). This is the one that made the
// M6-torch/coal stall invisible.
const sg = snapshot.contract?.suggestedSkill;
const blocked = formatBlockedBy(sg?.blockedBy);
if (blocked) {
push(" · ", { dimColor: true });
if (sg?.skillId) push(String(sg.skillId), { color: "red" });
push(" needs ", { dimColor: true });
push(blocked, { color: "red", bold: true });
}
// urgent preemption (food jumping the contract queue)
const reason = snapshot.contract?.reason;
if (typeof reason === "string" && reason.startsWith("urgent")) {
push(" · ", { dimColor: true });
push(reason, { color: "yellow" });
}
// stalled — no observable world change for a while
const np = snapshot.noProgressReason;
if (np) {
push(" · stalled:", { dimColor: true });
push(String(np), { color: "yellow" });
}
return segs;
}
// Convenience for tests / plain-text surfaces.
export function statusText(snapshot) {
return formatStatusSegments(snapshot)
.map((s) => s.text)
.join("");
}
+67
View File
@@ -0,0 +1,67 @@
// Pure formatting helpers for the monitor header. These assemble the per-tick
// "what / why / blocked / stalled" line from snapshot fields the bot already
// broadcasts, so the operator can see why the bot is (not) acting. Tested off
// ink — no React/render involved.
import { test } from "node:test";
import assert from "node:assert/strict";
import { formatStatusSegments, statusText, formatBlockedBy, stateColor } from "./format.js";
test("statusText surfaces state, firing rail, active skill and stall reason", () => {
const txt = statusText({
runtimeState: "idle",
lastReflex: { name: "curriculum" },
activeSkill: "gather.logs",
noProgressReason: "waiting_for_day",
});
assert.match(txt, /idle/);
assert.match(txt, /curriculum/);
assert.match(txt, /gather\.logs/);
assert.match(txt, /waiting_for_day/);
});
test("reflexPaused renders a PAUSED marker", () => {
assert.match(statusText({ runtimeState: "working", reflexPaused: true }), /PAUSED/);
assert.doesNotMatch(statusText({ runtimeState: "working", reflexPaused: false }), /PAUSED/);
});
test("blocked prerequisite is shown by name, never as [object Object]", () => {
const snap = {
runtimeState: "working",
contract: { suggestedSkill: { skillId: "craft.torch", blockedBy: [{ item: "coal", min: 1, have: 0 }] } },
};
const txt = statusText(snap);
assert.match(txt, /craft\.torch/);
assert.match(txt, /coal/);
assert.doesNotMatch(txt, /\[object Object\]/);
});
test("urgent contract reason (food preemption) is surfaced", () => {
const txt = statusText({
runtimeState: "working",
contract: { reason: "urgent:M4_food_security(100) preempts M1_wood_tools" },
});
assert.match(txt, /urgent/);
});
test("formatBlockedBy maps {item,min} and {tool} objects, null when empty", () => {
assert.equal(formatBlockedBy([]), null);
assert.equal(formatBlockedBy(undefined), null);
assert.equal(formatBlockedBy([{ item: "planks", min: 8, have: 0 }]), "planks×8");
assert.equal(formatBlockedBy([{ tool: "pickaxe" }]), "pickaxe");
assert.equal(formatBlockedBy([{ item: "coal", min: 1 }, { item: "stick", min: 1 }]), "coal+stick");
});
test("stateColor maps known states and defaults unknown ones to a visible colour", () => {
assert.equal(stateColor("emergency"), "red");
assert.equal(stateColor("idle"), "gray");
assert.equal(stateColor("planning"), "magenta");
// unknown / future states render in white rather than being blanked out
assert.equal(stateColor("teleporting"), "white");
assert.equal(stateColor(undefined), "gray");
});
test("empty snapshot yields no segments (header row collapses)", () => {
assert.equal(formatStatusSegments({}).length, 0);
});
+16
View File
@@ -24,6 +24,7 @@
import React, { useEffect, useReducer, useState } from "react";
import { render, Box, Text, useApp, useInput, useStdout } from "ink";
import { createIpcClient } from "./ipc-client.js";
import { formatStatusSegments } from "./format.js";
import { EVENT_TYPES } from "../runtime/ipc-protocol.js";
import { stateDir } from "../runtime/config.js";
import { initKnowledge, isAvailable as knowledgeReady, recentRecommendations, listImprovements, recommendationStats } from "../runtime/knowledge/index.js";
@@ -215,6 +216,21 @@ function StatusHeader({ snapshot, connectedIpc, width, startedAt }: { snapshot:
</>
) : null}
</Box>
{/* What / why / blocked / stalled — per-tick observability the bot
already computes (runtimeState, lastReflex, activeSkill, blockedBy,
noProgressReason); assembled by the pure formatStatusSegments helper
so it stays unit-testable off ink. */}
{(() => {
const segs = formatStatusSegments(snapshot);
if (segs.length === 0) return null;
return (
<Box>
{segs.map((s, i) => (
<Text key={i} color={s.color} dimColor={s.dimColor} bold={s.bold}>{s.text}</Text>
))}
</Box>
);
})()}
</Box>
);
}