> 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/phase34-session07-render-performance-and-audio-docs/spec.md).

# Session Specification

**Session ID**: `phase34-session07-render-performance-and-audio-docs` **Phase**: 34 - AI Rogue Audit Remediation **Status**: Not Started **Created**: 2026-06-26

***

## 1. Session Overview

This session reduces AI Rogue renderer hot-loop allocation pressure and reconciles current audio/media documentation with implemented behavior. It is next because the analysis script reported Phase 34 active, no current session, Sessions 01 through 06 completed, and Session 07 as the first unfinished current-phase candidate.

The work fixes AR-D4-002 by adding a bounded render projection cache around `createAiRogueRenderModel` so repeated ticker renders do not rebuild the full descriptor graph when the simulation snapshot, viewport, tile scale, and render preferences are unchanged. Clock-only presentation, tweens, effects, inspect overlay, and Pixi draw calls must continue to update independently of pure snapshot projection.

The session also resolves AR-D9-001 and AR-D9-002 by updating current docs and runtime comments to match reality: AI Rogue has Web Audio mixing, fades, loops, one-shots, local Ogg assets, and the reviewed 900 KB music cap, but it does not currently implement sidechain or event-based music ducking. Default enablement remains deferred to Session 08 closeout evidence.

***

## 2. Objectives

