> 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-session04-renderer-robustness-and-scheduling/spec.md).

# Session Specification

**Session ID**: `phase35-session04-renderer-robustness-and-scheduling` **Phase**: 35 - AI Rogue Audit Hardening And Refactor **Status**: Not Started **Created**: 2026-06-26

***

## 1. Session Overview

This session hardens the AI Rogue renderer and media fallback paths after the Phase 35 rebaseline, fixed-blocker regression pass, and runtime accessibility pass. Sessions 01-03 establish that production default enablement, dynamic summary behavior, compact controls, sprite cleanup, and core regression anchors are protected; this session now narrows the remaining renderer jank and platform-failure caveat from AR-D4-003, AR-D7-001, and AR-D8-002.

The current code already contains an animation-frame task helper, coalesced resize scheduling, reduced-motion fallback helpers, renderer lifecycle tests, asset metadata tests, RuntimeCanvas mount-error UI, and audio fallback tests. Implementation should therefore be verify-or-add: preserve existing coverage, add focused mount and asset-failure proof where evidence is still thin, and repair only concrete failures found by those checks.

The work is next because Phase 35 has no active session, Sessions 01-03 are complete, and Session 04 is the first unfinished Phase 35 candidate. It advances the phase by making renderer scheduling and platform failure behavior safe before persistence hardening and later renderer/React bridge extraction.

***

## 2. Objectives

