# Dispatch: Milestone M5 Encounter Zone Architecture & Terrain-Anchored Spawning Worker

**Target Role**: `teamwork_preview_worker` (`worker_m5_1`)
**Working Directory**: `c:\Projects\FreeExile\.agents\teamwork\worker_m5_1`
**Authoritative User Request**: `c:\Projects\FreeExile\.agents\teamwork\ORIGINAL_REQUEST.md` (specifically section `## 2026-10-01T19:19:13Z` - R5)

---

## 🔒 MANDATORY INTEGRITY WARNING
DO NOT CHEAT. All implementations must be genuine. DO NOT hardcode test results, create dummy/facade implementations, or circumvent the intended task. A `teamwork_preview_auditor` will independently verify your work. Integrity violations WILL be detected and your work WILL be rejected.

---

## 1. Explorer References & Blueprints
Read the following authoritative investigation reports and code blueprints:
- `c:\Projects\FreeExile\.agents\teamwork\explorer_m5_1\report.md` & `handoff.md` (Terrain-anchored pack spawning, cohesive pack leashing ~9.0 tiles around anchor, `window.zoneEncounterProgress`, and pack archetypes)
- `c:\Projects\FreeExile\.agents\teamwork\explorer_m5_2\report.md` & `handoff.md` (Grid pathfinding `grid_pathfinder.js`, 284 lines, zero-heap typed arrays, binary min-heap, Supercover DDA LoS, corner-cutting avoidance)
- `c:\Projects\FreeExile\.agents\teamwork\explorer_m5_3\report.md` & `handoff.md` (Scripted POI wave ambush $\le 1.0$ tile, Boss Gate lore popup integration with `zoneEncounterProgress`, dual visual cues in `world_renderer.js`)

---

## 2. Implementation Scope & File Ownership

### 2.1. `client/webapp/js/engine/grid_pathfinder.js` [NEW, $\le 320$ lines]
- Implement using the 284-line blueprint from `explorer_m5_2/report.md`.
- Zero-heap allocation via static typed buffers (`Uint32Array(16384)`, `Int32Array(16384)`, `Float32Array(16384)`).
- Binary min-heap with $O(1)$ `currentIteration++` reset.
- Supercover DDA raycast for line-of-sight shortcut when direct path to player is unblocked.
- Strict corner-cutting avoidance (diagonal movement requires both orthogonal tiles to be passable).
- Dynamic replanning throttling (250–500ms with jitter per monster).
- Export `window.GridPathfinder = { findPath, hasLineOfSight, steerMonsterChase, ... }`.

### 2.2. `client/webapp/js/data/wilderness_zone_packs.js` [MODIFIED, $\le 350$ lines]
- Integrate terrain-anchored encounter templates (Tier 1/2/3 LOW/MED/HIGH) based on `explorer_m5_1`.
- CRITICAL: Must PRESERVE existing pack template keys `pack_tang_kiem_alpha` and `pack_tang_kiem_beta` (required by unit test regexes!).

### 2.3. `client/webapp/js/engine/monster_pack_system.js` [MODIFIED, $\le 350$ lines]
- Extend `populateZonePacks` and pack handling based on `explorer_m5_1`:
  - Inspect `window.currentMapMetadata.encounterZones` and cluster anchors.
  - Spawn 3–5 monsters per anchor (ENCOUNTER_PACK, ENCOUNTER_ELITE).
  - Cohesive pack leashing (~9.0 tiles around anchor): return toward anchor when player exceeds leash radius.
  - Progress tracking: `window.zoneEncounterProgress[zoneId]` tracks `{ totalPacks, alivePacks, clearedPacks, totalKills }`.
  - When all packs in zone are cleared (`alivePacks === 0`), trigger `window.bossGateController?.unlock()`.

### 2.4. `client/webapp/js/engine/ambush_trigger_system.js` [MODIFIED, $\le 300$ lines]
- Implement scripted POI wave ambush based on `explorer_m5_3`:
  - Inspect `window.currentMapMetadata.pois`.
  - Proximity trigger: player within $\le 1.0$ tile of un-triggered POI (`!poi.isTriggered`).
  - Once triggered: set `poi.isTriggered = true`, spawn 3–5 monsters in ring around POI on passable tiles, trigger screen shake & audio cue.

