> 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-session07-renderer-and-react-bridge-refactor/spec.md).

# Session Specification

**Session ID**: `phase35-session07-renderer-and-react-bridge-refactor` **Phase**: 35 - AI Rogue Audit Hardening And Refactor **Status**: Not Started **Created**: 2026-06-26

***

## 1. Session Overview

This session splits the broad AI Rogue renderer, effects, render-model, audio adapter, and React runtime bridge after the prerequisite contracts from Sessions 03, 04, and 06 have passed validation. The goal is a behavior-preserving refactor, not new gameplay, new visuals, or new product scope.

The current renderer concentrates Pixi setup, sprite pools, inspect overlay, resize scheduling, reduced-motion subscriptions, audio dispatch, save payload creation, and controller state in one file. The current React bridge also owns mount lifecycle, persistence actions, compact controls, decision panels, and assistive summaries in one route-specific component. This session creates clearer ownership boundaries while preserving route cleanup, mount cancellation, projection cache behavior, sprite-pool cleanup, compact controls, save/load, and assistive summary behavior.

The session is next because Session 06 narrowed simulation ownership and left renderer and React bridge extraction as the next dependency-ordered refactor. Session 08 should not begin world/type cleanup until these renderer and bridge boundaries are smaller and covered by focused tests.

***

## 2. Objectives