1. Avoid repeated full render-model rebuilds on unchanged active ticker frames.
2. Preserve render-model correctness when run state, viewport, tile scale, or runtime preferences change.
3. Remove current "ducking" claims from code comments and docs unless explicit ducking is implemented in this session.
4. Align AI Rogue media and enablement docs with current Web Audio, asset-size, IndexedDB, and default-enablement posture.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase34-session01-characterization-test-harness` - Provides baseline render-model and AI Rogue regression coverage.
* [x] `phase34-session02-accessibility-and-compact-input` - Provides the dynamic runtime summary and input-mode behavior that cached render summaries must preserve.
* [x] `phase34-session04-renderer-lifecycle-and-robustness` - Provides bounded transient sprite cleanup, resize scheduling, media-query fallback, and audio fallback coverage.
* [x] `phase34-session06-persistence-schema-contracts` - Provides current browser-local IndexedDB and durable save-contract evidence used by docs.

### Required Tools Or Knowledge

* AI Rogue render projection in `src/extensions/ai-rogue/runtime/render-model.ts`.
* AI Rogue Pixi render loop, ticker, effects, resize, and audio integration in `src/extensions/ai-rogue/runtime/renderer.ts`.
* Existing render-model, renderer lifecycle, runtime canvas, and audio tests under `src/extensions/ai-rogue/`.
* Current docs in `docs/extensions/ai-rogue/` and `docs/media-policy.md`.
* Phase 34 audit source of truth in `.spec_system/PRD/phase_35/PRD_phase_35.md`.

### Environment Requirements

* Bun 1.3.14 project tooling.
* No new dependencies, generated media assets, art regeneration, binary re-encoding, SQL database, hosted persistence, remote loading, collectors, analytics, or Cloudflare dashboard actions are required.
* AI Rogue remains explicit opt-in and browser-local.

***

## 4. Scope

### In Scope (MVP)

* AI Rogue renderer can reuse the previous render model when the mounted run snapshot identity or turn/depth/status, viewport dimensions, preferred tile scale, and render preferences are unchanged.
* AI Rogue renderer invalidates projection cache on run reset, load, command result, resize, reduced-motion change, high-contrast change, Large HUD change, input-mode change, or seed metadata change.
* Clock-only animation and transient effects stay outside the projection cache so active ticker frames still animate and render correctly.
* Focused tests characterize render-model cache reuse and invalidation.
* Current docs and comments describe Web Audio mixing, loops, fades, one-shots, lazy local Ogg decode, and silent fallback without claiming unimplemented ducking.
* AI Rogue enablement and asset docs distinguish historical no-audio evidence from current Web Audio behavior, reviewed 900 KB music cap, and browser-local localStorage/IndexedDB state.

### Out Of Scope (Deferred)

* Implementing new audio ducking behavior - Reason: current code has no sidechain/compressor/event-based ducking path and the lower-risk fix is to remove the inaccurate current claim.
* New audio or visual assets - Reason: this session addresses runtime projection and documentation drift only.
* Broad rewrite of `render-model.ts`, `effects.ts`, or renderer ownership - Reason: the Phase 34 stub explicitly defers broad rewrite work.
* Resize coalescing and transient sprite retention - Reason: handled in Session 04 and should not be reopened unless regression evidence appears.
* Default enablement decision or full release gate table - Reason: assigned to Session 08.

***

## 5. Technical Approach

### Architecture

Add a small bounded cache at the renderer/render-model boundary. The cache should store only the latest projection for the mounted controller, not a process-wide map. The cache key should include the run snapshot object and the semantic values that can change projection output: turn, depth, status, viewport width, viewport height, preferred tile scale, reduced motion, high contrast, Large HUD labels, concrete input mode, and seed metadata.

Implement the cache either as a tiny helper in `render-model.ts` with focused unit coverage or as a renderer-local helper with exported test seams. The helper should return the same `AiRogueRenderModel` instance for repeated unchanged inputs, and a fresh model after any key input changes. Keep background drift, damage vignette, idle enemy animation, tweened entity positions, effects HUD, inspect overlay, camera snap, and `app.render()` as per-frame presentation work outside the cache.

For docs, update current maintained docs instead of rewriting historical session records. `enablement-decision.md` can keep Session 10 evidence when it is labeled historical or superseded by current Web Audio and media-policy records. `README.md`, `runtime/audio.ts`, `implementation-baseline.md`, `visual-assets.md`, and `folded Phase 35 PRD source` should stop implying that all AI Rogue runtime assets share the old 200 KB image cap or that audio ducking exists today.

### Design Patterns

* Latest-value cache: one mounted controller cache, invalidated by value keys and cleared on controller destroy/reset/load paths.
* Pure projection boundary: `createAiRogueRenderModel` remains deterministic for a snapshot and preferences; animation stays in renderer/effects.
* Documentation as contract: maintained docs describe current behavior, while historical session closeout evidence is explicitly labeled when stale.
* Static/local media posture: AI Rogue audio remains committed local Ogg assets loaded through Vite URL globs and browser Web Audio, not remote content.

***

## 6. Deliverables

### Files To Create

| File                                                                                             | Purpose                                                           | Est. Lines |
| ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- | ---------- |
| `.spec_system/specs/phase34-session07-render-performance-and-audio-docs/implementation-notes.md` | Session notes, AR-D4/AR-D9 evidence, decisions, and gate results. | \~180      |

### Files To Modify

| File                                                                   | Changes                                                                                   | Est. Lines |
| ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/runtime/render-model.ts`                      | Add latest-value projection cache helper or key utilities if kept near pure projection.   | \~90       |
| `src/extensions/ai-rogue/runtime/renderer.ts`                          | Reuse cached render projection and clear/invalidate cache on state and lifecycle changes. | \~80       |
| `src/extensions/ai-rogue/runtime/__tests__/render-model.test.ts`       | Cover cache reuse, invalidation, and deterministic projection behavior.                   | \~90       |
| `src/extensions/ai-rogue/runtime/__tests__/renderer-lifecycle.test.ts` | Cover renderer integration or test seams for projection rebuild bounds.                   | \~80       |
| `src/extensions/ai-rogue/runtime/audio.ts`                             | Update comments to describe mixing without unimplemented ducking.                         | \~10       |
| `docs/extensions/ai-rogue/README.md`                                   | Update current audio/media language and default-enablement posture.                       | \~30       |
| `docs/extensions/ai-rogue/enablement-decision.md`                      | Label no-audio/200 KB evidence as historical or superseded by current media policy.       | \~40       |
| `docs/extensions/ai-rogue/implementation-baseline.md`                  | Clarify current runtime image, audio, localStorage, and IndexedDB contracts.              | \~35       |
| `docs/extensions/ai-rogue/visual-assets.md`                            | Clarify image-atlas caps versus current audio policy references.                          | \~20       |
| `.spec_system/PRD/phase_35/PRD_phase_35.md`                            | Record AR-D4-002, AR-D9-001, and AR-D9-002 remediation evidence or status.                | \~70       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Active ticker frames do not rebuild `createAiRogueRenderModel` output when snapshot, viewport, tile scale, and render preferences are unchanged.
* [ ] Cached projection invalidates after simulation command results, reset, load, resize, reduced-motion change, high-contrast change, Large HUD change, input-mode change, and seed metadata change.
* [ ] Entity tweening, idle animation, effects, inspect overlay, damage vignette, background drift, camera snap, and `app.render()` still run when projection is reused.
* [ ] Current maintained docs and comments no longer claim unimplemented audio ducking.
* [ ] Current maintained docs distinguish historical no-audio/all-assets-200-KB evidence from current Web Audio and 900 KB AI Rogue music policy.
* [ ] No new remote loading, hosted writes, collectors, analytics, assets, or dependency changes are introduced.

