> 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/phase35-session06-simulation-ownership-refactor/spec.md).

# Session Specification

**Session ID**: `phase35-session06-simulation-ownership-refactor` **Phase**: 35 - AI Rogue Audit Hardening And Refactor **Status**: Not Started **Created**: 2026-06-26

***

## 1. Session Overview

This session narrows AI Rogue runtime ownership after the regression and persistence contracts from Sessions 02 and 05 have been validated. The next safe product step is not new gameplay content; it is preserving the current production-enabled behavior while making the simulation boundary easier to reason about before the renderer and world/type splits in Sessions 07 and 08.

Current source already has the public runtime barrel narrowed to `runtime/mount.ts` and has simulation-owned pre-run selected-upgrade and progression-loadout helpers. This session should preserve those fixed contracts, strengthen the import and fixture boundaries, and execute the first behavior-preserving extraction from `runtime/simulation.ts` into explicit run factory and snapshot modules.

The first split deliberately avoids broad reducer rewrites. Movement, player actions, enemy turns, floor progression, and turn finalization remain in `simulation.ts` unless an extraction is proven by focused tests during the session. The implementation must leave a concrete split map for those follow-up targets so Session 07 and Session 08 can proceed without reopening public API questions.

***

## 2. Objectives

1. Preserve the narrow mounted runtime public API and explicit test fixture boundary.
2. Move run creation, pre-run initialization, and snapshot assembly out of the broad simulation module through behavior-preserving internal modules.
3. Keep renderer run-state updates routed through simulation-owned transition helpers with turn-zero and terminal-state revalidation.
4. Prove same-seed determinism, pre-run state safety, production query gating, and runtime boundary checks with focused tests.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase35-session02-fixed-blocker-regression-coverage` - Provides direct blocker regression evidence for command correctness, fixture gating, and simulation-owned pre-run state.
* [x] `phase35-session05-persistence-schema-contracts` - Provides stable durable save, claim, and hydration contracts before runtime ownership refactoring.

### Required Tools Or Knowledge

* Bun repo-local runners for Vitest, TypeScript, ESLint, and Playwright.
* AI Rogue runtime ownership boundaries in `src/extensions/ai-rogue/runtime/`.
* Current fixture boundary behavior through `window.__AI_ROGUE_LOCAL_TEST_SCENARIO__` in dev/test only.

### Environment Requirements

* Run commands from the repo root.
* Preserve `VITE_CLAUDE_OS_ENABLED_EXTENSIONS=none` as the explicit disable path and do not add new hosted writes, collectors, analytics, Functions, remote game content loading, WebGPU-only behavior, or worker protocols.

***

## 4. Scope

### In Scope (MVP)

* AI Rogue production runtime users can keep launching generated runs through the narrow mounted controller entrypoint - preserve `runtime/index.ts` and `runtime/mount.ts` as the only product-facing runtime barrel.
* AI Rogue local/test fixtures can still exercise deterministic combat - keep fixture scenario access explicit, dev/test gated, and unavailable through product route query parameters.
* AI Rogue simulation owners can maintain run creation separately from command reducers - extract run creation and pre-run initialization into an internal factory module.
* AI Rogue tests can protect snapshot and same-seed behavior - extract snapshot assembly into an internal snapshot module and update focused tests.
* AI Rogue refactor follow-up can proceed without guesswork - record the concrete remaining split targets for command dispatch, movement, player actions, enemy turns, floor progression, and turn finalization.

### Out Of Scope (Deferred)

* Renderer, effects, render-model, audio, and React bridge extraction - Reason: assigned to Session 07 after this simulation boundary is stable.
* Broad world/type module split - Reason: assigned to Session 08 after runtime API and simulation ownership are settled.
* User-facing content expansion - Reason: Phase 35 is hardening and refactor scope only.
* New collectors, analytics, hosted writes, remote content, WebGPU-only paths, or worker protocols - Reason: require fresh security and privacy review.

***

## 5. Technical Approach

### Architecture

Keep `runtime/index.ts` as a one-line re-export of `runtime/mount.ts`. Treat `runtime/mount.ts` as the public product entrypoint and keep all simulation, fixture, renderer, and world internals out of that barrel.

Extract the low-risk simulation ownership pieces first. `run-factory.ts` should own `AiRogueRunOptions`, `createAiRogueRun`, and the pre-run selected-upgrade and progression-loadout transition helpers. `snapshot.ts` should own `createAiRogueSnapshot`. `simulation.ts` should keep command reducer behavior stable and re-export compatibility symbols only where existing tests or callers still require them during this session.

Renderer code should call explicit internal simulation factory APIs for run creation and pre-run updates. Product route code should continue importing only `../runtime/mount`, and local combat fixtures should remain behind the existing dev/test-only scenario hook rather than route query parsing.

### Design Patterns

* Narrow barrel: Keeps product imports stable and prevents renderer/test helper internals from becoming public runtime API.
* Behavior-preserving extraction: Moves code behind existing tests before changing reducer behavior.
* Compatibility re-export: Allows test migration to happen incrementally while preserving command behavior and typecheck stability.
* Source-scan boundary tests: Enforces fixture and broad-barrel rules without adding runtime debug surfaces.

***

## 6. Deliverables

### Files To Create

| File                                                                                         | Purpose                                                                          | Est. Lines |
| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/runtime/run-factory.ts`                                             | Own run creation, pre-run selected-upgrade, and progression-loadout transitions. | \~260      |
| `src/extensions/ai-rogue/runtime/snapshot.ts`                                                | Own runtime snapshot assembly from simulation state.                             | \~150      |
| `.spec_system/specs/phase35-session06-simulation-ownership-refactor/implementation-notes.md` | Record implementation evidence and the remaining simulation split map.           | \~220      |

