# HANDOFF REPORT — MAP SPEC MINER

> **Archetype**: Specification Miner  
> **Working Directory**: `c:\Projects\FreeExile\.agents\teamwork\spec_miner_map`  
> **Parent Conversation ID**: `1cc48fc5-ce57-4f48-8964-24cab4bfcacc`  
> **Deliverable Path**: `c:\Projects\FreeExile\.agents\teamwork\spec_miner_map\report.md`  
> **Timestamp**: 2026-10-01T19:28:00Z  

---

## 1. Observation

1. **Authoritative Specification Request (`ORIGINAL_REQUEST.md` line 172-314)**:
   - Section `## 2026-10-01T19:19:13Z` mandates 5 core technical requirements (R1–R5) plus non-negotiable regression criteria for an open-world procedural tile map overhaul based on PoE2 principles.
   - Quotation: *"Server-side procedural dungeon generator (BSP rooms, corridors, boss room, A* pathfinding, anti-bot obstacles) đã có nhưng client chưa nhận/render tile grid từ server. Đây là nền tảng cần tận dụng... Tile map mỗi zone wilderness có kích thước tối thiểu 60×45 tiles (zone đầu) đến 120×90 tiles (zone cuối). Format gửi: compact Uint8Array (1 byte/tile) thay vì JSON object array để tiết kiệm bandwidth."*
   - Quotation: *"Viewport Culling: Tính tileMinX, tileMaxX, tileMinY, tileMaxY từ camera position và viewport size. Chỉ loop và drawImage các tile nằm trong viewport + 2 tile padding. Số draw calls mỗi frame <= (viewport_width/TILE_W + 5) * (viewport_height/TILE_H + 5)."*
   - Quotation: *"Chunk Pre-rendering: Chia tile map thành chunks 16×16 tiles. Mỗi chunk được render vào một OffscreenCanvas (hoặc ImageBitmap) một lần khi load. Khi render frame, chỉ drawImage các chunk bitmap đang trong viewport... RAM Budget: Uint8Array tile data + OffscreenCanvas chunk cache tổng cộng <= 8 MB cho zone lớn nhất (120×90)."*

2. **Existing Codebase State**:
   - `client/webapp/js/engine/world_renderer.js:12-28`: Hardcoded mathematical formulas (`Math.abs(x-y) <= 1` for stone, `Math.hypot(x-5, y-(-3)) < 3.2` for water) without any tile grid data. File size is 460 lines (approaching 500-line hard cap).
   - `client/webapp/js/engine/collision_engine.js:88-141`: `isPositionBlocked(wx, wy, radius, isDodge)` currently only checks boundary rectangles from `ZONE_BOUNDS` and prop footprints from `mapProps`.
   - `client/webapp/js/engine/monster_system.js:256-260`: Chasing monster updates position via direct linear Euclidean delta (`step = dt * 1.8; m.wx += ((player.wx - m.wx) / distToPlayer) * step;`) without tile collision or pathfinding. File size is 485 lines.
   - `server/world/map_data_types.py:13-27`: Defines `TileType` with values 0 to 12 (`VOID=0, FLOOR=1, WALL=2, DESTRUCTIBLE_BARRICADE=3, MUD_POOL=4, SPIKE_TRAP=5, CRUMBLED_DEBRIS=6, BONE_PILE=7, POISON_VENT=8, CHASM=9, BOSS_GATE=10, BOSS_ALTAR=11, RUNIC_FLOOR=12`). Does not yet contain open-world terrain enums (`PATH`, `DENSE_TERRAIN`, `POI`, `ENCOUNTER_LOW`, `ENCOUNTER_MEDIUM`, `ENCOUNTER_HIGH`, `WATER`).
   - `server/world/procedural_map_engine.py:22-86`: Implements procedural BSP room carving and A* corridor carving, but dungeon-sized ($48 \times 48$). Currently 395 lines.
   - `client/webapp/index.html:173`: Contains pause overlay `#overlay-pause` and pause controller `window.isGamePaused = false` in `canvas_renderer.js:1-11`.
   - `client/webapp/js/data/wilderness_zone_packs.js:9-47`: Contains hardcoded float coordinates `(wx: 9.5, wy: -4.5)` for monster pack leaders and minions.

3. **Tool Execution & Test Baselines**:
   - `pytest tests/unit/ -q`: Command exited with code `0`. Output: `894 passed in 50.60s`. Exactly 894 unit tests currently exist and pass.
   - `python tools/lint/check_code_and_doc_hygiene.py --strict`: Command exited with code `0`. 0 Hard Cap violations across 540 files (508 clean, 32 soft cap warnings, 0 hard cap errors).

---

## 4. Logic Chain

1. **Pipeline & Data Modeling (R1)**:
   - Observation: `ORIGINAL_REQUEST.md:204-215` requires compact binary transmission via `Uint8Array` (1 byte/tile) and tile types including `FLOOR`, `WALL`, `PATH`, `DENSE_TERRAIN`, `WATER/CHASM`, `BOSS_GATE`, `POI`, `ENCOUNTER_HIGH`, `ENCOUNTER_MEDIUM`, `ENCOUNTER_LOW`.
   - Logic: Existing `TileType` in `server/world/map_data_types.py` spans 0–12. Extending this enum with IDs 13–19 preserves 100% backward compatibility with all existing unit tests in `test_war_fog_and_procedural_map.py` while fitting within an unsigned 8-bit integer ($0 \le v \le 255$).
   - Logic: Starter zone `zone_tang_kiem_nhai` needs a grid of at least $60 \times 45$ ($2,700\text{ bytes}$), scaling to $120 \times 90$ ($10,800\text{ bytes}$) for `zone_boundless_celestial_palace`. In binary, this is only $10.5\text{ KB}$, enabling instantaneous WebSocket transmission.

