# 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 5 maps, assert each has ≥3 rooms, all rooms reachable via flood fill, no room overlaps, and (floors 0–8) `stairs_down` is a floor tile reachable from the spawn room. Print ASCII render to confirm. **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, equipment, potions, scrolls - XP, leveling, progression - All 7 enemy types with behaviors - Boss arena on floor 9 - Gate: spawn each enemy type, verify stats. Equip item, verify stat changes. Kill enemy, 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 - Procedural pixel-art sprites / effects / lighting / UI per plan.md Rendering (`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; all menu states reachable; simulated `g` pickup and `f` descent work; audio-disabled mode does not crash; **stairs are visibly rendered** (the renderer blits a distinct stairs sprite on `stairs_down` — assert this, since invisible stairs make the game unwinnable). ### 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) - Wrap EVERY `pi -p` dispatch in `timeout --kill-after=30 `. The pi (node) process ignores SIGTERM, so plain `timeout ` lets a stuck dispatch linger past its deadline and stall the whole loop. `--kill-after` escalates to SIGKILL. - 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. 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`, 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. Check every acceptance criterion checkbox in `plan.md`. 4. 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 with full HP enemy, descending stairs on the last floor. - **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. - **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.