> For the complete documentation index, see [llms.txt](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase30-session06-dungeon-simulation-core/spec.md).

# Session Specification

**Session ID**: `phase30-session06-dungeon-simulation-core` **Phase**: 30 - AI Rogue Game Extension **Status**: Not Started **Created**: 2026-06-22

***

## 1. Session Overview

This session adds the deterministic AI Rogue dungeon simulation that later PixiJS rendering work will consume. Sessions 01-05 have already locked the AI Rogue product direction, mounted the disabled-first extension shell, proved the lazy PixiJS runtime boundary, implemented the browser-safe economy, and added local persistence contracts. The next missing foundation is a pure TypeScript run model that can produce maps, entities, turns, combat, fog, and coarse snapshots without browser or renderer APIs.

The work is intentionally renderer-independent. Simulation modules live under the existing `src/extensions/ai-rogue/runtime/` boundary, export serializable state and command results, and keep PixiJS asset frame names as vocabulary only. Session 07 can then render the committed atlas frames and wire wallet- backed upgrades against a stable simulation contract instead of inventing game rules inside the renderer.

The first slice is small: one seeded floor, floor/wall/door/hazard/fog tile semantics, player movement, keyboard and pointer command translation, turn advancement, two enemy behaviors, deterministic combat, field of view, fog of war, pickups, and a win/loss condition. Bosses, relic catalogs, classes, expanded progression, workers, physics, procedural biomes, and rendering stay deferred.

***

## 2. Objectives