### Testing Requirements

* [ ] Render-model cache tests cover repeated unchanged input, snapshot change, viewport change, preference change, and seed metadata change.
* [ ] Renderer lifecycle or adjacent tests cover cache integration and cache cleanup/invalidation behavior.
* [ ] Existing audio fallback tests still pass after comment/doc updates.
* [ ] Focused AI Rogue runtime tests pass or exact local blockers are recorded.

### Non-Functional Requirements

* [ ] AI Rogue remains explicit opt-in and browser-local.
* [ ] Static Pages/public-demo safety remains intact with no `/__*` bridge calls, hosted mutation requests, or remote media loading.
* [ ] Bundle and asset budget posture does not regress from the current 1500 KB total client JS gzip budget and checked asset-size policy.
* [ ] Product-facing routes keep product-facing copy only; docs and tests carry 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.
* [ ] `bun run test -- src/extensions/ai-rogue/runtime/__tests__/render-model.test.ts src/extensions/ai-rogue/runtime/__tests__/renderer-lifecycle.test.ts src/extensions/ai-rogue/runtime/__tests__/audio.test.ts` passes or exact blockers are recorded.
* [ ] `bun run test -- src/extensions/ai-rogue` passes or exact blockers are recorded.
* [ ] `bun run typecheck`, `bun run lint`, and `bun run format:check` pass or exact blockers are recorded.
* [ ] `bun run budget:check`, `bash scripts/check-asset-sizes.sh`, and `bun run runtime:check-private` pass or exact blockers are recorded.

***

## 8. Implementation Notes

### Working Assumptions

* Audio ducking should be removed from current docs/comments rather than implemented in this session. Repo evidence: the Session 07 stub says to decide between implementation and removal, `runtime/audio.ts` has gain buses, fades, loops, one-shots, and heartbeat but no sidechain/compressor/event ducking, and `game-feel.md` already describes the current mixing behavior without requiring ducking. Planning can proceed because removing the inaccurate claim fixes the audit drift without adding new audio behavior, assets, or risk.
* The render projection cache belongs at the latest-value renderer boundary instead of a broad render-model rewrite. Repo evidence: the audit recommends a cache keyed by snapshot, viewport, and preferences, while the Session 07 stub excludes broad rewrites of `render-model.ts` or `effects.ts`. Planning can proceed because a one-entry cache is enough to stop repeated unchanged-frame rebuilds and remains easy to invalidate.
* The current media policy already supports AI Rogue music under a reviewed 900 KB cap. Repo evidence: `docs/media-policy.md` lists an AI Rogue music-track cap and `scripts/check-asset-sizes.sh` is the enforcement path; the stale drift is in older enablement language. Planning can proceed by updating maintained docs and preserving historical evidence labels.

### Conflict Resolutions