1. Split renderer helper ownership for scheduling, state, save payloads, sprite pools, Pixi layers, inspect overlay, and audio dispatch without widening the public runtime barrel.
2. Split effects and render-model helpers by existing ownership rows while preserving projection cache, transient feedback, HUD, summary, and ordering behavior.
3. Split the React runtime bridge into lifecycle hooks and product components while preserving mount cancellation, save/load/reset, compact controls, decision controls, and assistive summary behavior.
4. Prove the refactor with focused unit tests, browser runtime/mobile checks, ASCII/LF validation, and static quality gates.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase35-session03-runtime-accessibility-controls` - Provides stable compact controls, Large HUD Labels, dynamic assistive summary, and mobile no-overflow behavior.
* [x] `phase35-session04-renderer-robustness-and-scheduling` - Provides stable resize coalescing, reduced-motion cleanup, Pixi failure handling, asset failure handling, audio fallback behavior, and renderer lifecycle tests.
* [x] `phase35-session06-simulation-ownership-refactor` - Provides stable mounted runtime imports, simulation-owned pre-run state, fixture boundary checks, and extracted run factory/snapshot helpers.

### Required Tools Or Knowledge

* Bun repo-local runners for Vitest, TypeScript, ESLint, format checks, and Playwright.
* Current AI Rogue runtime files under `src/extensions/ai-rogue/runtime/`.
* Current AI Rogue React bridge in `src/extensions/ai-rogue/views/runtime-canvas.tsx`.
* Current AI Rogue browser specs under `tests/e2e/`.

### Environment Requirements

* Run commands from the repo root.
* Preserve AI Rogue production default enablement and `VITE_CLAUDE_OS_ENABLED_EXTENSIONS=none` as the explicit disable path.
* Do not add hosted writes, collectors, analytics, Functions, remote game content loading, WebGPU-only behavior, worker protocols, or public-demo bridge requests.

***

## 4. Scope

### In Scope (MVP)

* AI Rogue maintainers can work on smaller renderer modules - extract scheduling, state/preferences, save payload creation, sprite pools, Pixi layers, inspect overlay, and audio dispatch into explicit internal modules.
* AI Rogue players keep the same runtime behavior - preserve mount cancellation, route cleanup, resize coalescing, reduced-motion cleanup, failure mapping, save/load/reset, compact controls, decision panels, and assistive summary updates.
* AI Rogue render output remains stable - preserve projection-cache keys, clock-only animation outside cached snapshot projection, sprite ordering, HUD descriptors, render summaries, and transient feedback projection.
* AI Rogue effects remain stable - split HUD overlay, transient combat effects, camera/shake/flash, cinematic cards/end screen, and cleanup helpers without changing public product copy or gameplay timing.
* AI Rogue tests remain close to behavior owners - update focused renderer, render-model, audio, runtime-canvas, and browser tests where import paths or module boundaries move.

### Out Of Scope (Deferred)

* Simulation reducer refactors - Reason: completed for this phase in Session 06 except for future targeted follow-ups.
* World and broad runtime type cleanup - Reason: assigned to Session 08.
* AI Rogue feature redesign, new game content, new controls, or new visual design - Reason: Phase 35 is hardening and refactor scope only.
* Documentation/media policy sync - Reason: assigned to Session 09 unless a changed import path requires a narrow note in implementation evidence.
* Final release gate matrix - Reason: assigned to Session 10.

### Product And Debug Surfaces

* Product surfaces: AI Rogue Play runtime canvas, runtime controls, compact controls, compile/terminal decision panels, save/load/reset states, and assistive summary.
* Debug or admin surfaces: none required. Runtime event diagnostics must remain hidden or test-only.

***

## 5. Technical Approach

### Architecture

Keep `src/extensions/ai-rogue/runtime/index.ts` as the public barrel that re-exports `runtime/mount.ts`. Treat all new renderer, effect, render-model, and view modules as internal implementation files imported explicitly by their owners. Do not create a broad replacement barrel that re-couples renderer internals.

Start with characterization and import-boundary tests, then extract pure or near-pure helpers first. Renderer state and preference helpers should move before controller wiring changes. Scheduler and browser subscription helpers should expose idempotent cleanup paths. Sprite-pool helpers should preserve transient sprite destruction and inactive sprite hiding. Inspect overlay helpers should preserve target cycling, clamping, and product-facing inspect messages.

Keep `effects.ts` as the orchestration entrypoint for `createAiRogueEffects`, but move cohesive helper domains into internal modules. Keep `render-model.ts` as the public render-model entrypoint, but move viewport/projection/HUD/summary helpers behind focused imports. Keep `runtime-canvas.tsx` as the exported view component, but move mount lifecycle and persistence/action concerns into hooks and move controls/decision panels into components under `src/extensions/ai-rogue/views/runtime/`.

### Design Patterns

* Behavior-preserving extraction: Characterize before moving code and keep command, render, and UI behavior unchanged.
* Narrow internal imports: Import concrete modules directly and avoid a broad renderer or runtime bridge barrel.
* Idempotent cleanup: Every extracted scheduler, subscription, audio, effect, and Pixi resource owner must tolerate repeated cleanup on route exit and failed mounts.
* Product-surface discipline: Normal Play route UI stays product-facing; diagnostics stay in tests, hidden event ledgers, or implementation notes.

***

## 6. Deliverables

### Files To Create

| File                                                                                              | Purpose                                                                    | Est. Lines |
| ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | ---------- |
| `.spec_system/specs/phase35-session07-renderer-and-react-bridge-refactor/implementation-notes.md` | Record evidence, moved boundaries, and follow-up caveats.                  | \~300      |
| `src/extensions/ai-rogue/runtime/renderer-scheduler.ts`                                           | Own animation-frame tasks, reduced-motion subscription, and cleanup.       | \~140      |
| `src/extensions/ai-rogue/runtime/renderer-state.ts`                                               | Own renderer state defaults, preferences, size measurement, and snapshot.  | \~180      |
| `src/extensions/ai-rogue/runtime/renderer-save.ts`                                                | Own runtime save payload and seed metadata helpers.                        | \~120      |
| `src/extensions/ai-rogue/runtime/renderer-sprites.ts`                                             | Own sprite pool sync, inactive cleanup, idle animation, and destruction.   | \~220      |
| `src/extensions/ai-rogue/runtime/renderer-layers.ts`                                              | Own Pixi layer creation and canvas preparation helpers.                    | \~110      |
| `src/extensions/ai-rogue/runtime/renderer-inspect.ts`                                             | Own inspect overlay, inspect focus, target cycling, and clamping.          | \~170      |
| `src/extensions/ai-rogue/runtime/renderer-audio-adapter.ts`                                       | Own audio preference mapping and result-to-audio dispatch.                 | \~100      |
| `src/extensions/ai-rogue/runtime/effects-hud.ts`                                                  | Own HUD overlay text projection helpers.                                   | \~180      |
| `src/extensions/ai-rogue/runtime/effects-transient.ts`                                            | Own floating numbers, impact sprites, particles, and cleanup helpers.      | \~220      |
| `src/extensions/ai-rogue/runtime/effects-cinematics.ts`                                           | Own camera/shake/flash, floor/relic cards, end screen, and layout helpers. | \~240      |
| `src/extensions/ai-rogue/runtime/render-viewport.ts`                                              | Own viewport math and viewport preference resolution.                      | \~120      |
| `src/extensions/ai-rogue/runtime/render-hud.ts`                                                   | Own HUD sprite projection, HUD descriptors, and render summaries.          | \~260      |
| `src/extensions/ai-rogue/views/runtime/use-runtime-controller.ts`                                 | Own RuntimeCanvas mount lifecycle and controller callbacks.                | \~260      |
| `src/extensions/ai-rogue/views/runtime/use-runtime-persistence-actions.ts`                        | Own save/load/reset actions and in-flight guards.                          | \~190      |
| `src/extensions/ai-rogue/views/runtime/runtime-controls.tsx`                                      | Own primary Play runtime controls.                                         | \~120      |
| `src/extensions/ai-rogue/views/runtime/runtime-decision-panels.tsx`                               | Own compile and terminal decision panels.                                  | \~180      |
| `src/extensions/ai-rogue/views/runtime/compact-runtime-controls.tsx`                              | Own compact/touch controls and command status.                             | \~150      |
| `src/extensions/ai-rogue/views/runtime/runtime-assistive-summary.ts`                              | Own assistive summary and event summary formatting helpers.                | \~180      |

### Files To Modify

| File                                                                   | Changes                                                                                       | Est. Lines |
| ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/runtime/renderer.ts`                          | Wire extracted renderer helpers while preserving controller behavior and cleanup.             | \~220      |
| `src/extensions/ai-rogue/runtime/effects.ts`                           | Orchestrate extracted effect helpers without changing effect semantics.                       | \~180      |
| `src/extensions/ai-rogue/runtime/render-model.ts`                      | Orchestrate extracted viewport/HUD helpers while preserving cache and ordering behavior.      | \~180      |
| `src/extensions/ai-rogue/views/runtime-canvas.tsx`                     | Delegate lifecycle, persistence, controls, panels, compact controls, and summaries.           | \~260      |
| `src/extensions/ai-rogue/runtime/__tests__/renderer-lifecycle.test.ts` | Preserve scheduler, cleanup, sprite-pool, inspect, and projection-cache behavior.             | \~100      |
| `src/extensions/ai-rogue/runtime/__tests__/render-model.test.ts`       | Preserve viewport, projection, HUD, summary, ordering, and cache behavior.                    | \~100      |
| `src/extensions/ai-rogue/runtime/__tests__/audio.test.ts`              | Preserve audio fallback, decode failure, dispose-before-decode, and result dispatch behavior. | \~50       |
| `src/extensions/ai-rogue/__tests__/runtime-canvas.test.tsx`            | Preserve mount cancellation, save/load/reset, compact controls, decisions, and summaries.     | \~140      |
| `tests/e2e/ai-rogue-runtime.spec.ts`                                   | Preserve route cleanup, remount, combat feedback, save/reset/load, and no query fixture leak. | \~40       |
| `tests/e2e/ai-rogue-mobile.spec.ts`                                    | Preserve compact controls, mobile no-overflow, and Large HUD behavior.                        | \~40       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Runtime mount, start, pause, resume, reset, load, save, destroy, resize, reduced-motion, and hidden-tab behavior remain unchanged after extraction.
* [ ] Projection cache remains valid and clock-only animation stays outside cached snapshot projection.
* [ ] Sprite pools still hide inactive persistent sprites, destroy transient feedback sprites, and clear on destroy or failed mount.
* [ ] Inspect mode still opens, closes, target-cycles, clamps to visible floor bounds, and renders the same product-facing inspect messages.
* [ ] RuntimeCanvas still cancels stale mounts, prevents duplicate reset/save/ compact triggers while in-flight, and resets controller state on route exit.
* [ ] Compact controls, compile choices, terminal choices, and assistive summaries render the same user-facing behavior and accessibility labels.
* [ ] No broad replacement barrel re-couples renderer, effects, render-model, audio, or React bridge internals.

