#!/usr/bin/env bash # Underdepths self-driving build pipeline. # # Drives the whole game build with `pi -p` (DEFAULT model only — never # --model/--provider). Resumable via .build_state (single int = last completed # phase). Re-run after a crash picks up where it left off. # # Hardening (learned the hard way on this exact challenge): # * SEQUENTIAL dispatches only — parallel `pi -p` agents corrupt shared files. # * Watchdog SIGKILL of the whole process group: `pi` is node, ignores # SIGTERM, so plain `timeout` lets hung workers linger. setsid -w puts the # worker in its own session; we kill -$pgid to reap the whole tree. # * Gate-pass advances even if the dispatch itself was killed/timed out. # * Ralph loop feeds the ACTUAL gate error back into the next dispatch. set -uo pipefail DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" cd "$DIR" STATE_FILE="$DIR/.build_state" LOG_DIR="$DIR/.logs" LOG="$LOG_DIR/build.log" DISPATCH_LOG="$LOG_DIR/dispatch.log" PIDFILE="$LOG_DIR/dispatch.pid" mkdir -p "$LOG_DIR" TTL="${UNDERDEPTHS_TTL:-3000}" # per-dispatch ceiling, seconds (50 min) MAX_RETRIES=3 PY="${PYTHON:-python3}" log() { printf '[%s] %s\n' "$(date +%H:%M:%S)" "$*" | tee -a "$LOG"; } # --------------------------------------------------------------------------- # run_dispatch : run `pi -p ""` under a watchdog. Always # returns (never hangs). Output appended to $DISPATCH_LOG. # --------------------------------------------------------------------------- run_dispatch() { local prompt="$1" : > "$DISPATCH_LOG" : > "$PIDFILE" log " dispatch: pi -p (<${#prompt} chars>) TTL=${TTL}s" # setsid -w: child becomes session leader (pid==pgid); parent waits => $! is a # synchronous handle. Inner bash records its pid+pgid for the watchdog. setsid -w bash -c ' echo "$$ $(ps -o pgid= -p $$ | tr -d " ")" > "$1" exec pi -p "$2" ' bash "$PIDFILE" "$prompt" >>"$DISPATCH_LOG" 2>&1 & local job=$! # Watchdog: after TTL, SIGKILL the whole session + the handle. ( sleep "$TTL" if [ -f "$PIDFILE" ]; then read -r wpid wpgid < "$PIDFILE" kill -KILL -- "-${wpgid}" 2>/dev/null kill -KILL "$wpid" 2>/dev/null fi kill -KILL "$job" 2>/dev/null ) & local wdog=$! wait "$job" 2>/dev/null local rc=$? kill "$wdog" 2>/dev/null wait "$wdog" 2>/dev/null log " dispatch returned rc=$rc" return "$rc" } # --------------------------------------------------------------------------- # run_gate : run the smoke gate. Sets GATE_OUT to combined output. # Returns 0 on PASS, 1 on FAIL. # --------------------------------------------------------------------------- GATE_OUT="" run_gate() { local out out="$($PY tests/smoke.py "$@" 2>&1)" local rc=$? GATE_OUT="$out" if [ "$rc" -eq 0 ]; then log " GATE $*: PASS" return 0 fi log " GATE $*: FAIL" return 1 } # --------------------------------------------------------------------------- # dispatch_fix : targeted fix dispatch with the real error. # --------------------------------------------------------------------------- dispatch_fix() { local kind="$1" err="$2" local prompt prompt="$(cat <list[GameMap] (all 10 floors), generate_floor(floor_index, rng)->GameMap engine/game_state.py GameSession dataclass + new_session(seed) main.py minimal but real: def main(argv=None)->int, detects SDL_VIDEODRIVER=='dummy' for headless, honors env UNDERDEPTHS_MAX_FRAMES, exposes new_game() BSP dungeon generation per plan.md: recursively split, carve rooms (4x4..10x8), L-corridors between siblings, 1-tile wall border, all 10 floors generated up front. Floors 0-8: place stairs_down on a FLOOR tile REACHABLE from spawn (verify with a flood fill — re-carve corridors until reachable). Floor 9 is the boss arena: single large room (20x15), NO stairs_down (None). spawn in the first room. Verify before finishing: python tests/smoke.py --phase 1 (must print PASS) Also eyeball the ASCII render it prints — '>' must appear on a reachable floor tile. EOF )" } phase2_build() { # Four independent systems, built SEQUENTIALLY (never parallel — shared files). run_dispatch "$(cat < set[tuple[int,int]] of visible tiles. Walls block sight but are themselves visible when adjacent to a visible floor tile. Do NOT modify map_gen.py. Verify: python tests/smoke.py --phase 2 (it tests fov now; other phase-2 parts may still fail — that's fine, just don't break phase 1). Finish fov only. EOF )" run_dispatch "$(cat < list[tuple]|None. Path EXCLUDES start, INCLUDES goal, [] when start==goal, None when unreachable. Treat walls + the `blocked` set as impassable. Do NOT modify map_gen.py or fov.py. Verify: python tests/smoke.py --phase 2 (pathfinding assertions should pass). EOF )" run_dispatch "$(cat <AttackRoll. Read .accuracy .evasion .power .armor .crit_chance (+optional .weapon_power) off the arguments (duck-typed). Formulas from plan.md: hit_chance = clamp(0.7 + (atk.accuracy - def.evasion)*0.05, 0.1, 0.95) base = atk.power + weapon_power ; reduced = max(0, base - def.armor) crit = rng.random() < atk.crit_chance ; damage = reduced*(2 if crit else 1) Miss => hit=False, damage=0. Do NOT modify map_gen/fov/pathfinding. Verify: python tests/smoke.py --phase 2 (combat assertions should pass). EOF )" run_dispatch "$(cat <None. Dispatch on enemy.behavior: wander / chase (A* toward player when in `visible`, else last_known_pos; adjacent=>melee via combat) / flee (hp<30% => move away) / ranged (shoot/kite per plan) / phase (move toward player ignoring walls, acts every 2 turns) / split (on death spawn 2 smaller). Read/write enemy.x/.y/.last_known_pos. Do NOT modify the engine/* systems. Verify: python tests/smoke.py --phase 2 (ALL of phase 2 must now PASS). EOF )" } phase3_build() { run_dispatch "$(cat <Enemy. Kinds: rat,goblin,skeleton_archer,orc_warrior,wraith,green_slime, ancient_dragon,small_slime. Stats EXACTLY per plan.md Enemy Roster (hp/power/armor/speed/behavior/xp). green_slime can_split=True. ancient_dragon armor 8 hp 120 power 15. data/items.py ITEM_DEFS dict + make_item(kind,x,y)->Item. Catalog per plan.md: rusty_dagger..war_hammer, leather/chain/plate armor, healing/strength/invisibility potions, fireball/ teleport/mapping scrolls. war_hammer power MUST be +10. entities/item.py Item dataclass: x,y,kind,name,category,stats(dict). entities/player.py Player: add inventory(list), equipped_weapon/equipped_armor, effect_timers(dict), total_power(), total_armor(), equip(item) (swap old back to inventory), gain_xp(amount)->int using the plan.md XP table (cumulative 30/70/140/250/400/600/850/1150/ 1500), level cap 10, FULL HEAL + stat gain on level-up. entities/enemy.py ensure Enemy has all contract fields (last_known_pos, can_split, speed, etc.). Do NOT break phases 1-2. Verify: python tests/smoke.py --phase 3 (must PASS). EOF )" } phase4_build() { # Large phase — split into sequential sub-builds BEFORE the single phase gate. run_dispatch "$(cat <GameSession that generates all 10 floors, places the player at floor-0 spawn, state='menu'/ 'playing'. engine/serializers.py: session_to_dict(session)->dict and session_from_dict(d)->GameSession (JSON-safe). Persist player (stats, level, xp, inventory, equipped, effect_timers, position), all 10 floors (tiles, explored, entities, stairs_down, spawn), current_floor, turn, log. Do NOT serialize the volatile `visible` grid (recomputed from FOV on load). Verify with a quick python -c round-trip; do not break earlier phases. EOF )" run_dispatch "$(cat <None translating logical keys into intents and mutating session: 'up/down/left/right' (move 1 tile; moving into an enemy = melee via combat; after the player acts, advance enemies via ai.behaviors + log messages), 'g' (pick up item under player into inventory), 'f' (descend ONLY if player stands on stairs_down; current_floor+=1; recompute FOV), 'i','e','q','r' (inventory/ equipment/potion/scroll menus or direct use), 'S' (save via serializers to save.json then state='saved'), '?' (How to Play), 'm' (mute toggle), 'escape'/'wait'. Dragon death on floor 9 => session.state='victory'. Player hp<=0 => state='dead'. engine/audio.py: AudioEngine(enabled=True) wrapping pygame.mixer — generate short in-memory tones (stdlib array); .play(name), .toggle_mute(), .muted bool, .available bool; NEVER raise (silent fallback if mixer init fails). main.py: full game loop, main menu (New Game / Continue if save.json exists / How to Play / Quit), How to Play screen (every control + the pickup/descent steps), death + victory screens, 'g'/'f' are driven by actions.apply_input. MUST detect headless via SDL_VIDEODRIVER=='dummy' (never force it in code) and honor env UNDERDEPTHS_MAX_FRAMES to exit after N frames. Expose new_game(seed)->GameSession. Do NOT break earlier phases. EOF )" run_dispatch "$(cat < cached pygame.Surface, rasterized once via pygame.draw from the grids — MUST include a 'stairs' sprite that is DISTINCT, non-empty, and glowing YELLOW (R>120,G>100,B<110), plus distinct sprites for player + all 7 enemies + items. render/renderer.py: Renderer.render(surface, session, camera_xy=(0,0)) draws map tiles + entities + items, and MUST blit the 'stairs' sprite on EVERY stairs_down tile (invisible stairs make the game unwinnable — a build failure). render/effects.py: radial torch-light from player (SIGHT_RADIUS falloff), explored-but-not-visible tiles dimmed, wall occlusion, screen vignette, particle bursts (hit/crit/death/pickup/level-up/stairs), screen-shake on damage. render/camera.py: smooth easing follow. NO external image files. Do NOT break earlier phases. Verify: python tests/smoke.py --phase 4 (must PASS — includes the stairs-rendered assertion and the dragon-kill -> victory assertion). EOF )" } # --------------------------------------------------------------------------- # run_phase : attempt-1 build dispatches, then gate->fix Ralph loop. # Returns 0 on gate PASS, 1 after MAX_RETRIES exhausted. # --------------------------------------------------------------------------- run_phase() { local n=$1 log "===== PHASE $n: build (attempt 1) =====" case "$n" in 1) phase1_build ;; 2) phase2_build ;; 3) phase3_build ;; 4) phase4_build ;; *) log "unknown phase $n"; return 1 ;; esac local attempt for attempt in $(seq 1 "$MAX_RETRIES"); do if run_gate --phase "$n"; then return 0 fi if [ "$attempt" -lt "$MAX_RETRIES" ]; then log "===== PHASE $n: fix attempt $((attempt + 1)) =====" dispatch_fix "--phase $n" "$GATE_OUT" || true fi done log "PHASE $n FAILED after $MAX_RETRIES gate attempts" log "last gate output:\n$GATE_OUT" return 1 } # --------------------------------------------------------------------------- # Goal backstop: after all 4 phases, verify EVERY acceptance criterion headlessly. # --------------------------------------------------------------------------- goal_loop() { log "===== GOAL BACKSTOP =====" if run_gate --goal; then return 0 fi local attempt for attempt in $(seq 1 "$MAX_RETRIES"); do log "===== GOAL fix attempt $attempt =====" dispatch_fix "--goal" "$GATE_OUT" || true if run_gate --goal; then return 0 fi done log "GOAL FAILED after $MAX_RETRIES attempts" log "last goal output:\n$GATE_OUT" return 1 } # --------------------------------------------------------------------------- # main # --------------------------------------------------------------------------- main() { local state state="$(cat "$STATE_FILE" 2>/dev/null || echo 0)" log "Underdepths pipeline starting. Last completed phase: $state" for n in 1 2 3 4; do if [ "$n" -le "$state" ]; then log "phase $n: already complete, skipping" continue fi if ! run_phase "$n"; then log "HALT: phase $n did not pass. See $DISPATCH_LOG and $LOG." exit 1 fi echo "$n" > "$STATE_FILE" log "phase $n COMPLETE (.build_state -> $n)" done if ! goal_loop; then log "HALT: goal backstop did not pass. See $DISPATCH_LOG and $LOG." exit 1 fi log "============================================================" log "BUILD COMPLETE: all 4 phases + goal backstop PASS." log "Play it: python main.py" log "============================================================" } main "$@"