1. Prove ResizeObserver and window resize storms are bounded to one measured render pass per animation frame or an equivalent coalesced path.
2. Prove reduced-motion media-query setup cannot fail runtime mount when `matchMedia` throws, exposes legacy listeners only, or lacks subscription APIs.
3. Prove Pixi/WebGL initialization and atlas asset-load failures clean partial renderer resources and reach product-facing RuntimeCanvas error states instead of uncaught setup failures.
4. Prove audio remains silent-safe when Web Audio is unavailable, construction fails, fetch/decode fails, or disposal races decode completion.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase35-session01-rebaseline-audit-evidence` - Provides the current live-versus-historical finding ledger and routes AR-D4-003, AR-D7-001, and AR-D8-002 to this session.
* [x] `phase35-session02-fixed-blocker-regression-coverage` - Confirms sprite lifecycle, fixed blocker, and mounted summary regression anchors before renderer fallback hardening.
* [x] `phase35-session03-runtime-accessibility-controls` - Confirms the Play surface product-facing RuntimeCanvas fallback and accessibility behavior that renderer failures must preserve.

### Required Tools Or Knowledge

* Bun 1.3.14 for Vitest, typecheck, lint, build, and scripts.
* Playwright Chromium for AI Rogue runtime route smoke.
* PixiJS v8 renderer lifecycle, Vite dynamic imports, Web Audio fallback behavior, and the AI Rogue RuntimeCanvas bridge.
* Current AI Rogue asset, renderer, render-model, audio, and browser test patterns.

### Environment Requirements

* Local dependencies installed from `bun.lock`.
* Playwright browser binaries available for focused Chromium tests.
* `src/data/live-data.json` can be seeded by `bun run seed:data` if absent.

***

## 4. Scope

### In Scope (MVP)

* AI Rogue Play users can resize the browser or host container without unbounded immediate resize/render work - verify or repair the `createAnimationFrameTask`, `scheduleResize`, and `resize()` controller paths in `renderer.ts`.
* AI Rogue users in locked-down or legacy browser environments cannot lose the runtime because reduced-motion probing throws or exposes only legacy listener APIs - verify or repair `createReducedMotionSync` and subscription cleanup in `renderer.ts`.
* AI Rogue users on unsupported or failing WebGL/Pixi/asset paths get a controlled RuntimeCanvas loading/error state - add focused proof around `mountAiRogueRenderer`, partial Pixi cleanup, atlas asset loading, and the RuntimeCanvas mount rejection path.
* AI Rogue users with unavailable or failing Web Audio get silent fallback behavior - verify or repair `createAiRogueAudioEngine` for missing `AudioContext`, constructor failure, fetch/decode failure, and dispose races.
* AI Rogue tests preserve render projection cache reuse/invalidation and transient feedback sprite cleanup while scheduler and fallback evidence is tightened.

### Out Of Scope (Deferred)

* WebGPU support - Reason: Phase 35 explicitly excludes WebGPU and WebGPU-only behavior without fresh review.
* Worker protocols or hosted runtime rendering - Reason: would widen the privacy/capability model and is outside this hardening session.
* New audio behavior, sidechain ducking, or new media assets - Reason: this session covers fallback and lifecycle safety only.
* Browser storage quota or blocked IndexedDB harnesses - Reason: Session 05 owns the storage portion of AR-D8-002 and persistence schema contracts.
* Renderer, effects, render-model, audio adapter, or React bridge module extraction - Reason: Session 07 owns extraction after this fallback behavior is protected.
* Documentation/media-policy cleanup and final release gate matrix - Reason: assigned to Sessions 09-10.
* Hosted writes, collectors, analytics, remote game-content loading, Pages Functions, public-demo bridge calls, or expanded game content - Reason: requires fresh review and is outside this session.

***

## 5. Technical Approach

### Architecture

Start with behavior-owned characterization. The renderer owns resize scheduling, reduced-motion browser subscriptions, Pixi lifecycle, render cache clearing, sprite cleanup, and low-level mount error cleanup. The asset module owns atlas metadata validation, Pixi asset loading, nearest-neighbor texture configuration, and explicit frame texture errors. RuntimeCanvas owns the product-facing loading and error states when mount rejects. The audio engine owns silent Web Audio fallback and disposal safety.

Run focused tests before source edits. If current code already satisfies a contract, record the evidence and add only the missing assertion or mount harness. If a repair is required, keep it local to the owner module and avoid extracting renderer architecture ahead of Session 07. All user-facing fallback copy should remain product-facing; diagnostics belong in tests and session evidence.

### Design Patterns

* Verify-or-add hardening: preserve existing behavior and add direct evidence before changing runtime code.
* Behavior-owned tests: keep renderer lifecycle tests under `runtime/__tests__/`, RuntimeCanvas UI tests under the extension test folder, and browser route proof in `tests/e2e/ai-rogue-runtime.spec.ts`.
* Controlled failure propagation: lower-level renderer/asset/audio failures either degrade silently where appropriate or reject through the existing RuntimeCanvas error state.
* Cleanup on scope exit: cancel frame tasks, disconnect subscriptions, destroy partial Pixi resources, clear sprite pools, and stop audio handles during failed or destroyed mounts.
* Browser-local boundary: no new network, bridge, hosted write, collector, analytics, worker, WebGPU-only, or remote asset capability.

***

## 6. Deliverables

### Files To Create

| File                                                                                              | Purpose                                                                      | Est. Lines |
| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------- |
| `.spec_system/specs/phase35-session04-renderer-robustness-and-scheduling/implementation-notes.md` | Evidence ledger for renderer scheduling, platform failures, audio, and gates | \~280      |
| `src/extensions/ai-rogue/runtime/__tests__/renderer-mount-failures.test.ts`                       | Focused Pixi/WebGL init, atlas load, partial cleanup, and mount error proof  | \~160      |

### Files To Modify

| File                                                                   | Changes                                                                                         | Est. Lines |
| ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/runtime/renderer.ts`                          | Repair only if resize, reduced-motion, Pixi init, asset failure, or cleanup evidence fails      | \~80       |
| `src/extensions/ai-rogue/runtime/assets.ts`                            | Repair only if atlas load failure or texture-source errors are unclear or unsafe                | \~20       |
| `src/extensions/ai-rogue/runtime/audio.ts`                             | Repair only if silent fallback, fetch/decode failure, or dispose-race coverage exposes a gap    | \~40       |
| `src/extensions/ai-rogue/views/runtime-canvas.tsx`                     | Repair only if renderer/Pixi rejection does not surface product-facing loading and error states | \~25       |
| `src/extensions/ai-rogue/runtime/__tests__/renderer-lifecycle.test.ts` | Add or refine resize coalescing, reduced-motion, cache, and sprite lifecycle assertions         | \~70       |
| `src/extensions/ai-rogue/runtime/__tests__/assets.test.ts`             | Add or refine atlas load rejection and texture-source failure assertions                        | \~45       |
| `src/extensions/ai-rogue/runtime/__tests__/audio.test.ts`              | Add or refine silent fallback, fetch/decode, heartbeat/music dispose, and race assertions       | \~55       |
| `src/extensions/ai-rogue/__tests__/runtime-canvas.test.tsx`            | Add or refine product-facing mount rejection assertions for lower-level renderer failures       | \~35       |
| `tests/e2e/ai-rogue-runtime.spec.ts`                                   | Add or refine runtime resize and route cleanup smoke proof after scheduling changes             | \~35       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Resize storms produce bounded resize/render work, ideally one measured pass per animation frame, while the synchronous controller `resize()` path remains available.
* [ ] Reduced-motion probing cannot fail runtime mount by itself when `matchMedia` throws, lacks subscriptions, or exposes legacy listeners only.
* [ ] Pixi/WebGL initialization and atlas asset failures clean partial renderer resources and surface a controlled RuntimeCanvas error state.
* [ ] Audio failures stay silent or no-op safe for missing `AudioContext`, constructor failure, fetch failure, decode failure, and dispose races.
* [ ] Render projection cache reuse/invalidation and transient feedback sprite cleanup remain covered after scheduler or fallback changes.