### Testing Requirements

* [ ] Focused renderer lifecycle, renderer mount failure, render-model, audio, and runtime-canvas tests pass.
* [ ] AI Rogue runtime and mobile Playwright specs pass.
* [ ] Typecheck, lint, and format checks pass after module moves.
* [ ] ASCII, LF, and whitespace checks pass for changed files.

### Non-Functional Requirements

* [ ] No new dependency, asset, network, hosted write, collector, analytics, public-demo bridge, Function, WebGPU-only path, or worker behavior is introduced.
* [ ] Bundle budget risk is not increased by adding large runtime dependencies.
* [ ] Product-facing UI copy is unchanged unless an existing accessibility or product test requires the same wording to move with a component.

### 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 && bun run format:check` passes.

***

## 8. Implementation Notes

### Working Assumptions

* Session 07 should preserve current behavior rather than redesign renderer or Play UI. Evidence: the Phase 35 stub marks feature redesign as out of scope, and Sessions 03, 04, and 06 already validated the behavior contracts to protect.
* The renderer can be split without changing the mounted public entrypoint. Evidence: `runtime/index.ts` re-exports only `./mount`, `runtime/mount.ts` lazy-imports `./renderer`, and Session 06 validation passed runtime boundary checks.
* Effects and render-model should keep their existing entrypoint files as orchestrators. Evidence: renderer imports `createAiRogueEffects` and `createAiRogueRenderProjectionCache` directly, while the session requirement rejects a broad replacement barrel.
* RuntimeCanvas component extraction can proceed through local hooks and components because route behavior is already characterized. Evidence: `runtime-canvas.test.tsx` and AI Rogue mobile/runtime Playwright specs cover mount failures, compact controls, save/load/reset, assistive summary, and route cleanup behavior.

