Files
agentic-labs-challenge/underdepths/orchestrate.sh
T
2026-08-13 07:28:55 +02:00

556 lines
29 KiB
Bash
Executable File

#!/usr/bin/env bash
# Underdepths self-driving build pipeline.
# Drives the whole game build with `pi -p` as the primitive. Resumable: progress
# lives in .build_state (index of last completed phase). Delete it to restart.
#
# phase N -> dispatch build work via `pi -p "<phase prompt>"`
# -> run gate: python tests/smoke.py --phase N
# -> on fail: feed the gate error back into pi -p (Ralph loop, <=3 tries)
# phase 2 -> FOV / A* / combat dispatched concurrently, then AI, then gate
# phase 4 -> split into 4a (persist+audio) + 4b (actions+render+main), then gate
# after phase 4 -> goal backstop: verify EVERY plan.md acceptance criterion,
# dispatch fixes until all pass.
#
# All `timeout` calls use --kill-after: pi (node) ignores SIGTERM, so without a
# SIGKILL escalation a stuck dispatch lingers past its TTL and stalls the loop.
set -uo pipefail
cd "$(dirname "$0")"
STATE_FILE=.build_state
LOG=build.log
GATE_ERR=.last_gate_error
MAX_RETRIES=3
PHASE_TTL=3000 # seconds per pi -p dispatch (50 min)
GOAL_TTL=3000
mkdir -p build_logs
# --------------------------------------------------------------------------- #
log() { printf '[%s] %s\n' "$(date +%T)" "$*" | tee -a "$LOG" >/dev/null; }
get_state() { [ -f "$STATE_FILE" ] && cat "$STATE_FILE" 2>/dev/null || echo 0; }
set_state() { echo "$1" > "$STATE_FILE"; }
# dispatch NAME PROMPT [TTL] : run pi -p, append to $LOG, return its exit code.
dispatch() {
local name="$1" prompt="$2" ttl="${3:-$PHASE_TTL}"
log ">>> DISPATCH: $name (ttl ${ttl}s)"
if timeout --kill-after=30 "$ttl" pi -p "$prompt" >>"$LOG" 2>&1; then
log "<<< DISPATCH OK: $name"
return 0
fi
local rc=$?
log "<<< DISPATCH rc=$rc: $name"
return "$rc"
}
# run_gate N : 0 == pass. Captures output to $GATE_ERR on failure.
run_gate() {
local n="$1"
log " gate: python tests/smoke.py --phase $n"
if python tests/smoke.py --phase "$n" >"$GATE_ERR" 2>&1; then
tail -n 20 "$GATE_ERR" >>"$LOG"
log " GATE phase $n PASSED"
rm -f "$GATE_ERR"
return 0
fi
log " GATE phase $n FAILED"
tail -n 50 "$GATE_ERR" | tee -a "$LOG"
return 1
}
# ralph N NAME BASE_PROMPT [TTL] : dispatch + gate loop; set_state on pass.
ralph() {
local n="$1" name="$2" base="$3" ttl="${4:-$PHASE_TTL}"
local attempt=0 prompt="$base"
while :; do
attempt=$((attempt + 1))
log "==== PHASE $n ($name) attempt $attempt ===="
dispatch "$name#$attempt" "$prompt" "$ttl" || true
if run_gate "$n"; then
set_state "$n"
log "==== PHASE $n COMPLETE (state=$n) ===="
return 0
fi
if [ "$attempt" -ge "$MAX_RETRIES" ]; then
log "!!!! PHASE $n FAILED after $MAX_RETRIES attempts - HALTING"
return 1
fi
local err; err="$(tail -n 60 "$GATE_ERR" 2>/dev/null)"
prompt="A previous build attempt for PHASE $n ($name) FAILED its verification gate. The gate error (last 60 lines) is below. Fix the SPECIFIC failures it reports; do NOT rewrite parts that already work.
--- GATE ERROR ---
$err
--- END GATE ERROR ---
Original phase task:
$base"
log " feeding gate error back into retry..."
done
}
# phase 2 : parallel FOV/A*/combat, then AI, then gate, then comprehensive fallback.
phase2() {
log "==== PHASE 2 (parallel core systems) ===="
timeout --kill-after=30 "$PHASE_TTL" pi -p "$COMMON
$P2_FOV" >build_logs/p2_fov.log 2>&1 &
timeout --kill-after=30 "$PHASE_TTL" pi -p "$COMMON
$P2_ASTAR" >build_logs/p2_astar.log 2>&1 &
timeout --kill-after=30 "$PHASE_TTL" pi -p "$COMMON
$P2_COMBAT" >build_logs/p2_combat.log 2>&1 &
wait
log "parallel core systems done (build_logs/p2_*.log)"
dispatch "ai-behaviors" "$COMMON
$P2_AI" "$PHASE_TTL" || true
if run_gate 2; then set_state 2; log "==== PHASE 2 COMPLETE ===="; return 0; fi
log "phase 2 gate failed -> comprehensive Ralph fallback"
ralph 2 core-systems "$COMMON
$P2_ALL"
}
# phase 4 : split into two sequential builds because the phase is too large for a
# single bounded dispatch. 4a = persistence+audio+game-state; 4b = actions+render+
# main. Then one gate; on failure a combined Ralph fix loop.
phase4() {
log "==== PHASE 4 (polish) — split build ===="
dispatch "polish-persist#a1" "$COMMON
$P4A" "$PHASE_TTL" || true
dispatch "polish-ui#a1" "$COMMON
$P4B" "$PHASE_TTL" || true
if run_gate 4; then set_state 4; log "==== PHASE 4 COMPLETE (state=4) ===="; return 0; fi
log "phase 4 gate failed -> Ralph combined-fix fallback"
ralph 4 polish "$COMMON
$P4_FIX"
}
# goal backstop : verify every acceptance criterion, fix until all pass.
goal_backstop() {
log "==== GOAL BACKSTOP ===="
local attempt=0 prompt="$COMMON
$P_GOAL"
while :; do
attempt=$((attempt + 1))
log "goal verify attempt $attempt"
dispatch "goal-verify#$attempt" "$prompt" "$GOAL_TTL" || true
if grep -q "ALL_CRITERIA_PASS" "$LOG"; then
log "agent reported ALL_CRITERIA_PASS"
fi
# independent hard check: the full gate suite must pass.
if python tests/smoke.py --all >build_logs/goal_gate.log 2>&1; then
log "smoke --all PASSED"
tail -n 8 build_logs/goal_gate.log >>"$LOG"
if grep -q "ALL_CRITERIA_PASS" "$LOG"; then
log "==== ALL ACCEPTANCE CRITERIA PASS ===="
return 0
fi
else
log "smoke --all FAILED during goal backstop:"
tail -n 50 build_logs/goal_gate.log | tee -a "$LOG"
fi
if [ "$attempt" -ge "$MAX_RETRIES" ]; then
log "!!!! GOAL BACKSTOP exhausted retries - manual review needed"
return 1
fi
local err; err="$(tail -n 60 "$LOG")"
prompt="$COMMON
A previous goal-verification attempt did NOT confirm ALL_CRITERIA_PASS. Recent log tail:
$err
Re-read the Acceptance Criteria in plan.md, run 'python tests/smoke.py --all' and 'UNDERDEPTHS_HEADLESS=1 python main.py', fix EVERY failing criterion, then print ALL_CRITERIA_PASS as the final line.
$P_GOAL"
log " feeding goal errors back into retry..."
done
}
main() {
echo "Underdepths build pipeline — log: $LOG"
local s; s="$(get_state)"; log "build_state=$s at start"
if [ "$s" -lt 1 ]; then ralph 1 foundation "$COMMON
$P1" || { log "HALT phase 1"; exit 1; }; fi
s="$(get_state)"
if [ "$s" -lt 2 ]; then phase2 || { log "HALT phase 2"; exit 1; }; fi
s="$(get_state)"
if [ "$s" -lt 3 ]; then ralph 3 content "$COMMON
$P3" || { log "HALT phase 3"; exit 1; }; fi
s="$(get_state)"
if [ "$s" -lt 4 ]; then phase4 || { log "HALT phase 4"; exit 1; }; fi
goal_backstop || { log "GOAL BACKSTOP did not fully pass"; }
log "==== PIPELINE FINISHED ===="
}
# --------------------------------------------------------------------------- #
# PROMPTS (literal heredocs; composed with $COMMON at call sites)
# --------------------------------------------------------------------------- #
read -r -d '' COMMON <<'EOF'
You are building Underdepths, a turn-based roguelike in Python 3 with pygame-ce.
The current working directory contains plan.md (the COMPLETE game design document)
and AGENTS.md (build conventions). READ BOTH FULLY FIRST and follow them exactly.
GLOBAL RULES (non-negotiable):
- pygame-ce is for rendering, input, and generated audio ONLY. Everything else is
the Python standard library. NEVER import numpy. Represent the map grid as
list[list[int]] (0 = wall, 1 = floor) and explored/visible as list[list[bool]].
Generate sound samples with array.array.
- Use @dataclass(slots=True) for all entities and state objects. Type-hint every
function signature. All tunable values live in data/constants.py. No magic
numbers scattered in logic.
- No stubs and no TODO comments. Every function you write must have a real, working
implementation.
- The message log (list[str]) is the primary feedback channel: log every combat
event, pickup, level-up, and status change in human-readable form.
- Error handling at boundaries only (file I/O, input). Game logic must never raise
on valid game states.
- Floor numbering: 10 floors, indices 0..9. The Ancient Dragon boss arena is
floor_index 9 (this is "floor 10" in human terms). Victory = the dragon is dead.
COORDINATION: tests/smoke.py is the verification gate AND the API contract. It
imports exact module/function/attribute names. Produce EXACTLY the names the phase
section lists. After writing code, run the gate command named at the end of your
section, read any failure, and fix it before finishing.
EOF
read -r -d '' P1 <<'EOF'
PHASE 1 — FOUNDATION + DATA MODEL. Create/modify ONLY: data/constants.py,
entities/entity.py, engine/map_gen.py, entities/player.py, entities/enemy.py,
data/enemies.py, engine/game_state.py, main.py.
data/constants.py:
MAP_W=80, MAP_H=50, TILE=16, SIGHT_RADIUS=8, FLOORS=10
COLORS = {dict of named RGB tuples from plan.md Rendering section}
plus any tuning constants you need.
entities/entity.py:
@dataclass(slots=True) Entity: x:int=0, y:int=0, name:str="", color:tuple=(255,255,255)
read-only property pos -> (x, y).
engine/map_gen.py:
@dataclass class Rect: x:int, y:int, w:int, h:int
def center(self)->tuple[int,int]
def inner(self)->tuple[int,int,int,int] # x1,y1,x2,y2 inclusive
@dataclass(slots=True) GameMap: width:int, height:int, tiles:list[list[int]],
rooms:list[Rect], explored:list[list[bool]], visible:list[list[bool]],
entities:list, stairs_down:tuple[int,int]|None, floor_index:int
def generate_dungeon(floor_index:int, rng:random.Random) -> GameMap
BSP per plan.md: all walls; recursively split 5-8 times alternating axis;
carve rooms (4x4..10x8) shrunk 1-2 from region edges; connect siblings with
L-shaped corridors; 1-tile wall border. floors 0-8: >=3 rooms, fully
connected, stairs_down on a floor tile in the room farthest from spawn.
floor 9: BOSS ARENA = single 20x15 room centered, stairs_down=None.
DETERMINISM: use ONLY the passed rng (never the global random module).
def is_wall(gmap,x,y)->bool
def walkable(gmap,x,y)->bool # in-bounds and tiles[y][x]==1
entities/player.py:
@dataclass(slots=True) Player(Entity). Base stats (plan.md Progression):
hp=50,max_hp=50,power=4,armor=0,accuracy=5,evasion=2,crit_chance=0.10,speed=1,
level=1,xp=0,inventory:list=[],weapon=None,armor_item=None,timers:dict=field(default_factory=dict).
Properties adding equipment bonuses (None this phase -> return base; but compute
weapon.power / armor_item.armor / crit_delta / evasion_delta when present):
effective_power, effective_armor, effective_accuracy, effective_evasion,
effective_crit_chance. Player(x=0,y=0) and Player(x=3,y=1) must both construct.
entities/enemy.py:
@dataclass(slots=True) Enemy(Entity): hp,max_hp,power,armor,accuracy,evasion,
crit_chance,speed,behavior:str,xp_value:int,ranged_power:int,last_known_pos,
act_counter:int=0,can_split:bool=False. Same effective_* properties as Player.
def make_enemy(kind:str,x:int,y:int)->Enemy : read data.enemies.ENEMIES[kind];
set every field, behavior, xp_value, ranged_power, color; can_split True only
for 'Green Slime'.
data/enemies.py:
ENEMIES dict keyed exactly: 'Rat','Goblin','Skeleton Archer','Orc Warrior',
'Wraith','Green Slime','Ancient Dragon'. Each value a dict: hp,power,armor,
accuracy,evasion,crit_chance,speed,behavior,xp,ranged_power,floors=(min,max),color.
MUST match plan.md Enemy Roster EXACTLY: Rat hp8/pow3/ar0/sp1/wander/xp5/(0,3);
Goblin hp15/pow5/ar1/chase/xp12/(0,5); Skeleton Archer hp12/pow4/ranged_power6/
ar1/ranged/xp15/(2,7); Orc Warrior hp30/pow8/ar3/flee/xp25/(3,8); Wraith hp20/
pow10/phase/xp30/sp2/(5,8); Green Slime hp18/pow5/ar1/split/xp18/(4,8);
Ancient Dragon hp120/pow15/ar8/chase/xp200/(9,9).
def enemies_for_floor(floor_index)->list[str] : kinds whose floors range includes
floor_index; 'Ancient Dragon' only when floor_index==9.
engine/game_state.py:
@dataclass(slots=True) GameSession: player:Player, dungeon:list[GameMap],
current_floor:int, log:list[str], turn:int=0, state:str="playing"
@property current_map -> dungeon[current_floor]
(Full new_game() + recompute_fov() come in phase 4. Just the dataclass now.)
main.py: minimal real pygame loop — set SDL dummy drivers when no display, open a
window, generate floor 0, render tiles as colored rects (plan.md Rendering). ESC
quits. Must run headless under SDL_VIDEODRIVER=dummy without crashing.
GOAL: `python tests/smoke.py --phase 1` exits 0. Run it, read failures, fix.
EOF
read -r -d '' P2_FOV <<'EOF'
PHASE 2 (parallel) — Create ONLY engine/fov.py. Do not touch any other file.
def compute_fov(gmap, ox:int, oy:int, radius:int) -> set[tuple[int,int]]
Recursive shadowcasting over 8 octants, written from scratch (no library). A tile
is visible if an unblocked line reaches it. Walls (tiles[y][x]==0) block sight, but
a wall adjacent to a visible floor tile is itself visible. Return only in-bounds
tiles within Chebyshev distance <= radius. Always include (ox, oy).
Self-check (must print fov ok):
python -c "import sys;sys.path.insert(0,'.');from engine.fov import compute_fov;from engine.map_gen import GameMap; m=GameMap(7,7,[[0]*7 for _ in range(7)],[],[[False]*7 for _ in range(7)],[[False]*7 for _ in range(7)],[],None,0); m.tiles[3][3]=1; assert compute_fov(m,3,3,8)=={(3,3)}; print('fov ok')"
EOF
read -r -d '' P2_ASTAR <<'EOF'
PHASE 2 (parallel) — Create ONLY engine/pathfinding.py. Do not touch any other file.
def astar(gmap, start:tuple[int,int], goal:tuple[int,int], blocked:set|None=None) -> list[tuple[int,int]]|None
Grid A* with Manhattan heuristic, from scratch. Walkable = in-bounds and
tiles[y][x]==1 and (blocked is None or (x,y) not in blocked). Return full path
start..goal inclusive, or None if unreachable.
Self-check (must print astar ok):
python -c "import sys;sys.path.insert(0,'.');from engine.pathfinding import astar;from engine.map_gen import GameMap; m=GameMap(10,1,[[1]*10],[],[],[],[],None,0); p=astar(m,(0,0),(9,0)); assert p and p[0]==(0,0) and p[-1]==(9,0); print('astar ok')"
EOF
read -r -d '' P2_COMBAT <<'EOF'
PHASE 2 (parallel) — Create ONLY engine/combat.py. Do not touch any other file.
Implement plan.md Combat:
def hit_chance(attacker, defender) -> float
base = 0.7 + (eff_acc(attacker) - eff_eva(defender))*0.05
return max(0.1, min(0.95, base))
eff_acc(o)=getattr(o,'effective_accuracy',getattr(o,'accuracy',5))
eff_eva(o)=getattr(o,'effective_evasion',getattr(o,'evasion',2))
def attack(attacker, defender, log:list, ranged:bool=False) -> dict
Hit if random.random() < hit_chance. Use the standard random module.
Miss -> append "<attacker.name> misses <defender.name>"; return
{"hit":False,"damage":0,"crit":False}.
Hit -> base = attacker.ranged_power if (ranged and hasattr) else eff_power(attacker);
reduced = max(0, base - eff_armor(defender));
crit = random.random() < eff_crit(attacker);
damage = reduced * (2 if crit else 1); defender.hp -= damage;
append normal/critical/defeat messages (defeat line mentions xp_value).
return {"hit":True,"damage":damage,"crit":crit}.
eff_power(o)=getattr(o,'effective_power',getattr(o,'power',0))
eff_armor(o)=getattr(o,'effective_armor',getattr(o,'armor',0))
eff_crit(o)=getattr(o,'effective_crit_chance',getattr(o,'crit_chance',0.0))
NEVER raise on valid states (e.g. defender.hp already <=0). Do NOT award XP here.
Self-check (must print combat ok):
python -c "import sys;sys.path.insert(0,'.');from engine.combat import attack;from entities.enemy import make_enemy;from entities.player import Player; a=Player(x=0,y=0); r=attack(a,make_enemy('Goblin',0,0),[]); assert set(r)=={'hit','damage','crit'}; print('combat ok')"
EOF
read -r -d '' P2_AI <<'EOF'
PHASE 2 (sequential, after fov/astar/combat exist) — Create ONLY ai/behaviors.py.
def enemy_turn(enemy, session) -> None
One enemy's action this turn by enemy.behavior, reading session.player,
session.current_map (.tiles,.width,.height,.entities,.stairs_down), session.log.
Use engine.fov.compute_fov (player visible from enemy?), engine.pathfinding.astar
(movement), engine.combat.attack (melee/ranged).
Behaviors (plan.md Enemy AI):
wander: 50% move to a random walkable neighbor, else wait. Never seeks player.
chase: player visible -> astar to a walkable tile ADJACENT to the player (never
onto the player; treat player + other enemies as blocked), step one tile;
already adjacent -> attack(enemy, session.player, session.log). Update
enemy.last_known_pos whenever player visible. Not visible -> step toward
last_known_pos; reached & still no sight -> wander.
flee: player visible and hp < 30% max -> step away (increase distance); else chase.
ranged: visible & distance>3 -> ranged attack (attack(...,ranged=True), log
"X shoots at you"); visible & distance<=2 -> step away (kite); not visible
-> wander.
phase: step toward player IGNORING walls, acts every 2 turns (use act_counter);
adjacent -> melee.
split: chase normally; on death spawn 2 smaller copies (half hp, half power) that
do not split again.
Ancient Dragon (boss, behavior 'chase'): chase PLUS every 3rd turn (act_counter) a
breath weapon: 15 damage to the player if on a clear row/column line toward
it, else AoE; log "The dragon unleashes its breath!".
Shared: enemies never share a tile; remove dead enemies from current_map.entities;
if session.player.hp<=0 set session.state='dead'. Robust: never raise on edge cases
(no path, surrounded) -> wait. DO NOT modify fov/pathfinding/combat.
EOF
read -r -d '' P2_ALL <<'EOF'
PHASE 2 (comprehensive) — You may edit engine/fov.py, engine/pathfinding.py,
engine/combat.py, and ai/behaviors.py. Implement all four per the contracts above
(see plan.md Systems sections 2-5 and Enemy AI). Make `python tests/smoke.py --phase 2`
exit 0. Specifically: compute_fov (recursive shadowcasting, radius 8, walls block but
adjacent wall visible), astar (Manhattan, blocked set, None when unreachable), attack
(hit_chance/damage/crit, never raises, returns {hit,damage,crit}), enemy_turn (wander/
chase/flee/ranged/phase/split/dragon-breath, A* around walls, melee when adjacent).
Run the gate, read failures, fix.
EOF
read -r -d '' P3 <<'EOF'
PHASE 3 — CONTENT: items, equipment, progression. Create/modify: data/items.py,
entities/item.py, entities/player.py (add methods), data/constants.py (add XP table).
data/enemies.py and make_enemy already exist from phase 1 — keep them working.
data/constants.py additions:
XP_THRESHOLDS = [30,70,140,250,400,600,850,1150,1500] # cumulative xp -> levels 2..10
plus per-level HP/power gains matching plan.md (L1->2 +10hp/+1pow ... L9->10 +20hp/+3pow).
entities/item.py:
@dataclass(slots=True) Item(Entity): kind:str ('weapon'|'armor'|'potion'|'scroll'),
sub:str="", power:int=0, armor:int=0, evasion_delta:float=0.0, crit_delta:float=0.0,
heal:int=0, duration:int=0, radius:int=0, damage:int=0, value:int=0.
def make_item(name:str)->Item from the catalog below.
Catalog (plan.md, EXACT): 'Rusty Dagger' weapon power2; 'Short Sword' weapon
power4; 'Battle Axe' weapon power7; 'War Hammer' weapon power10 crit_delta-0.05;
'Leather Armor' armor armor2; 'Chain Mail' armor armor4; 'Plate Armor' armor
armor7 evasion_delta-0.10; 'Healing Potion' potion heal30; 'Strength Potion' potion
duration20 (strength +5 power); 'Invisibility Potion' potion duration15;
'Scroll of Fireball' scroll damage20 radius3; 'Scroll of Teleport' scroll;
'Scroll of Mapping' scroll. Colors: weapons yellow, armor blue, potions red,
scrolls cyan.
data/items.py:
ITEM_CATALOG dict (name->stats) if you centralize; def roll_item(floor_index:int,
rng:random.Random)->Item : better weapons/armor deeper, potions/scrolls uniform.
entities/player.py additions (keep phase-1 fields/properties working):
def equip_item(self, item): weapon -> return current self.weapon to inventory, set
self.weapon=item; armor -> same for self.armor_item. effective_* must include
equipment + an active 'strength' timer.
def gain_xp(self, amount:int, log:list): self.xp += amount; while level<10 and
xp>=XP_THRESHOLDS[level-1]: level up (apply HP/power gains), hp=max_hp (full
heal), log "You reach level N! (HP +X, Power +Y)".
Timers: strength/invisibility via self.timers; def tick_timers(self, log) decrements.
GOAL: `python tests/smoke.py --phase 3` exits 0. Run it, read failures, fix.
EOF
read -r -d '' P4A <<'EOF'
PHASE 4a — PERSISTENCE + AUDIO + GAME-STATE WIRING. Create/modify ONLY:
engine/game_state.py (add new_game + recompute_fov), engine/serializers.py,
engine/audio.py. Do NOT touch engine/actions.py, render/*, or main.py (a later step
4b handles those); but everything you write must import cleanly on its own.
engine/game_state.py (the GameSession dataclass already exists from phase 1 — keep
it and direct GameSession(...) construction working):
def recompute_fov(self): clear current_map.visible; compute fov from the player's
position with SIGHT_RADIUS via engine.fov.compute_fov; mark those tiles visible;
merge them into current_map.explored (once explored, always remembered).
def new_game(seed:int|None=None) -> GameSession: build random.Random(seed);
generate all 10 floors with generate_dungeon(fi, rng); place the player at the
center of floor 0's first room; spawn enemies on each floor per plan.md per-floor
table (use data.enemies.enemies_for_floor + make_enemy; floor 9 arena: ONLY the
Ancient Dragon + 2 Healing Potions near the entrance, no other enemies); spawn
items per the table (data.items.roll_item); set state='playing', current_floor=0,
turn=0, log=[].
engine/serializers.py:
session_to_dict(sess) -> dict ; dict_to_session(d) -> GameSession
save_session(sess, path) ; load_session(path) -> GameSession (JSON only)
Serialize: player (all stats, level, xp, inventory list, equipped weapon/armor,
x/y, timers dict), all 10 floors (width,height,tiles,rooms,explored,entities with
kind/name + positions + current stats, stairs_down, floor_index), current_floor,
turn, log. Do NOT serialize visible (recompute on load). dict_to_session(
session_to_dict(s)) must equal s — the gate compares the dicts. Round-trip items
via make_item(name) and enemies via make_enemy(kind,...), storing name/kind plus
the mutable fields (hp, x, y, etc.).
engine/audio.py:
class Audio: __init__ tries pygame.mixer.init() in try/except; on ANY failure set
self.enabled=False and return (NEVER raise). When enabled, synthesize short Sound
objects IN MEMORY from array.array samples for: hit, miss, damage, pickup, stairs,
levelup, death, victory. self.muted=False. def play(name): a silent no-op when not
enabled or muted. def toggle_mute(): flip self.muted. MUST NOT load any .wav/.ogg
asset files. (The gate monkeypatches pygame.mixer.init to raise OSError and asserts
Audio() survives with enabled=False, and that play/toggle_mute never raise.)
Self-check (must print "4a ok"): python -c "import sys;sys.path.insert(0,'.');import os;os.environ.setdefault('SDL_VIDEODRIVER','dummy');os.environ.setdefault('SDL_AUDIODRIVER','dummy');import tempfile;from engine.game_state import new_game;from engine.serializers import session_to_dict,save_session,load_session;from engine.audio import Audio;a=Audio();a.play('hit');a.toggle_mute();s=new_game(1);p=tempfile.mktemp();save_session(s,p);L=load_session(p);assert session_to_dict(L)==session_to_dict(s);print('4a ok')"
(The full phase-4 gate also needs actions/render/main from step 4b, so it may still
fail — that is expected here; just make YOUR three files correct and importable.)
EOF
read -r -d '' P4B <<'EOF'
PHASE 4b — ACTIONS + RENDERING + FULL GAME. Create/modify ONLY: engine/actions.py,
render/renderer.py, render/camera.py, main.py. (game_state.new_game, serializers, and
audio already exist from step 4a — use them, do not break them.)
engine/actions.py — pure functions taking a GameSession (and an index where noted),
mutating it, appending log lines, and for turn-costing actions then:
sess.player.tick_timers(sess.log); sess.turn += 1; run every enemy via
ai.behaviors.enemy_turn (snapshot current_map.entities first; remove dead enemies
safely); sess.recompute_fov().
try_move(sess, dx, dy): target tile; if an enemy is there -> attack(sess.player,
enemy, sess.log) melee; if the enemy died -> sess.player.gain_xp(enemy.xp_value,
sess.log), remove it, and if it was a splitting slime spawn 2 smaller copies (half
hp/power, no further split); elif walkable & empty -> move the player; elif wall
-> nothing.
pickup(sess): the item at the player's tile (if any) -> inventory; log "You pick up
<name>.".
descend(sess): ONLY if the player stands on current_map.stairs_down; otherwise do
nothing. When valid: current_floor += 1; place the player at the next floor's
first-room center (or the arena entrance for floor 9); recompute_fov; log "You
descend to floor N." Victory: when the dragon is slain on floor 9, set
sess.state='victory' (the kill is handled in try_move/AI). On floor 9 with the
dragon still alive there are no stairs, so descend is a no-op.
use_item(sess, index): quaff potion or read scroll by item.kind: Healing +30 HP (cap
max_hp); Strength +5 power for 20 turns (player.timers['strength']); Invisibility
15 turns (player.timers['invisibility']); Fireball 20 damage to all enemies within
radius 3 of the player; Teleport to a random walkable tile of the current floor;
Mapping -> set every current-floor tile explored=True. Consume (remove) the item.
equip(sess, index): sess.player.equip_item(item); remove it from inventory.
render/renderer.py + render/camera.py: draw 16x16 colored rects per plan.md Rendering
(wall/floor visible vs explored-not-visible shades, entities by type color, player,
stairs bright yellow '>'); camera follows the player, viewport ~50x30 tiles; UI panels:
top bar (Floor N/10, HP bar, Level, XP bar), right panel (last 8 log messages,
color-coded), bottom (equipment + sound state), and CONTEXT PROMPTS: when the player
stands on an item show "Press G to pick up <name>"; when on stairs show
"Press F to descend". All drawing must be safe under SDL_VIDEODRIVER=dummy.
main.py — the FULL game:
Main menu: New Game / Continue (only offered if save.json exists) / How to Play /
Quit. Show the How to Play screen BEFORE the first turn of every New Game, and make
'?' reopen it during play. Controls (plan.md): arrows/hjkl move, g pickup, i
inventory, e equipment, q quaff, r read, f descend on stairs, S save+quit, ? help, m
mute, Esc cancel/close menus. Game states: menu, playing, dead (game-over screen
"You died on floor N. You reached level M." then DELETE save.json), victory (win
screen, DELETE save.json). 'S' -> save_session to save.json -> return to menu. On
startup, if save.json exists, offer Continue. MUST run headless under
SDL_VIDEODRIVER=dummy & SDL_AUDIODRIVER=dummy without crashing. Support
UNDERDEPTHS_HEADLESS=1: run a short scripted smoke (open menu, start a new game,
move a few steps, attempt a pickup, loop briefly) then exit 0 — the goal backstop
uses this.
GOAL: `python tests/smoke.py --phase 4` exits 0. Run it, read failures, fix. (The
pickup, descend, and audio-disabled tests all live in this gate.)
EOF
read -r -d '' P4_FIX <<'EOF'
PHASE 4 (combined fix) — You may edit any phase-4 file: engine/game_state.py,
engine/serializers.py, engine/audio.py, engine/actions.py, render/renderer.py,
render/camera.py, main.py. Two earlier sub-builds (4a persistence+audio, 4b
actions+render+main) ran but the phase-4 gate still fails. Read the gate error, fix
the SPECIFIC failures, keep working parts intact. Make `python tests/smoke.py --phase 4`
exit 0. Key requirements: new_game() builds all 10 floors and spawns per the per-floor
table; serializers round-trip exactly (session_to_dict equality); Audio() survives a
forced mixer-init failure and never loads asset files; actions.pickup moves the
under-player item into inventory and removes it from the map; actions.descend advances
current_floor when on stairs; main.py runs headless and supports UNDERDEPTHS_HEADLESS=1.
Run the gate, read failures, fix.
EOF
read -r -d '' P_GOAL <<'EOF'
FINAL ACCEPTANCE VERIFICATION for Underdepths. Read the "Acceptance Criteria"
section of plan.md. Run `python tests/smoke.py --all` and
`UNDERDEPTHS_HEADLESS=1 python main.py`. For EACH acceptance-criterion checkbox,
state PASS or FAIL with one line of evidence. If EVERY criterion passes, print
exactly ALL_CRITERIA_PASS as the final line and change nothing. If any FAIL, FIX
the specific failure (you may modify any file), re-run the checks, and repeat until
all pass, then print ALL_CRITERIA_PASS. Do NOT declare success while any criterion
is unmet. Pay special attention to: 10 procedurally generated floors; 6 regular +
1 boss enemy with their behaviors visible; A*/FOV/BSP/combat/XP/items/save-load all
genuinely working; How to Play from menu AND before every New Game; context prompts
for g pickup and f descent (and the input smoke test proves both); audio safety
(mute works, missing device does not crash); win state (kill the dragon on the final
floor) and lose state (death -> game over, save deleted); save/quit/relaunch/
continue.
EOF
main "$@"