### Testing Requirements

* [ ] Renderer lifecycle and mount-failure focused tests pass.
* [ ] Asset and audio focused tests pass.
* [ ] RuntimeCanvas focused mount-error tests pass.
* [ ] AI Rogue runtime Playwright smoke passes for nonblank canvas, resize reporting, keyboard input, and route cleanup.
* [ ] Typecheck, lint, build, budget, asset-size, and targeted privacy scans pass after source or test changes.

### Non-Functional Requirements

* [ ] No new hosted write, collector, analytics, remote-loading, worker, WebGPU-only, or public-demo bridge surface is introduced.
* [ ] No new dependency, media asset, or bundle-budget overage is introduced.
* [ ] User-facing fallback copy remains product-facing; diagnostics remain in tests, hidden events, or implementation evidence.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] Primary user-facing surfaces contain product-facing copy only.

***

## 8. Implementation Notes

### Working Assumptions

* Session 04 should be evidence-first rather than a renderer rewrite. Repo evidence shows `renderer.ts` already uses `createAnimationFrameTask` for `scheduledResize`, `renderer-lifecycle.test.ts` already covers task coalescing and reduced-motion fallbacks, and `audio.test.ts` already covers several silent fallback paths. Planning can proceed because the remaining work is to fill direct mount/asset failure proof and repair only concrete gaps.
* Pixi/WebGL init failure should be represented as a controlled mount rejection handled by RuntimeCanvas, not a new product UI mode. Repo evidence shows `runtime-canvas.test.tsx` already asserts rejected mounts produce a product-facing runtime error state, and `renderer.ts` already cleans partial Pixi app state in its catch path. Planning can proceed by strengthening that path instead of inventing a new route surface.
* This is not a monorepo session. The analysis script reported no monorepo detection, no packages, and no active package, so repo-root-relative paths are sufficient.

### Conflict Resolutions

* The Session 04 stub lists several coverage gaps, but current source already contains direct tests for resize task coalescing, throwing `matchMedia`, legacy reduced-motion listeners, missing `AudioContext`, failed fetch/decode, and dispose-before-decode. The chosen interpretation is to preserve existing coverage, add missing Pixi/asset mount-failure harnesses, and repair only if the focused evidence fails. This wins because it aligns with the newer completed Session 01-03 evidence and the current source state.
* The folded audit mentions blocked/quota IndexedDB as feasible platform coverage, while the Session 05 stub assigns storage failure and persistence schema contracts to Session 05. The chosen interpretation is to defer browser storage quota/blocked harnesses to Session 05 and keep Session 04 on renderer, asset, and audio failure paths. This wins because it preserves the phase split and avoids mixing persistence scope into renderer scheduling.