2. **Rendering Performance & Mobile Optimization (R2)**:
   - Observation: Drawing 10,800 tiles individually per frame would choke mobile browsers.
   - Logic: Partitioning the grid into $16 \times 16$ tile chunks yields only 12 chunks for $60 \times 45$ and 48 chunks for $120 \times 90$. Pre-baking chunks into `OffscreenCanvas` reduces frame draw calls to only the visible chunks ($\sim 2$ to $6$ calls per frame), easily satisfying $\le (viewport_W / TILE_W + 5) \times (viewport_H / TILE_H + 5)$.
   - Logic: A dirty flag ensures only chunks containing mutated tiles (e.g. breached boss gate) are re-baked. Memory for 48 chunks using an active visible pool remains well below the $8\text{ MB}$ RAM budget.

3. **Collision & Security Authority (R3)**:
   - Observation: `collision_engine.js:88` only clamps boundaries and prop footprints. Monsters in `monster_system.js:256` walk in straight lines.
   - Logic: Augmenting `isPositionBlocked(wx, wy, radius)` to query `getTileAt(Math.floor(wx), Math.floor(wy))` immediately blocks `WALL`, `CHASM`, `WATER`, and locked `BOSS_GATE` without altering the existing 2-axis sliding physics (`resolveMovementWithSliding`).
   - Logic: For monster chase mechanics, adding an A*/BFS grid pathfinding check ensures monsters navigate around walls and obstacle chokepoints rather than phasing through solid rock.

4. **Fog of War & Minimap HUD (R4)**:
   - Observation: `war_fog.js` currently exists only as a modal simulator (`#modal-war-fog`).
   - Logic: Bringing fog of war directly into the main world render loop via `window.fogGrid` (`Uint8Array`) with 8-tile radius reveals enables real-time line-of-sight shading. Persisting explored states in `localStorage` under `fe_fog_${zone_id}_${seed}` ensures player progress is remembered across teleports.
   - Logic: The 120×80 HUD canvas provides instant situational awareness with designated color markers (white player, green waypoints, red boss gate, yellow POI).

5. **Encounter Zone Spawning & Anti-Cheat (R5)**:
   - Observation: Monsters currently spawn at static coordinates regardless of procedural terrain.
   - Logic: Binding packs to `ENCOUNTER_*` tile clusters guarantees monsters spawn organically in open terrain, away from the 8-tile spawn safe clearing and waypoint safe radii.
   - Logic: Scripted POI ambushes and Boss Gate lore popups create structured progression where unlocking the boss arena requires conquering all prerequisite packs in the zone.

6. **Regression Invariance**:
   - Observation: All 894 unit tests must pass; waypoint safe radius and game pause must remain functional.
   - Logic: None of the new tile map capabilities alter the core waypoint math (`isInWaypointSafeRadius`), the combat feel engine, or the pause flag in `canvas_renderer.js`. Existing APIs are strictly preserved.

---

## 3. Caveats

- **OffscreenCanvas Browser Compatibility**: Older Safari or WebKit browsers may lack native `OffscreenCanvas`. The rendering implementation must include a fallback to hidden `<canvas>` elements (`document.createElement('canvas')`).
- **File Length Constraints**: Existing files `world_renderer.js` (460 lines) and `monster_system.js` (485 lines) are close to the 500-line hard cap. Implementation subagents must extract new subsystems into modular helper files (e.g. `tile_map_renderer.js`, `grid_pathfinder.js`) rather than inflating existing files.
- **No other caveats**.

---

## 4. Conclusion

All 5 core requirements (R1–R5), data structures, algorithms, tile enum mappings, memory budgets, and regression boundaries have been completely extracted, analyzed, and documented in `c:\Projects\FreeExile\.agents\teamwork\spec_miner_map\report.md`.
The specification provides a complete, actionable, and verified blueprint ready for implementation by engineering subagents.

---

## 5. Verification Method

To verify the observations and findings in this report:

1. **Verify Existing Test Suite Baseline (894 Tests Pass)**:
   ```powershell
   pytest tests/unit/ -q
   ```
   *Expected Result*: `894 passed`.

2. **Verify Code & Doc Hygiene Compliance**:
   ```powershell
   python tools/lint/check_code_and_doc_hygiene.py --strict
   ```
   *Expected Result*: `0 Hard Cap Violations`.

3. **Verify Game Design Matrix & Database Synchronization**:
   ```powershell
   python tools/lint/verify_game_design_matrix.py
   ```
   *Expected Result*: `[PASS] 100% IN SYNC`.

4. **Inspect Generated Deliverables**:
   - View `c:\Projects\FreeExile\.agents\teamwork\spec_miner_map\report.md` for the complete 36-feature inventory, 16 edge cases, and architectural constraints.