### Conflict Resolutions

* Master PRD phase table still labels Phase 35 as `Not Started`, while the analyzer output, `.spec_system/PRD/phase_35/PRD_phase_35.md`, and completed Session 01-06 validation artifacts show Phase 35 is in progress. The chosen interpretation is the analyzer and phase-local PRD are authoritative for planning because the plansession command requires script state as ground truth and the completed validations prove the current phase state.
* The folded audit appendix contains historical wording that says a Session 07 added the render projection cache, while the Phase 35 Session 07 stub and source facts say this session must preserve the cache. The chosen interpretation is preservation, not reimplementation, because Session 04 and Session 06 validations already passed projection-cache and renderer lifecycle checks.

### Key Considerations

* Keep AI Rogue production default-enabled and preserve `VITE_CLAUDE_OS_ENABLED_EXTENSIONS=none` as the explicit disable path.
* Keep AI Rogue browser-local and static-demo safe. No `/__*` bridge calls, hosted writes, collectors, analytics, Functions, remote game-content loading, WebGPU-only path, worker protocol, private path, credential, raw prompt, provider body, or raw telemetry export belongs in this session.
* Keep generated deterministic fixtures behind test/local hooks and out of product route query strings.
* Keep diagnostics hidden or test-only; normal Play route UI remains product-facing.