### Key Considerations

* Keep AI Rogue production-enabled by default and preserve `VITE_CLAUDE_OS_ENABLED_EXTENSIONS=none` as the explicit disable path.
* Keep AI Rogue browser-local and static-demo safe.
* Preserve route-lazy Pixi ownership behind the Play route/local facade.
* Avoid adding WebGPU, workers, hosted writes, collectors, analytics, remote game-content loading, or public-demo bridge dependencies.
* Keep total client JS gzip under the 1500 KB cap and avoid new media assets.

### Potential Challenges

* Pixi mount-failure tests may need module-level mocks or a small test-only seam in `renderer.ts`: prefer the smallest owner-local harness that proves cleanup without extracting Session 07 architecture early.
* Build and budget headroom is tight: avoid new dependencies and keep any test helpers out of production bundles unless they are already tree-shaken test-only exports.
* Dynamic imports can make failure paths asynchronous: tests should await mount rejection and cleanup events rather than relying on immediate synchronous assertions.

### Relevant Considerations

* \[P34] **AI Rogue is production default-enabled**: Preserve the default and explicit `none` disable path while hardening runtime fallback behavior.
* \[P31-P34] **Pages and AI Rogue CI guards deferred**: Keep Pages/public-demo boundaries visible in evidence and avoid introducing bridge or hosted runtime dependencies.
* \[P31-P34] **Public-demo and AI Rogue gates stay bundled**: Runtime changes should be validated with private-runtime, asset-size, no-remote, budget, and browser smoke checks.
* \[P30/P32/P34] **Route-lazy runtime ownership scales**: Keep Pixi behind the Play route/local facade; React owns DOM fallback states.
* \[P30/P32/P34] **Do not widen AI Rogue capabilities without review**: Production default visibility is approved, but collectors, WebGPU, workers, remote loading, hosted writes, and expanded content are not.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Renderer lifecycle work can leak frame callbacks, subscriptions, Pixi resources, sprites, or audio handles on failed or destroyed mounts.
* Platform failures can become uncaught setup errors instead of controlled product-facing fallback states.
* Scheduler or reduced-motion changes can invalidate render cache, sprite cleanup, or accessibility summary behavior if not covered by focused tests.

***

## 9. Testing Strategy

### Unit Tests

* Run renderer lifecycle tests for resize coalescing, reduced-motion fallback, projection cache reuse/invalidation, and sprite cleanup.
* Run renderer mount-failure tests for Pixi init rejection, atlas asset load rejection, partial app destroy, and mount rejection status events.
* Run asset tests for atlas worker preferences, load rejection behavior, and explicit texture-source/frame errors.
* Run audio tests for missing Web Audio, constructor failure, fetch/decode failure, heartbeat/music disposal, and dispose-before-decode races.
* Run RuntimeCanvas tests for product-facing mount loading and error states.

### Integration Tests

* Run focused AI Rogue runtime Playwright tests for nonblank canvas mount, resize reporting, keyboard input, route exit cleanup, and clean remount.

### Runtime Verification

* Execute `bun run build`, `bun run budget:check`, `bash scripts/check-asset-sizes.sh`, `bun run runtime:check-private`, and targeted AI Rogue source scans if runtime source changes.

### Edge Cases

* ResizeObserver and window resize callbacks fire repeatedly before the next animation frame.
* `window.matchMedia` throws, returns listener-less objects, or supports only `addListener`/`removeListener`.
* Pixi application initialization rejects before a canvas is appended.
* Atlas image loading rejects after a partial Pixi application exists.
* Audio decode completes after the engine has been disposed.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase35-session01-rebaseline-audit-evidence`, `phase35-session02-fixed-blocker-regression-coverage`, `phase35-session03-runtime-accessibility-controls`
* Depended by: `phase35-session07-renderer-and-react-bridge-refactor`, `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-session04-renderer-robustness-and-scheduling/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.