### 2.5. `client/webapp/js/engine/monster_system.js` [MODIFIED, $\le 480$ lines, HARD CEILING $\le 490$ lines]
- Hook `steerMonsterChase` (from `grid_pathfinder.js`) into monster movement loop.
- Hook pack leashing and encounter tracking from `monster_pack_system.js`.
- CRITICAL: Automated unit tests (`test_monster_poise_and_leash.py` and `test_waypoint_safe_radius.py`) assert `monster_system.js` line count $\le 490$ lines! Keep lines safely around 475–480 lines by delegating logic to `monster_pack_system.js` and `grid_pathfinder.js`.

### 2.6. `client/webapp/js/engine/boss_gate_controller.js` [MODIFIED, $\le 200$ lines]
- Wire with `window.zoneEncounterProgress`:
  - Proximity popup ($\le 3.0$ tiles, hysteresis $> 3.5$ tiles) displays remaining packs/kills until gate opens.
  - Auto-unlocks when encounter progress requirement met.

### 2.7. `client/webapp/js/engine/world_renderer.js` [MODIFIED, $\le 490$ lines, HARD CAP 500 lines]
- Add POI rendering loop based on `explorer_m5_3`:
  - Un-triggered POI: pulsing amber radial aura, rotating dashed rune ring (`#fbbf24`), bobbing beacon (`✨`).
  - Triggered POI: extinguished stone altar and urn (`🏺`).
  - Respect Fog of War: only render if `WarFog.getFogState(poi.x, poi.y) > 0`.

### 2.8. `client/webapp/index.html` [MODIFIED, $\le 200$ lines, HARD CAP 400 lines]
- Mount `<script src="js/engine/grid_pathfinder.js"></script>` before `monster_system.js`.

### 2.9. `tests/unit/test_encounter_zones.py` [MODIFIED, $\le 300$ lines]
- Create genuine hybrid unit test suite:
  - Python server tests: encounter zone generation, bounds, tier classifications, POI serialization/deserialization, Safe Haven purity.
  - Genuine Node.js subprocess runtime tests (using `subprocess.run(["node", "-e", ...])`):
    - `grid_pathfinder.js`: path finding around wall, corner-cutting avoidance, DDA LoS shortcut.
    - `monster_pack_system.js`: cluster pack spawning, cohesive leashing, zone encounter progress, Boss Gate auto-unlock.
    - Scripted POI wave ambush: proximity trigger at $\le 1.0$ tile, 3–5 monsters spawned, once-only flag.
    - Boss Gate lore popup: proximity at $\le 3.0$ tiles, hysteresis at $> 3.5$ tiles, progress display.
  - Strictly $\le 300$ lines. Zero boolean tautologies, zero mock shortcuts!

---

## 3. Mandatory Verification Commands
Run and document results in `handoff.md`:
1. `pytest tests/unit/test_encounter_zones.py -v` (All tests must PASS)
2. `pytest tests/unit/test_fog_and_minimap.py -v` (14/14 PASS)
3. `pytest tests/unit/test_tile_collision.py -v` (11/11 PASS)
4. `pytest tests/unit/test_mobile_webapp_config.py -v` (15/15 PASS)
5. `pytest tests/unit/test_monster_poise_and_leash.py -v` (Must PASS, verifies line cap $\le 490$)
6. `pytest tests/unit/test_waypoint_safe_radius.py -v` (Must PASS, verifies line cap $\le 490$)
7. `pytest tests/e2e/test_poe2_map_system_e2e.py -v` (81/81 PASS)
8. `node tools/perf/map_render_benchmark.js` (Must PASS with 0 stationary re-bakes)
9. `pytest tests/unit/ -q` (all 975+ unit tests must PASS with zero regressions)
10. `python tools/lint/check_code_and_doc_hygiene.py --strict` (0 violations)

Write `handoff.md` in your working directory and notify parent when complete.