### Files To Modify

| File                                                                 | Changes                                                                                                        | Est. Lines |
| -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/runtime/simulation.ts`                      | Import or re-export factory and snapshot helpers while keeping command reducer behavior stable.                | \~120      |
| `src/extensions/ai-rogue/runtime/renderer.ts`                        | Import run factory and pre-run helpers from explicit internal modules, preserving runtime controller behavior. | \~25       |
| `src/extensions/ai-rogue/runtime/__tests__/runtime-boundary.test.ts` | Expand public barrel, fixture boundary, and production route import assertions.                                | \~80       |
| `src/extensions/ai-rogue/runtime/__tests__/pre-run-state.test.ts`    | Update imports and add turn-zero revalidation coverage around extracted factory helpers.                       | \~60       |
| `src/extensions/ai-rogue/runtime/__tests__/simulation.test.ts`       | Add same-seed and snapshot regression coverage for extracted modules.                                          | \~60       |
| `src/extensions/ai-rogue/__tests__/runtime-canvas.test.tsx`          | Preserve local scenario hook and generated default behavior after import changes.                              | \~30       |
| `tests/e2e/ai-rogue-runtime.spec.ts`                                 | Preserve production query-ignore and local combat hook runtime checks.                                         | \~20       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Production Play code imports the mounted runtime entrypoint, not the broad runtime barrel, simulation internals, or fixture modules.
* [ ] Test combat fixtures remain available only through explicit dev/test hooks and do not respond to product route query parameters.
* [ ] Renderer selected-upgrade and progression-loadout updates remain simulation-owned and are ignored after turn advancement or terminal run status.
* [ ] Same-seed generated runs and snapshots remain deterministic before and after extraction.
* [ ] `runtime/simulation.ts` is smaller and has a recorded split map for the remaining reducer targets.

### Testing Requirements

* [ ] Focused runtime boundary, pre-run state, and simulation tests pass.
* [ ] Focused runtime-canvas/client tests pass where import or fixture behavior is touched.
* [ ] Playwright runtime checks pass for product query-ignore behavior and local combat hook behavior.

### Non-Functional Requirements

* [ ] No new dependency, asset, network, hosted write, collector, analytics, or worker behavior is introduced.
* [ ] Bundle budget risk is not increased by adding large runtime dependencies.
* [ ] Product-facing UI copy is unchanged unless required by an existing test.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] Primary user-facing surfaces contain product-facing copy only.
* [ ] `bun run typecheck && bun run lint` passes.

***

## 8. Implementation Notes

### Working Assumptions

* Session 06 should not redo fixed Phase 34 boundary work; it should preserve and deepen it. Evidence: `runtime/index.ts` already exports only `./mount`, `runtime/mount.ts` already avoids fixture exports, and `runtime/__tests__/runtime-boundary.test.ts` already asserts the narrow public barrel.
* Simulation-owned selected-upgrade and progression-loadout helpers already exist and are tested, so the safe next move is extraction plus stronger boundary checks. Evidence: `runtime/simulation.ts` exports `applyAiRoguePreRunSelectedUpgrade` and `applyAiRoguePreRunProgressionLoadout`, and `runtime/__tests__/pre-run-state.test.ts` covers apply, replace, clear, duplicate, and post-start ignore behavior.
* Fixture scenario behavior is a local/test hook, not a product query contract. Evidence: `runtime-canvas.tsx` resolves combat scenarios only when `import.meta.env.DEV` is true, public demo mode is false, and `window.__AI_ROGUE_LOCAL_TEST_SCENARIO__` is set to `combat`; Playwright coverage already asserts `?scenario=combat` stays generated.

### Key Considerations

* Keep AI Rogue production default-enabled and preserve `VITE_CLAUDE_OS_ENABLED_EXTENSIONS=none` as the explicit disable path.
* Keep the public demo static-only and avoid any new bridge request, hosted write, collector, analytics, Function, remote content loading, private telemetry, WebGPU-only path, or worker protocol.
* Keep the session behavior-preserving; this is refactor infrastructure, not a gameplay content session.

### Potential Challenges

* `simulation.ts` is large and tightly coupled: Extract run creation and snapshot first, then record exact follow-up targets instead of broad reducer rewrites.
* Test imports currently use `../simulation` heavily: Update only tests whose intent is factory or snapshot behavior, and preserve compatibility re-exports for command behavior.
* Fixture isolation is easy to weaken during refactor: Add source-scan tests before changing imports and keep local combat behavior covered by Playwright.

### Relevant Considerations

* \[P34] **AI Rogue is production default-enabled**: Preserve default visibility and explicit `none` opt-out while narrowing internals.
* \[P31-P34] **Public-demo and AI Rogue gates stay bundled**: Runtime changes should keep no-bridge and privacy boundaries visible in verification.
* \[P30/P32/P34] **Route-lazy runtime ownership scales**: Keep Pixi and runtime internals behind the Play route/local facade while React owns DOM accessibility and simulation owns run-state transitions.
* \[P34] **Do not expose deterministic fixtures through product routes**: Fixture scenarios remain test/local-only and must not become query-driven product behavior.
* \[P30/P32/P34] **Do not widen AI Rogue capabilities without review**: Collectors, WebGPU, workers, remote loading, hosted writes, or expanded content are excluded.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Boundary drift: Production routes or mounted entrypoints accidentally import simulation, fixture, or broad barrel APIs.
* State mutation drift: Renderer update methods accidentally bypass turn-zero and terminal-state revalidation.
* Determinism drift: Extracted factory or snapshot code changes same-seed run output or command result shape.

***

## 9. Testing Strategy

### Unit Tests

* Extend `runtime-boundary.test.ts` for narrow barrel, mounted entrypoint, and fixture import boundaries.
* Extend `pre-run-state.test.ts` for extracted factory imports and turn-zero selected-upgrade/loadout revalidation.
* Extend `simulation.test.ts` for same-seed run and snapshot determinism after extraction.

### Integration Tests

* Run focused runtime-canvas and client tests that assert generated default, local combat hook, and production mount import behavior.

### Runtime Verification

* Run the AI Rogue runtime Playwright spec that covers painted runtime canvas, local combat hook behavior, and product query-ignore behavior.

### Edge Cases

* Invalid local scenario hook values resolve to generated runs.
* `?scenario=combat` does not change product Play behavior.
* Selected upgrade or progression loadout changes after turn advancement or terminal state return the existing state unchanged.
* Same seed produces stable generated world, snapshot, and command result shape after extraction.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase35-session02-fixed-blocker-regression-coverage`, `phase35-session05-persistence-schema-contracts`.
* Depended by: `phase35-session07-renderer-and-react-bridge-refactor`, `phase35-session08-world-types-and-fixture-cleanup`, `phase35-session09-documentation-and-media-policy-sync`, `phase35-session10-final-release-gate`.

***

## 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/phase35-session06-simulation-ownership-refactor/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.