1. Create deterministic seeded RNG, grid, world generation, and fixture seeds for repeatable AI Rogue simulation tests.
2. Define serializable tiles, entities, player state, enemy behaviors, combat log events, run status, and coarse snapshots in pure TypeScript.
3. Implement command application for keyboard and pointer-derived movement, turn advancement, FOV, fog of war, pickups, hazards, win, and loss.
4. Cover deterministic generation, movement, FOV, combat, run completion, and enemy behavior with focused Vitest suites that do not import PixiJS or browser APIs.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase30-session01-direction-and-asset-readiness` - Locked AI Rogue naming, currency, first-slice enemy vocabulary, tile scale, and asset constraints.
* [x] `phase30-session02-extension-shell-and-routes` - Added the disabled-first AI Rogue extension shell and Play surface that will host the simulation.
* [x] `phase30-session03-pixijs-runtime-boundary` - Proved the route-scoped runtime boundary, coarse controller events, input sampler, and cleanup.
* [x] `phase30-session04-economy-and-ledger` - Added Insight Shards economy language that in-run pickups and completion rewards must not contradict.
* [x] `phase30-session05-persistence-and-save-contracts` - Added local save, wallet, run-history, and snapshot contracts that later sessions can connect to simulation summaries.

### Required Tools Or Knowledge

* Existing runtime files in `src/extensions/ai-rogue/runtime/`.
* Existing input command contract in `src/extensions/ai-rogue/runtime/types.ts` and `src/extensions/ai-rogue/runtime/input.ts`.
* Locked atlas vocabulary in `src/assets/ai-rogue/gameplay-atlas.json`.
* AI Rogue plan and asset records in `docs/extensions/ai-rogue/`.
* Reference algorithms in `EXAMPLES/Rotten-Soup/` and `EXAMPLES/frogue/`, used only as algorithm precedents, not renderer architecture.

### Environment Requirements

* Bun 1.3.14 project tooling.
* TypeScript, Vitest, and existing path aliases.
* No browser, DOM, PixiJS, IndexedDB, localStorage, worker, network, or server API required for simulation tests.

***

## 4. Scope

### In Scope (MVP)

* AI Rogue maintainer can generate a repeatable dungeon floor - implemented with seeded RNG, bounded dimensions around the 30x16 baseline, deterministic room/corridor or cellular-style layout, doors, hazards, pickups, enemies, player start, and exit placement.
* AI Rogue player can move through valid tiles - implemented with command application for cardinal movement, blocked-wall feedback, door traversal, hazard damage, pickup collection, and turn advancement.
* AI Rogue player can fight two enemy types - implemented with `Errant Process` as a melee chaser and `Firewall Sentry` as a stationary ranged guard with telegraphed line threat events.
* AI Rogue run state can expose fog and visible tiles - implemented with deterministic FOV and explored-tile tracking in serializable snapshots.
* AI Rogue runtime can translate non-renderer input into simulation commands - implemented by extending pure input helpers for keyboard and pointer target translation without changing PixiJS renderer ownership.
* AI Rogue tests can reuse fixed seeds - implemented with fixture seeds for generation, combat, FOV, movement, win, and loss paths.

### Out Of Scope (Deferred)

* PixiJS sprite rendering, texture slicing, animation, HUD, and asset placement
  * Reason: Session 07 owns play runtime integration.
* Wallet-backed upgrades, relic purchases, class selection, and run-affecting loadout choices - Reason: Session 07 adds one spendable upgrade, and Session 08 expands progression.
* Kernel Sentinel boss behavior, deeper floors, biome systems, and expanded objective variety - Reason: Session 08 owns progression depth.
* Worker simulation, physics engine, `rot.js`, WebGPU, audio, gamepad, pointer lock, remote content, collectors, server endpoints, or generated data writes
  * Reason: Phase 30 first slice is local, deterministic, and renderer-owned only after this pure simulation contract exists.
* Persisting full dungeon state into IndexedDB - Reason: Session 05 created the envelope, but Session 07 should connect save/load after rendering and runtime events consume the simulation.

***

## 5. Technical Approach

### Architecture

Add pure modules directly under `src/extensions/ai-rogue/runtime/` so the simulation remains part of the game runtime boundary but does not import `pixi.js`, React, browser APIs, or storage helpers. `rng.ts` owns deterministic integer and weighted-choice primitives. `world.ts` owns tile constants, grid helpers, seeded floor generation, passability, line-of-sight helpers, hazards, pickup placement, and exit placement. `entities.ts` owns entity kinds, player state, enemy templates, and behavior inputs. `combat.ts` owns deterministic attack resolution and combat log events. `fov.ts` owns visible/explored tile projection. `simulation.ts` ties those together into `createAiRogueRun`, `applyAiRogueCommand`, enemy turns, run status, and coarse snapshots.

The first implementation should use the existing `AiRogueInputCommand` union for cardinal movement and primary/secondary actions. Pointer support should be pure coordinate translation in `input.ts`, returning a cardinal command or target tile from a viewport/tile geometry input. The renderer can later call that helper without changing simulation semantics.

All public state exported by simulation modules should be serializable and bounded. Snapshots may include IDs, labels, positions, health, tile kinds, visibility, explored coordinates, run status, turn count, shard count, and combat log messages. They must not include raw private telemetry, browser storage objects, Pixi instances, DOM nodes, closures, or generated runtime data.

### Design Patterns

* Pure simulation core: deterministic functions take state plus command and return the next state, events, and status without side effects.
* Seeded fixtures: tests pin seeds and assert stable maps, positions, combat outcomes, and completion paths.
* Renderer vocabulary only: tile and entity kinds align to committed atlas frame names, but modules do not import image assets or PixiJS textures.
* Exhaustive command handling: every `AiRogueInputCommand` maps to a handled simulation result or an explicit no-op event.
* Bounded snapshots: coordinates, entities, logs, and explored tiles stay bounded and deterministic to protect later persistence and browser payloads.

***

## 6. Deliverables

### Files To Create

| File                                                           | Purpose                                                                                                                | Est. Lines |
| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/runtime/rng.ts`                       | Seeded RNG, integer ranges, shuffling, weighted choices, and deterministic helpers.                                    | \~140      |
| `src/extensions/ai-rogue/runtime/world.ts`                     | Grid, tile kinds, passability, deterministic floor generation, hazards, doors, pickups, exits, and map snapshots.      | \~320      |
| `src/extensions/ai-rogue/runtime/entities.ts`                  | Player, enemy, pickup, position, direction, enemy behavior, and snapshot types.                                        | \~220      |
| `src/extensions/ai-rogue/runtime/fov.ts`                       | Field-of-view, line-of-sight, visible tile sets, and explored-tile projection helpers.                                 | \~180      |
| `src/extensions/ai-rogue/runtime/combat.ts`                    | Deterministic player/enemy attacks, ranged sentry threat events, damage, death, and combat log entries.                | \~220      |
| `src/extensions/ai-rogue/runtime/simulation.ts`                | Run creation, command reducer, turn advancement, enemy turns, hazards, pickups, win/loss status, and coarse snapshots. | \~360      |
| `src/extensions/ai-rogue/runtime/simulation-fixtures.ts`       | Stable seeds and helper scenarios for unit tests and later Playwright use.                                             | \~120      |
| `src/extensions/ai-rogue/runtime/__tests__/rng.test.ts`        | Determinism and weighted-choice tests.                                                                                 | \~120      |
| `src/extensions/ai-rogue/runtime/__tests__/world.test.ts`      | Map generation, passability, hazards, doors, pickup, exit, and spawn determinism tests.                                | \~180      |
| `src/extensions/ai-rogue/runtime/__tests__/fov.test.ts`        | FOV, wall blocking, explored tiles, and fog projection tests.                                                          | \~140      |
| `src/extensions/ai-rogue/runtime/__tests__/combat.test.ts`     | Deterministic melee, ranged sentry, damage, death, and log event tests.                                                | \~180      |
| `src/extensions/ai-rogue/runtime/__tests__/simulation.test.ts` | End-to-end pure simulation tests for movement, enemy turns, pickups, win, loss, and snapshots.                         | \~260      |