* Security posture vs Phase 34 audit blockers: `.spec_system/SECURITY-COMPLIANCE.md` reports no open security findings, while Phase 34 audit docs list AR-D4 and AR-D9 blockers. The selected interpretation is that these are product quality, performance, and default-enablement blockers, not cumulative security findings. The plan therefore fixes performance/docs drift while preserving the clean security posture.
* Historical enablement evidence vs current runtime: `enablement-decision.md` says no audio implementation was found and all AI Rogue runtime assets were under the old 200 KB cap, while current source/docs include Web Audio, local Ogg assets, and the reviewed 900 KB AI Rogue music cap. The current code and media policy win for maintained docs; older rows should be labeled historical or superseded rather than silently treated as current truth.

### Key Considerations

* Do not change default enablement or public-demo hosted behavior.
* Keep PixiJS, audio, and projection work route-scoped to AI Rogue Play.
* Prefer focused tests and small helper seams over large renderer refactors.
* Record exact evidence for Session 08 closeout.

### Potential Challenges

* Cache keys can miss preference changes if they rely only on object identity: build a semantic key from the values that affect projection.
* Cached summaries can go stale for assistive surfaces: include summary-affecting preferences and seed metadata in the cache key.
* A cache can mask reset/load bugs if it survives lifecycle changes: clear it on controller destroy, reset, load, and run-start paths.
* Docs can accidentally imply default-on approval: keep default enablement as a Session 08 recommendation decision.

### Relevant Considerations

* \[P30/P32] **AI Rogue default enablement deferred**: This session reduces blockers but must not flip default enablement.
* \[P31-P33] **Pages demo stays static-only**: Runtime and docs changes must not introduce bridge calls, hosted writes, collectors, analytics, Functions, or remote loading.
* \[P30/P32] **Route-lazy runtime ownership scales**: Keep Pixi/audio behind the Play route runtime boundary and clear resources on scope exit.
* \[P30] **Opt-in gates catch real issues**: Pair focused tests with type, lint, format, budget, private-runtime, asset-size, and no-remote checks before closeout.
* \[P30/P32] **Do not let docs imply approval or default enablement**: Current docs must be accurate about audio and media policy without declaring default enablement done.

### Behavioral Quality Focus

Checklist active: Yes

Top behavioral risks for this session:

* Stale cached render projection after a simulation, viewport, input, or accessibility preference change.
* Hidden lifecycle retention if cached models outlive reset, load, or destroy.
* Documentation drift that causes reviewers to believe ducking, no-audio, or default enablement are current truths when they are not.

***

## 9. Testing Strategy

### Unit Tests

* `src/extensions/ai-rogue/runtime/__tests__/render-model.test.ts` for cache reuse, invalidation, summary preservation, seed metadata changes, and stable sorted sprite projection.
* `src/extensions/ai-rogue/runtime/__tests__/renderer-lifecycle.test.ts` for renderer cache integration or helper test seams that prove repeated render calls are bounded.
* `src/extensions/ai-rogue/runtime/__tests__/audio.test.ts` for existing Web Audio fallback behavior after comment-only changes.

### Integration Tests

* `bun run test -- src/extensions/ai-rogue` to cover nearby runtime, canvas, save, accessibility summary, and audio behavior.

### Runtime Verification

* Source inspect the renderer render path to ensure clock-driven animation and effects still run every frame while projection is cached.
* Run budget, asset-size, private-runtime, no-bridge, no-hosted-write, and no-remote-loading spot checks to preserve Session 08 closeout posture.

### Edge Cases

* Same snapshot rendered across multiple active ticker frames.
* Same snapshot after viewport width or height changes.
* Same snapshot after `reducedMotion`, `highContrastTiles`, `largeHudLabels`, `inputMode`, or seed metadata changes.
* Run reset, load, start, completion, victory, defeat, and controller destroy.
* Current docs mentioning audio, no-audio, ducking, IndexedDB, localStorage, media cap, default enablement, and remote loading.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase34-session01-characterization-test-harness`, `phase34-session02-accessibility-and-compact-input`, `phase34-session04-renderer-lifecycle-and-robustness`, `phase34-session06-persistence-schema-contracts`.
* Depended by: `phase34-session08-default-enablement-evidence-closeout`.

***

## 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/phase34-session07-render-performance-and-audio-docs/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.
