# AGENTS.md — Underdepths Roguelike ## Project Building "Underdepths," a turn-based roguelike dungeon crawler in Python. Read `plan.md` for the complete game design document. It is the source of truth for all gameplay mechanics, data, and acceptance criteria. ## Tech Stack - Python 3.11+ - pygame-ce (rendering + input + generated audio) - Standard library for everything else (json, random, math, dataclasses, heapq, array) - No other third-party packages unless absolutely necessary ## Conventions - Use `@dataclass(slots=True)` for all game entities and state objects. - Type hints on every function signature. - Constants live in `data/constants.py`. No magic numbers scattered in logic. - Functions are small and named clearly. No comments explaining *what*, only *why*. - Error handling at boundaries: file I/O (save/load), user input. Game logic should never raise on valid game states. - The message log is the primary feedback mechanism. Every combat event, item pickup, level-up, and status change must log a human-readable message. - Rendering is pure: it reads `GameSession` and draws, never mutates state. Split it into `renderer` (composition), `render/sprites` (pixel-art rasterization + Surface caching), and `render/effects` (lighting/particles). Cache sprite Surfaces; do not rebuild them per frame. ## Architecture Rules - `GameSession` (in `engine/game_state.py`) is the single source of truth for all mutable state. It is what gets serialized for save/load. - Systems are pure functions that take state and return new state or mutate in place. No hidden global state. - Rendering reads from `GameSession`; it never mutates game state. - Input handling translates key presses into intent (move, pickup, use item), which the game loop applies to state. ## Orchestration This project uses a **self-driving build pipeline**. Your first action is to write `orchestrate.sh` — a bash script that drives the entire build using `pi -p` (non-interactive mode) as the build primitive. Then you execute it. All `pi -p` dispatches use the DEFAULT model — never pass `--model` or `--provider`. The entire build must run on whatever model is configured as the default, so it works unchanged on any default model. ### How it works ``` orchestrate.sh ├── reads .build_state to find last completed phase ├── for each remaining phase: │ ├── dispatches build work via `pi -p ""` │ ├── runs the phase gate (python tests/smoke.py --phase N) │ ├── if gate fails: feeds error output back via `pi -p ""` │ ├── Ralph loop: retries up to MAX_RETRIES until gate passes │ └── on pass: advances .build_state ├── after all phases: goal check — verifies ALL acceptance criteria │ ├── if any fail: dispatches targeted fix via `pi -p` │ └── loops until all pass or MAX_RETRIES exhausted └── prints build summary ``` ### State machine `.build_state` is a single integer: the index of the last completed phase. This makes the pipeline **resumable** — if it crashes, re-running `orchestrate.sh` picks up where it left off. Delete `.build_state` to start over. ### Phase definitions Each phase has: a name, a build directive (what to tell `pi -p`), and a gate command (what to run to verify). The script defines them inline. **Phase 0 — Orchestration setup:** Write `orchestrate.sh`, `tests/smoke.py` (stub with phase functions), and `.build_state`. This phase is you — you write it directly, not via `pi -p`. **Phase 1 — Foundation:** - Build: `data/constants.py`, `entities/entity.py`, `engine/map_gen.py`, `entities/player.py`, `entities/enemy.py`, minimal `main.py` game loop. - Gate: generate at least 5 maps, assert each has 8–12 BSP rooms, all rooms reachable via flood fill, no room overlaps, and every stored corridor path has `len(path) - 1 <= MAX_CORRIDOR_LENGTH == 14`. Verify every path tile is floor, every endpoint touches a recorded room or junction, and the generator carved no unrecorded corridors. On floors 0–8, `stairs_down` must be a floor tile reachable from the spawn room. Print an ASCII render and the measured longest section. **Phase 2 — Core Systems (parallelizable):** FOV, A*, and combat are independent. Dispatch them as separate `pi -p` calls that can run concurrently: - `engine/fov.py` — recursive shadowcasting, sight radius 8 - `engine/pathfinding.py` — A* with Manhattan heuristic - `engine/combat.py` — hit chance, damage reduction, crits - `ai/behaviors.py` — depends on pathfinding + FOV, build after those land - Gate: FOV (walled-in player sees only self), A* (path exists between any two floor tiles), combat (1000 simulated attacks, damage in expected range), AI (enemy chases player through a test corridor) **Phase 3 — Content Layer:** - Items, inventory, weapon/armor/boots equipment, potions, scrolls - Guaranteed Shoes of Hermes on display floor 2 and Hunter's Bow on display floor 3 - Bow ranged attack and the Shoes' held-running capability flag - XP, leveling, progression - All 7 enemy types with behaviors; regular-floor initial density is exactly `4 + 2 * floor_index` (4, 6, 8, …, 20) - Boss arena on floor 9 - Gate: spawn each enemy type and verify stats; verify exact strictly increasing density on floors 0–8 and the guaranteed reachable Shoes/Bow placements. Equip every slot and verify stat/capability changes. Through the normal Bow action, place a nearer chasing target and a farther fleeing target and verify the fleeing target is selected; place a target behind a wall and verify it cannot be hit; verify a valid shot spends a turn and can damage/kill with correct logs. Kill an enemy and verify XP + level-up at threshold. **Phase 4 — Polish, Visuals, Audio & Persist:** - Save/load JSON, menu system, death/victory screens, UI panels - A visible How to Play screen, contextual pickup/stairs prompts, and simple generated sound effects with graceful silent fallback - Poll held direction keys only while Shoes of Hermes are equipped: one immediate step, 180 ms initial delay, 75 ms repeat, one complete turn per repeated step, immediate stop on release/block/menu/floor/state change/death/victory - Procedural pixel-art sprites / effects / lighting / UI per plan.md Rendering, including distinct Bow and winged Shoes (`data/sprites.py`, `render/sprites.py`, `render/effects.py`) - This phase is large — split it into sequential sub-dispatches (e.g. 4a persistence+audio, 4b actions+render+sprites+main) that run BEFORE the single phase gate, if one dispatch cannot finish within the TTL - Gate: save → load → assert state equality including weapon/armor/boots; all menu states reachable; simulated `g` pickup and `f` descent work. Drive the real movement input clock: without Shoes, holding moves once; with Shoes, assert no repeat at 179 ms, one at 180 ms, then one per 75 ms, and no further movement after release, block, menu, floor change, death, or victory. Through real `b` input, assert the Bow prefers a fleeing target over a nearer chaser, cannot shoot through a wall, spends a turn, and can kill. Audio-disabled mode does not crash; **stairs are visibly rendered** with a distinct stairs sprite on `stairs_down`. ### Goal backstop After Phase 4, the script does NOT declare success. It runs a final goal check: `pi -p` with a prompt that reads every acceptance criterion in `plan.md`, runs `python main.py` headless for a smoke playthrough, and reports which checkboxes pass/fail. Any failure gets dispatched as a fix task. The loop repeats until ALL criteria pass. This is the backstop that prevents early stopping — the pipeline cannot exit successfully while any criterion is unmet. ### Retry semantics Gates that fail feed the actual error output (stdout + stderr) back into the next `pi -p` call, not just "try again." The agent sees what broke and fixes specifically that. Max 3 retries per phase before the pipeline halts with a diagnostic. ### Operational hardening (learned the hard way) - Bound EVERY `pi -p` dispatch with a hard TTL and SIGKILL escalation. Use GNU `timeout --kill-after=30` when available, or Homebrew's `gtimeout` on macOS. Detect the executable at startup. If neither exists, implement the same behavior with Python stdlib `subprocess.Popen(start_new_session=True)`, `wait(timeout=...)`, and `os.killpg(..., signal.SIGKILL)`; never run an unbounded dispatch. The pi (node) process ignores SIGTERM, so plain timeout handling can stall the pipeline. - Never run two `orchestrate.sh` instances in the same directory at once: concurrent `pi -p` agents editing the same files corrupt them. The pipeline is resumable via `.build_state` — just re-run a single instance. - If a phase is too large for one bounded dispatch (the agent emits little/no output as it nears the TTL — it is over-planning), split it into sequential sub-dispatches that run before the single phase gate. Phase 4 (game-state + serializers + audio + actions + render + sprites + main) is the usual candidate. - A per-dispatch TTL around 50 minutes is a sane ceiling. ## Build Order Follow the phase definitions in the Orchestration section above. Build incrementally. Run `python tests/smoke.py --phase N` after each phase. Do not proceed if it fails. Fix the failure, then continue. ## Definition of Done ALL acceptance criteria in `plan.md` → Acceptance Criteria section must pass. The game must be playable start to finish via `python main.py`. It must not crash. It must have win and lose states. It must save and load. Corridors must stay within the 14-step section limit, monster density must rise every regular floor, Shoes of Hermes must provide deliberate hold-to-run, and the Bow must let the player shoot visible fleeing enemies. Controls must be explained in-game, with contextual prompts for item pickup and stairs. It must look polished: distinct procedural pixel-art sprites, FOV lighting, particle juice, and a clean bordered UI — not flat colored squares. When you believe you are done: 1. Run `python tests/smoke.py` — must pass. 2. Run `python main.py` and play through: read How to Play, move, fight, stand on an item and press `g`, equip Shoes of Hermes and hold/release a direction, equip the Hunter's Bow and shoot a fleeing enemy with `b`, stand on stairs and press `f`, save, quit, relaunch, and continue. Confirm sound effects play when audio exists and the game still works when audio initialization fails. 3. Generate multiple maps and inspect the longest corridor plus regular-floor enemy counts. 4. Check every acceptance criterion checkbox in `plan.md`. 5. If anything fails, fix it. Do not stop until all pass. ## What Kills Entries - **Crashes during play.** Every code path must be safe. Test edge cases: empty inventory, no item at feet, attacking a full-HP enemy, and attempting descent on floor 9 where `stairs_down` is `None` (it must safely do nothing). - **Hidden or broken controls.** The game must visibly explain controls. While the player stands on an item show `Press G to pick up`; while on stairs show `Press F to descend`. Automated tests must exercise both actions. - **Systems that don't actually work.** If A* is there but enemies walk into walls, the judge sees that. Each system must be genuinely functional. - **Long, empty traversal.** Every generated corridor section must be at most 14 steps, and initial monster counts on floors 0–8 must be exactly 4 through 20 in increments of 2. Tests must measure both rather than trusting constants. - **Fake mobility or ranged items.** Shoes of Hermes must poll held keys and apply complete turns until release; OS key repeat is not the feature. The guaranteed Hunter's Bow must fire with `b`, respect visibility/range/walls, spend a turn, and be able to damage and kill a fleeing enemy. - **Unwinnable floors.** Every floor 0–8 MUST have stairs on a floor tile reachable from spawn AND visibly rendered (the `>` staircase) so the player can find it and press `f` to descend. Floor 9 is won by slaying a dragon the player can actually damage with floor-9 gear. Missing, unreachable, or invisible stairs — or an unkillable boss — fail the build. The previous build shipped stairs that existed in the map data but were never drawn, so the game had no visible way down: do not repeat this. - **Stopping early.** The prompt must produce a complete game. If you finish a phase and the acceptance criteria aren't all met, keep building. - **Flat colored-square art.** Entities/tiles drawn as plain rectangles read as unfinished. Procedural pixel-art sprites (distinct per type), lighting, and particles are required — see plan.md Rendering. ## Anti-Patterns to Avoid - Don't add networking, and don't load external image / sprite-sheet / font / audio asset files. All art is procedural pixel-art drawn from in-code palettes with `pygame.draw`. Plain flat colored rectangles for entities or tiles are NOT acceptable — they read as unfinished; see plan.md Rendering. - Don't add music, external audio files, or a complex audio engine. Generate a few short tones with pygame and continue silently if no audio device exists. - Don't build a character creation screen or class system. - Don't add crafting or shops. - Don't write more files than needed — merge where natural. - Don't stub functions. Every function must have a real implementation.