### Files To Modify

| File                                                       | Changes                                                                                                                            | Est. Lines |
| ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/runtime/types.ts`                 | Add serializable simulation command, position, tile, entity, run status, event, and snapshot exports as needed by runtime callers. | \~120      |
| `src/extensions/ai-rogue/runtime/input.ts`                 | Add pure pointer-to-tile and pointer-to-cardinal-command translation helpers with bounded geometry validation.                     | \~90       |
| `src/extensions/ai-rogue/runtime/index.ts`                 | Export the pure simulation modules without importing PixiJS or widening shared app chunks.                                         | \~40       |
| `src/extensions/ai-rogue/runtime/__tests__/input.test.ts`  | Cover pointer command translation, invalid geometry, and existing keyboard behavior.                                               | \~120      |
| `src/extensions/ai-rogue/runtime/__tests__/assets.test.ts` | Assert simulation tile/entity vocabulary remains compatible with required atlas frame names where practical.                       | \~60       |
| `src/extensions/ai-rogue/__tests__/save-schema.test.ts`    | Add a narrow assertion that run summaries can accept simulation completion labels without private text.                            | \~40       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] The same seed produces the same map dimensions, tile layout, start, exit, pickups, enemy placement, and first-turn snapshot.
* [ ] Movement respects walls, doors, hazards, pickups, win/loss states, and turn advancement.
* [ ] `Errant Process` and `Firewall Sentry` have distinct deterministic behaviors and produce visible combat log events.
* [ ] FOV and fog snapshots distinguish visible, explored, and hidden tiles without exposing renderer objects.
* [ ] Pointer-derived commands and keyboard commands can drive the same pure simulation reducer.
* [ ] Simulation state is serializable, bounded, and free of browser, PixiJS, storage, network, and private telemetry references.

### Testing Requirements

* [ ] Unit tests cover RNG determinism, world generation, movement, FOV, fog, hazards, pickups, combat, enemy behavior, win/loss completion, and snapshot stability.
* [ ] Input tests cover keyboard and pointer translation edge cases.
* [ ] Tests prove simulation modules do not need PixiJS, DOM, localStorage, IndexedDB, or a browser environment.

### Non-Functional Requirements

* [ ] No new runtime dependency such as `rot.js`, physics, worker, audio, or renderer helper is added.
* [ ] No server endpoint, network call, collector, generated-data write, hosted storage, credential flow, or admin bridge is introduced.
* [ ] Tile and entity kinds line up with the committed AI Rogue atlas vocabulary and Session 06 enemy scope.
* [ ] Simulation logs remain concise and capped.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] Focused AI Rogue runtime Vitest suite passes.
* [ ] `bun run typecheck` passes or any unrelated pre-existing failure is documented with evidence.

***

## 8. Implementation Notes

### Working Assumptions

* No `rot.js` dependency should be added for this first slice: the Phase 30 PRD says AI Rogue plans its own seeded RNG and treats `rot.js` as a dependency to weigh against bundle budget, while Session 06 explicitly asks for pure TypeScript primitives.
* A single around-30x16 floor is the correct first map size: the Session 06 stub and visual-assets doc both name the 1280x720 baseline of about 30x16 visible 32px tiles, which is enough for one room/combat composition before mobile polish in Session 09.
* Runtime save snapshots should remain coarse in this session: Session 05 created a browser-local envelope and run summaries, but Session 07 should connect durable save/load after renderer and runtime events consume the simulation contract.

### Conflict Resolutions

* The Session 06 stub says stable runtime interfaces from Session 03 can run after or alongside the session, while the analysis script marks Session 03 completed. The chosen interpretation is that Session 06 depends on the existing runtime/input/controller contracts and should update their pure types without changing renderer lifecycle behavior.
* The asset records include the `Kernel Sentinel` boss frame, but Session 06 requires exactly two enemy behaviors. The chosen interpretation is to model `Errant Process` and `Firewall Sentry` now and leave boss behavior for Session 08 progression depth.
* The stub mentions progression primitives, while Session 08 owns progression depth. The chosen interpretation is to include only run status, shard pickup counts, completion events, and summary-friendly labels in Session 06; relics, classes, achievements, and model-flavored drops remain deferred.

### Key Considerations

* Keep simulation tests fast and deterministic so future renderer and Playwright coverage can reuse fixture seeds.
* Preserve the disabled-first extension posture. Simulation code can exist in the bundle only when imported through the AI Rogue runtime path and must not change extension enablement.
* Treat combat and generation failures as explicit simulation events, not crashes, wherever a bounded no-op state can safely continue.

### Potential Challenges

* FOV can become costly if it scans unbounded grids: keep floor dimensions capped and test deterministic ordering of coordinate sets.
* Enemy turns can mutate state in confusing order: process actors in stable ID order, log each event, and make defeat/win status stop later actions.
* Pointer translation can drift once the renderer scales the canvas: keep the helper geometry explicit and covered so Session 07 can pass the current viewport/tile scale into it.

### Relevant Considerations

* \[P02] **Static extension registry requires code changes**: Add simulation under the existing extension source tree; do not introduce dynamic loading, eval, remote packages, or marketplace behavior.
* \[P02] **Extension payloads and labels stay bounded**: Keep snapshots, logs, entity lists, and visible tile sets capped.
* \[P00] **Stack conventions**: Use Bun, TypeScript, Vite, React 19, and existing Vitest patterns without adding a renderer dependency to unit tests.
* \[P27] **Repo-wide formatting drift remains**: Run focused formatting and avoid broad repo formatting churn.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Determinism drift: generation, enemy turns, combat, and weighted choices must remain stable for the same seed.
* Unbounded state: explored tiles, logs, entities, retries, and command handling must stay capped and deterministic.
* Contract leakage: pure simulation must not import PixiJS, browser storage, DOM objects, raw private telemetry, or generated runtime data.

***

## 9. Testing Strategy

### Unit Tests

* Test `rng.ts` for repeatable sequences, bounded integer ranges, shuffles, and weighted choices.
* Test `world.ts` for deterministic map generation, passability, hazards, doors, pickup placement, exit placement, and stable spawn positions.
* Test `fov.ts` for line-of-sight blocking, visible-tile projection, and explored-tile updates.
* Test `combat.ts` for deterministic melee and ranged outcomes, health changes, death handling, and combat log event shape.
* Test `simulation.ts` for command application, turn ordering, enemy behavior, pickup collection, hazard damage, win/loss, no-op commands, and snapshots.

### Integration Tests

* Test `input.ts` pointer helpers with viewport bounds, tile size, invalid geometry, and cardinal direction selection.
* Test `runtime/index.ts` exports so pure simulation callers can import without loading renderer code.
* Test save-schema compatibility for simulation summary labels and bounded run metadata.

### Runtime Verification

* Run focused Vitest suites for `src/extensions/ai-rogue/runtime/`.
* Run `bun run typecheck` to confirm the pure simulation contract is valid for later React and PixiJS integration.
* Inspect import boundaries to ensure no new simulation module imports `pixi.js`, React, browser storage, or route code.

### Edge Cases

* Zero or malformed seed input.
* Movement into wall, outside grid, closed door, hazard, enemy, pickup, and exit tiles.
* Enemy blocked by wall or another actor.
* Ranged sentry line blocked by wall.
* Player death during hazard or enemy turn.
* Win reached with enemies still alive.
* Repeated command after terminal win/loss state.
* Pointer coordinates outside the canvas or with invalid tile scale.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase30-session01-direction-and-asset-readiness`, `phase30-session02-extension-shell-and-routes`, `phase30-session03-pixijs-runtime-boundary`, `phase30-session04-economy-and-ledger`, `phase30-session05-persistence-and-save-contracts`
* Depended by: `phase30-session07-play-runtime-integration`, `phase30-session08-progression-depth`, `phase30-session09-content-polish-and-mobile`, `phase30-session10-quality-gates-and-enablement`

***

## Next Steps

Run the `implement` workflow step to begin implementation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase30-session06-dungeon-simulation-core/spec.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