### Potential Challenges

* `renderer.ts` is broad and stateful: extract pure helpers first, then wire controller behavior after tests describe current behavior.
* `effects.ts` contains tightly shared closure state: keep `effects.ts` as the orchestration owner and move helper domains only where cleanup and update semantics stay obvious.
* `runtime-canvas.tsx` has many in-flight guards: move lifecycle and persistence actions into hooks with duplicate-trigger prevention and mount-generation checks intact.

### Relevant Considerations

* \[P34] **AI Rogue is production default-enabled**: Refactor must preserve default visibility and the explicit `none` disable path.
* \[P31-P34] **Public-demo and AI Rogue gates stay bundled**: Runtime and mobile browser checks should remain part of verification, even though Session 10 owns the final full gate.
* \[P31-P34] **Pages demo stays static-only**: Do not add public-demo bridge reads, writes, collectors, analytics, Functions, or runtime hosting behavior.
* \[P30/P32/P34] **Route-lazy runtime ownership scales**: Keep Pixi behind the Play route/local facade; React owns DOM accessibility and mounted imports while simulation owns run-state transitions.
* \[P30/P34] **Visibility gates catch real issues**: Pair focused unit tests with browser runtime/mobile checks after moving renderer and bridge boundaries.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Scoped lifecycle resources can leak during extraction. Scheduler, media query, resize, visibility, blur, pointer, Pixi, effects, audio, and input sampler owners must clean up on route exit, failed mount, and destroy.
* State-mutating actions can duplicate under rapid interaction. Reset, save, load, compact commands, compile choices, and terminal choices must keep in-flight prevention and state revalidation.
* Product surfaces can accidentally expose diagnostics. Runtime event details must stay hidden or test-only, and visible Play copy should remain product-facing.

***

## 9. Testing Strategy

### Unit Tests

* `src/extensions/ai-rogue/runtime/__tests__/renderer-lifecycle.test.ts` for scheduler, reduced-motion cleanup, sprite-pool cleanup, projection cache invalidation, and renderer destroy behavior.
* `src/extensions/ai-rogue/runtime/__tests__/renderer-mount-failures.test.ts` for partial Pixi cleanup and mount rejection behavior after helper moves.
* `src/extensions/ai-rogue/runtime/__tests__/render-model.test.ts` for viewport math, ordering, HUD descriptors, render summary, and cache reuse.
* `src/extensions/ai-rogue/runtime/__tests__/audio.test.ts` for no-op fallback, decode failure, dispose-before-decode, and result dispatch behavior.
* `src/extensions/ai-rogue/__tests__/runtime-canvas.test.tsx` for mount cancellation, save/load/reset, compact controls, decisions, hidden diagnostics, and assistive summaries.

### Integration Tests

* `bun run test -- src/extensions/ai-rogue/runtime src/extensions/ai-rogue/__tests__/runtime-canvas.test.tsx src/extensions/ai-rogue/__tests__/client.test.tsx`
* `bunx playwright test tests/e2e/ai-rogue-runtime.spec.ts tests/e2e/ai-rogue-mobile.spec.ts`

### Runtime Verification

* Verify Play route starts and pauses the runtime, dispatches compact commands, saves, loads, resets, handles remount, keeps runtime diagnostics hidden, and avoids product query fixture activation.

### Edge Cases

* Failed Pixi import, failed atlas load, missing Web Audio, decode failure, dispose-before-decode, repeated destroy, hidden-tab resume, reduced-motion listener failures, resize storms, stale mount cancellation, duplicate compact taps, save/load failure, terminal run state, and mobile no-overflow.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase35-session03-runtime-accessibility-controls`, `phase35-session04-renderer-robustness-and-scheduling`, `phase35-session06-simulation-ownership-refactor`
* Depended by: `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-session07-renderer-and-react-bridge-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.
