(Underdepth) Prepare for Pass 5

This commit is contained in:
AlexKucera committed 2026-08-13 18:26:55 +02:00
1 parent 6147ab3121
commit 05e340dec2
29 files changed
-4888

No files matched your search

-470
View File
@@ -1,470 +0,0 @@
#!/usr/bin/env bash
# =============================================================================
# Underdepths — self-driving build pipeline.
#
# Drives the entire game build via `pi -p` (the DEFAULT model only — never
# passes --model/--provider), one dispatch per build phase, each gated by
# `python3 tests/smoke.py --phase N`. Resumable across crashes via .build_state.
# A goal backstop after phase 4 verifies EVERY acceptance criterion and loops
# fixes until all pass.
#
# Phases run SEQUENTIALLY (a hung worker would block bash `&`+`wait` forever;
# learned the hard way on this very project). Every dispatch is wrapped in
# `timeout --kill-after=30` because the pi (node) process ignores SIGTERM.
#
# State machine (.build_state = index of last completed phase):
# 0 -> nothing 1 -> P1 2 -> P2 3 -> P3 4 -> P4(4a+4b+gate) 5 -> goal
# =============================================================================
set -uo pipefail
cd "$(dirname "$0")"
STATE=.build_state
PIDF=.pipeline.pid
LOG_DIR=logs
mkdir -p "$LOG_DIR"
MAX_RETRIES=${MAX_RETRIES:-3}
TTL=${TTL:-3000} # ~50 min ceiling per dispatch
PY=${PY:-python3}
GATE="$PY tests/smoke.py"
COMPILE_GATE="$PY -m compileall -q engine render data entities ai main.py tests 2>&1 && echo COMPILE_OK"
# --- concurrency guard: never two pipelines in one directory ---------------
if [[ -f "$PIDF" ]]; then
old="$(cat "$PIDF" 2>/dev/null || true)"
if [[ -n "$old" && "$old" != "$$" ]] && kill -0 "$old" 2>/dev/null; then
echo "FATAL: orchestrate.sh (PID $old) already running in this dir." >&2
echo " The pipeline edits shared files concurrently; re-run a single" >&2
echo " instance after it finishes (it is resumable via .build_state)." >&2
exit 1
fi
fi
echo "$$" > "$PIDF"
trap 'rm -f "$PIDF"' EXIT
get_state() { [[ -f "$STATE" ]] && cat "$STATE" 2>/dev/null || echo 0; }
set_state() { echo "$1" > "$STATE"; }
halt() { echo "!!! PIPELINE HALTED at the phase above — see logs/ !!!" >&2; exit 1; }
# dispatch NAME PROMPT GATE_CMD
# Ralph loop: up to MAX_RETRIES, feeding the actual gate error back on retry.
dispatch() {
local name="$1" prompt="$2" gate="$3"
local attempt=0 gate_out gate_rc full_prompt
while (( attempt < MAX_RETRIES )); do
attempt=$((attempt + 1))
echo "==================================================================="
echo ">>> $name (attempt $attempt/$MAX_RETRIES) $(date +%H:%M:%S)"
echo "==================================================================="
if (( attempt == 1 )); then
full_prompt="$prompt"
else
full_prompt="$(printf '%s\n\n--- PREVIOUS ATTEMPT FAILED THE GATE (fix THIS specifically) ---\n%s\n\nDo not rewrite parts that already work. Make the gate pass.\n\n--- ORIGINAL TASK ---\n%s' \
"$prompt" "$(printf '%s' "${gate_out}" | tail -n 70)" "$prompt")"
fi
local logf="$LOG_DIR/${name}.attempt${attempt}.log"
# Run pi in its OWN session/process-group via setsid; a watchdog hard-SIGKILLs
# the entire group at TTL. GNU `timeout --kill-after` proved unreliable on this
# host (a hung pi worker lingered ~20 min past its deadline); the explicit
# whole-group kill is the dependable hammer. (setsid ships via util-linux.)
setsid bash -c 'pi -p -a --name "$0" @plan.md "$1" > "$2" 2>&1' \
"$name" "$full_prompt" "$logf" &
local job=$!
( sleep "$TTL"; kill -KILL -"$job" 2>/dev/null; ) &
local wd=$!
wait "$job" 2>/dev/null
local rc=$?
kill "$wd" 2>/dev/null; wait "$wd" 2>/dev/null
if (( rc != 0 )); then
echo " ! dispatch ended (rc=$rc; timeout or error); tail of log:" >&2
tail -n 8 "$logf" >&2
fi
echo " gate: $gate"
gate_out="$(eval "$gate" 2>&1)"
gate_rc=$?
printf '%s\n' "${gate_out}" | tail -n 35
if (( gate_rc == 0 )); then
echo "<<< $name PASS"
return 0
fi
echo " ! gate failed (attempt $attempt, rc=$gate_rc)"
done
echo "<<< $name FAILED after $MAX_RETRIES attempts — full log: $LOG_DIR/${name}.attempt${MAX_RETRIES}.log" >&2
return 1
}
# =============================================================================
# Shared preamble prepended to every worker prompt.
# =============================================================================
read -r -d '' SHARED <<'SHARED_EOF' || true
You are building "Underdepths", a turn-based roguelike in Python 3 + pygame-ce.
@plan.md is the COMPLETE design spec — READ IT before writing anything.
AGENTS.md (auto-loaded) holds the project conventions; follow them.
CONTRACT (authoritative): tests/smoke.py is your verification gate AND its
module docstring defines the EXACT public API you must implement — dataclass
fields, function names + signatures, return shapes. Implement to that API.
Run `python3 tests/smoke.py --phase N` repeatedly until it prints
`phase N: PASS`. You MAY correct smoke.py ONLY if an expectation directly
contradicts plan.md; NEVER weaken a behavioural assertion to pass trivially.
HEADLESS RULE (getting this wrong fails the whole build): smoke.py sets
SDL_VIDEODRIVER=dummy. In main.py NEVER force headless with
os.environ.setdefault("SDL_VIDEODRIVER","dummy") or setdefault on the audio
driver — that makes `python3 main.py` silently run headless and exit on every
real machine. Instead detect headless from the ENVIRONMENT the test sets:
headless = os.environ.get("SDL_VIDEODRIVER","").lower() == "dummy"
When headless is True, run a scripted self-check loop:
main(max_frames=K) runs at most K frames then returns. When headless is False,
open a REAL window with REAL audio and play normally. `python3 main.py` with no
environment variables MUST launch the playable game window.
IMPLEMENTATION RULES:
- @dataclass(slots=True) for all entities and state objects. Type hints on every
function signature. Constants in data/constants.py. No magic numbers in logic.
- NO stubs, NO TODO comments, NO placeholders. Every function has a real,
working implementation. If a file lists a function, it must work.
- All art is procedural pixel-art drawn with pygame.draw from in-code palettes —
NO external image / sprite-sheet / font / audio asset files. pygame.font.SysFont
only. Plain flat colored rectangles for entities/tiles are NOT acceptable.
- Every combat event, item pickup, level-up, and status change must append a
human-readable message to session.log (the message log is primary feedback).
- Use the standard library (json, random, math, dataclasses, heapq, array).
Represent grids as list[list[int]] (tiles) and list[list[bool]] (explored /
visible) — no numpy dependency. GameSession is the single source of truth.
- Rendering reads GameSession and draws; it never mutates game state.
SHARED_EOF
# =============================================================================
# Phase 1 — Foundation
# =============================================================================
read -r -d '' P1 <<'P1_EOF' || true
BUILD PHASE 1 — Foundation. Make `python3 tests/smoke.py --phase 1` print PASS.
Create these files (add __init__.py to data/, entities/, engine/, ai/, render/):
data/constants.py
TILE=20, MAP_WIDTH=80, MAP_HEIGHT=50, SIGHT_RADIUS=8, FLOORS=10
COLORS / PALETTE dicts (wall dark gray ~ (60,60,70) visible / (30,30,35)
explored; floor (40,35,30)/(20,18,15); per-enemy accent hues; item accents
yellow/blue/red/cyan; stairs yellow). The full XP/level-up table from plan
(levels 1->2 ... 9->10: cumulative XP 30,70,140,250,400,600,850,1150,1500;
HP/power gains per plan). Per-floor enemy/item count distribution from plan.
entities/entity.py
@dataclass(slots=True) Entity(x:int, y:int, name:str, sprite_key:str,
blocks:bool=True).
entities/player.py
@dataclass(slots=True) Player(Entity) with the base stats from plan
(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, equipped:dict, effects:list,
facing="down", name="You", sprite_key="player", blocks=True).
Methods: total_power()->int (base + equipped weapon power + strength effect),
total_armor()->int (base + equipped armor), gain_xp(amount)->bool that applies
the level-up table (level up may chain multiple levels), fully heals and
increases max_hp/power per the table, logs "You reach level N!", returns True
if any level-up occurred. Implement the FULL level table now.
entities/enemy.py
@dataclass(slots=True) Enemy(Entity) with hp,max_hp,power,armor,accuracy,
evasion,crit_chance,speed,behavior,xp_value, plus last_known_pos (tuple|None),
act_counter:int=0, can_split:bool=True, ranged_power:int=0.
ENEMY_KINDS list of all seven. make_enemy(kind,x,y)->Enemy returning the FULL
stat roster from plan's Enemy Roster table (rat/goblin/skeleton_archer/
orc_warrior/wraith/green_slime/ancient_dragon). Dragon ranged_power>=15.
engine/map_gen.py
@dataclass(slots=True) Rect(x,y,w,h) with a .center property returning (x+w//2,
y+h//2). @dataclass(slots=True) GameMap(width,height,tiles,rooms,explored,
visible,entities,stairs_down,floor_index) exactly per the contract docstring.
generate_dungeon(floor_index,width=80,height=50)->GameMap using BSP: all walls,
5-8 recursive splits alternating axis, carve a room (4x4..10x8, shrunk 1-2 from
region edge) per leaf, connect siblings with L-shaped corridors, place stairs_down
in the room farthest from spawn. Floor 9 is the BOSS ARENA: a single large room
(~20x15) — exactly ONE room with w>=15 and h>=10. Floors 0-8 have >=3 rooms,
a solid 1-tile wall border on all four edges, no overlapping rooms, and every
room reachable from every other via floor-tile flood fill. is_walkable(map,x,y)
->bool (in bounds and tile==1). populate(map,floor_index,rng=None) places
ENEMIES per plan's per-floor distribution (floor 9: just the dragon + leave room
for 2 potions; items are added in phase 3 so do not place items yet). Ensure
populate never raises on any floor 0-9.
main.py
A MINIMAL entry for now: define main(max_frames=None) that, when
SDL_VIDEODRIVER==dummy, runs a tiny headless self-check (generate a dungeon,
print nothing fatal) and returns; otherwise prints "Underdepths — phase 1
scaffold". It will be FULLY rebuilt in phase 4. Obey the HEADLESS RULE.
P1_EOF
P1="$(printf '%s\n\n%s' "$SHARED" "$P1")"
# =============================================================================
# Phase 2 — Core systems (FOV, A*, combat, minimal game state, chase AI)
# =============================================================================
read -r -d '' P2 <<'P2_EOF' || true
BUILD PHASE 2 — Core systems. Make `python3 tests/smoke.py --phase 2` print PASS.
Do NOT regress phase 1 (re-run --phase 1 if unsure).
engine/fov.py
compute_fov(game_map, ox, oy, radius=8) -> set of (x,y) visible tiles, using
RECURSIVE SHADOWCASTING over 8 octants (write it from scratch, no library).
Walls block sight but a wall adjacent to a visible floor tile is itself
visible. Mutate game_map.visible accordingly and RETURN the visible set.
engine/pathfinding.py
astar(game_map, start, goal, blocked=frozenset()) -> list[(x,y)] | None, grid
A* with Manhattan heuristic. Walkable = in-bounds floor tile not in `blocked`
and not a wall. Return the path excluding the start node's duplicate; None if
unreachable or if start/goal is a wall/out of bounds.
engine/combat.py
attack(attacker, defender, rng=None, log=None) -> dict with keys
hit:bool, damage:int, crit:bool, killed:bool. Use plan's formulas:
hit_chance = clamp(0.7 + (attacker.accuracy - defender.evasion)*0.05, 0.1, 0.95);
on hit, base = attacker.power(+weapon bonus via total_power for the player),
reduced = max(0, base - defender.armor), crit doubles damage, apply to
defender.hp, killed = defender.hp <= 0. If log is a list, append the plan's
human messages ("You hit the Goblin for 8 damage!", "Critical hit! ...",
"Goblin misses you"). The attacker may be Player (use total_power/total_armor)
or Enemy (use raw stats). rng defaults to random.Random().
engine/game_state.py
@dataclass(slots=True) GameSession holding player, dungeon (list of 10
GameMap), current_floor:int, log:list[str], turn:int, state:str
("playing"/"dead"/"victory"/"menu"), plus an rng. new_game(seed=None)->
GameSession: build the player, generate all 10 floors (generate_dungeon),
populate enemies, place the player in the first room center of floor 0,
init log/turn, set state="playing". recompute_fov(session): clear visible,
compute_fov from the player, merge into explored. (Items/inventory wiring is
phase 3; keep new_game minimal but functional.)
ai/behaviors.py
take_enemy_turn(enemy, session, rng=None) dispatching on enemy.behavior.
Implement at least: wander (random walkable step or wait), chase (A* toward
player when player visible via FOV, else toward last_known_pos; adjacent ->
melee via combat.attack into session.log), and a stub for the others (you will
finish flee/ranged/phase/split in phase 3). Respect speed (speed==2 acts every
other turn via act_counter). Enemies must not stack (treat other entities as
blocked). Update last_known_pos when the player is visible.
P2_EOF
P2="$(printf '%s\n\n%s' "$SHARED" "$P2")"
# =============================================================================
# Phase 3 — Content: items, inventory, equipment, scrolls, full AI, XP wiring
# =============================================================================
read -r -d '' P3 <<'P3_EOF' || true
BUILD PHASE 3 — Content layer. Make `python3 tests/smoke.py --phase 3` pass.
Do NOT regress phases 1-2.
entities/item.py
@dataclass(slots=True) Item(Entity) with item_type ("weapon"/"armor"/
"potion"/"scroll"), subtype (e.g. "healing","strength","invisibility",
"fireball","teleport","mapping"), stats:dict, name, sprite_key.
make_item(name,x,y)->Item implementing the FULL catalog from plan: Rusty
Dagger(+2), Short Sword(+4), Battle Axe(+7), War Hammer(+10 power, crit -5%),
Leather Armor(armor 2), Chain Mail(armor 4), Plate Armor(armor 7, evasion -10%),
Healing Potion(heal 30), Strength Potion(+5 power/20 turns), Invisibility
Potion(invisible/15 turns), Scroll of Fireball(20 dmg radius 3), Scroll of
Teleport, Scroll of Mapping. Player.total_power/total_armor must read the
equipped weapon/armor stats.
engine/actions.py (full gameplay actions; pure functions on GameSession)
try_move(session, dx, dy)->bool: if target tile has an enemy -> melee
(combat.attack player->enemy, log, award XP + handle death/split, check win);
else move player if walkable & unblocked; then advance enemy turns + recompute
FOV + tick effect timers. Return whether the player acted.
pickup(session)->bool: if an Item is under the player, move it to inventory
(or auto-consume potions? NO — into inventory), log "You pick up X", return True.
descend(session)->bool: if player on stairs_down, current_floor+=1, place
player at that floor's spawn/first room center, recompute FOV, log descent.
Return False if not on stairs or already on floor 9 (no stairs there pre-win).
use_item(session, item): potions -> apply effect (heal capped at max_hp;
strength/invisibility push a timed Effect into player.effects), scrolls ->
fireball (20 dmg to all enemies within 3 of player), teleport (random walkable
tile), mapping (set entire current floor explored True); consume (remove from
inventory). Equippables -> equip(session,item).
equip(session,item): place in the right slot, move old item back to inventory,
apply stat mods via total_power/total_armor (War Hammer crit -5%, Plate evasion
-10%). Log "You equip X".
ai/behaviors.py (COMPLETE the behavior set)
Finish flee (HP<30% -> move away, else chase), ranged/kiting (skeleton archer:
fire ranged_attack at range>3 using ranged_power with a distance penalty;
step away when adjacent <=2; wander when no sight), phase (wraith: move toward
player IGNORING walls, acts every 2 turns via act_counter), and the dragon's
boss behavior (chase + every 3rd turn breath weapon: 15 damage to all tiles in
a line toward the player). on_death(enemy, session): if green_slime and
can_split, spawn TWO smaller slimes (half hp, half power, can_split=False,
name "Small Slime") into the floor entities and log it; always award XP via
player.gain_xp and remove the corpse. Slime small variants must not split.
engine/game_state.py (extend)
new_game must now also place ITEMS per plan's distribution (extend populate or
spawn items alongside enemies; floor 9 gets exactly 2 healing potions near the
entrance + the dragon). Add a player.invisible flag (True while an invisibility
effect is active — enemies then cannot see the player). Effect timers tick down
each turn (try_move end) and expire. Death -> state="dead"; killing the dragon
on floor 9 -> state="victory".
data/items.py and data/enemies.py (optional)
You may keep catalogs inline in the entity modules OR factor them here; either
is fine. Do not duplicate the make_enemy/make_item contract.
P3_EOF
P3="$(printf '%s\n\n%s' "$SHARED" "$P3")"
# =============================================================================
# Phase 4a — Persistence + audio + state transitions
# =============================================================================
read -r -d '' P4A <<'P4A_EOF' || true
BUILD PHASE 4a — Persistence + resilient audio. Do NOT regress phases 1-3.
This is the first half of phase 4; the render/UI/main half follows in 4b.
engine/serializers.py
session_to_dict(session)->dict and dict_to_session(d)->GameSession giving an
EXACT round trip. Serialize: player (all stats, level, xp, inventory, equipped,
position, effects with remaining turns, facing), all 10 floors (tiles, rooms,
explored, entities, stairs_down, floor_index), current_floor, turn, log, state.
Do NOT serialize the `visible` grids — they are recomputed via recompute_fov on
load. dict_to_session must reconstruct Player/Enemy/Item objects (store a type
discriminator per entity) and call recompute_fov. Tiles as list[list[int]],
explored as list[list[bool]] serialize directly with json.
engine/audio.py
AudioManager class. Generate short tones in memory with stdlib array.array +
pygame.mixer.Sound(buffer=...) (NO audio asset files). Provide play(name) for
events: hit, miss, damage, pickup, use, stairs, levelup, death, victory.
toggle_mute()->mutes/unmutes; .muted bool. CRITICAL: every public method must
be wrapped so that ANY mixer init / Sound creation failure disables audio
silently and never raises — the game stays fully playable with no audio device.
Initialize the mixer once, lazily and defensively.
engine/game_state.py (extend)
save(session, path="save.json") writes session_to_dict via json to the game
directory; load(path) reads it. On player death: state="dead" AND delete
save.json (permadeath). On victory: state="victory" and delete save.json.
Keep new_game/recompute_fov working. Add a helper has_save(path) used by the
menu (phase 4b).
You only write logic here; rendering and the full main loop come in phase 4b.
Run `python3 tests/smoke.py --phase 1`, `--phase 2`, `--phase 3` to confirm no
regression; phase 4 gate runs after 4b.
P4A_EOF
P4A="$(printf '%s\n\n%s' "$SHARED" "$P4A")"
# =============================================================================
# Phase 4b — Procedural pixel-art, rendering, juice, full main loop + UI
# =============================================================================
read -r -d '' P4B <<'P4B_EOF' || true
BUILD PHASE 4b — Visuals, UI, and the full game loop. Make
`python3 tests/smoke.py --phase 4` print PASS. Do NOT regress phases 1-3.
Phase 4a already added serializers.py, audio.py, and save/load.
data/sprites.py
2D grids of single-char palette keys (e.g. "." transparent, "K" outline,
shades) for EVERY entity, tile, item, and stairs — roughly 12x12..16x16 cells.
Each of the 7 enemies + the player + each item category + stairs must be
DISTINCT and recognizable (not recolors): hooded adventurer whose equipped
weapon/armor change the sprite; rat (tail/ears/whiskers); goblin (ears/
loincloth); skeleton archer (bow/quiver/glowing eyes); orc warrior (tusks/
big blade); wraith (tattered cloak, no legs); green slime (glossy, googly
eyes, drip); ancient dragon (horns/wings/scales/fangs). 2-3 idle frames each.
render/sprites.py
Rasterize a palette-key grid to a pygame.Surface ONCE and cache by
(name,frame,SCALE). The renderer blits the cached surface scaled to TILE.
render/effects.py
Radial torch-light centered on the player out to SIGHT_RADIUS (brightness
falloff), explored-not-visible tiles remembered but tinted dark blue-gray and
dimmer, walls occlude light (derived from the FOV/visible grid), soft screen
vignette. Particle bursts (hit sparks, crit star burst, blood/slime/ash poof
on death, level-up stars, pickup sparkle, stairs shimmer) — pool and cap
counts. Screen-shake on player damage (decaying offset). Floating combat text
(-8, MISS!, CRIT!). Soft ellipse shadows under entities.
render/camera.py
Viewport offset that eases toward the player each frame. Show ~48x28 tiles.
render/renderer.py (PURE: reads GameSession, never mutates)
Compose: map tiles (beveled walls w/ lighter top edge + darker bottom + seeded
per-tile variation; dithered floor with flecks), entities + items + stairs,
lighting overlay, particles, shadows, screen-shake, camera offset. UI: bordered
panels (1px pixel frame, inner bevel); top bar (Floor N/10, HP bar with heart
icon, Level, XP bar); right panel (last ~8 log messages, color-coded: combat
white, damage red, level-up green, items yellow); bottom bar (equipment slots
as pixel-art icons, active effect timers, sound on/off icon); context prompt
line styled as UI — on an item show "Press G to pick up <name>", on stairs
show "Press F to descend". pygame.font.SysFont only.
main.py (FULL rebuild)
State machine: menu -> playing -> dead / victory / saved. Obey the HEADLESS
RULE precisely (detect SDL_VIDEODRIVER==dummy; main(max_frames=K) runs a
scripted headless self-check of K frames then returns; real launches open a
window with audio). Main menu: New Game (generate dungeon, then show How to
Play before the first turn), Continue (only if save.json exists), How to Play
(always; explains EVERY control), Quit. How to Play must be reachable from the
menu and shown before every New Game, and reopened with `?` during play.
Controls from plan: arrows/hjkl move-attack, g pickup, i inventory, e
equipment, q quaff, r read scroll, f descend (on stairs), S save+quit,
? help, m mute, Esc close menus. Show contextual "Press G to pick up" on an
item and "Press F to descend" on stairs. Death screen: "You died on floor N.
You reached level M." Victory: "You slew the Ancient Dragon! ...". Press any
key -> menu. Initialize audio at the app boundary; keep playable if it fails.
P4B_EOF
P4B="$(printf '%s\n\n%s' "$SHARED" "$P4B")"
# =============================================================================
# Phase 4 gate + goal backstop prompts
# =============================================================================
read -r -d '' P4FIX <<'P4FIX_EOF' || true
VERIFY AND FIX PHASE 4. Run `python3 tests/smoke.py --phase 4`. If it already
prints `phase 4: PASS`, change nothing. If it fails, read the failure, open the
relevant file(s) among engine/serializers.py, engine/audio.py, engine/actions.py,
engine/game_state.py, render/*, data/sprites.py, main.py, and fix the SPECIFIC
failure without regressing phases 1-3 (re-run --phase 1/2/3 to be sure). Do not
weaken smoke assertions.
P4FIX_EOF
read -r -d '' PGOAL <<'PGOAL_EOF' || true
GOAL BACKSTOP. The four phase gates should already pass. Now verify EVERY
acceptance criterion in @plan.md end to end:
1. Run `python3 tests/smoke.py --goal`. It must print "[goal] ALL ACCEPTANCE
CRITERIA PASS". If any criterion fails, read the failure and fix the SPECIFIC
gap in the code (you may touch any file) without weakening smoke assertions.
2. Confirm `python3 main.py` is structured to launch a real window with audio
when SDL_VIDEODRIVER is NOT dummy (do NOT actually open a window here — just
confirm the headless branch is env-gated, not forced).
3. Re-run `python3 tests/smoke.py --goal` until it passes.
The game must be complete and playable: 10 floors, 7 enemies, A*, FOV, BSP,
combat with crits, XP/leveling, items/inventory/equipment, save/load, win + lose
states, How to Play, contextual g/f prompts, resilient audio, and distinct
procedural pixel-art with lighting + particles.
PGOAL_EOF
PGOAL="$(printf '%s\n\n%s' "$SHARED" "$PGOAL")"
# =============================================================================
# Main driver
# =============================================================================
echo "Underdepths build pipeline — state=$(get_state) ttl=${TTL}s retries=${MAX_RETRIES}"
s="$(get_state)"
if (( s < 1 )); then dispatch phase1-foundation "$P1" "$GATE --phase 1" && set_state 1 || halt; fi
s="$(get_state)"
if (( s < 2 )); then dispatch phase2-core "$P2" "$GATE --phase 2" && set_state 2 || halt; fi
s="$(get_state)"
if (( s < 3 )); then dispatch phase3-content "$P3" "$GATE --phase 3" && set_state 3 || halt; fi
s="$(get_state)"
if (( s < 4 )); then
dispatch phase4a-persist "$P4A" "$COMPILE_GATE" || halt
dispatch phase4b-visuals "$P4B" "$COMPILE_GATE" || halt
dispatch phase4-gate "$P4FIX" "$GATE --phase 4" && set_state 4 || halt
fi
s="$(get_state)"
if (( s < 5 )); then dispatch goal-backstop "$PGOAL" "$GATE --goal" && set_state 5 || halt; fi
echo
echo "==================================================================="
echo "BUILD COMPLETE — all phase gates + goal backstop PASS."
echo "Play it: python3 main.py"
echo "Verify: python3 tests/smoke.py --goal"
echo "==================================================================="