> 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/phase36-session04-theme-audio-routing-contract/spec.md).

# Session Specification

**Session ID**: `phase36-session04-theme-audio-routing-contract` **Phase**: 36 - AI Rogue Audio Asset Finishing **Status**: Not Started **Created**: 2026-06-28

***

## 1. Session Overview

This session defines and implements the AI Rogue theme-audio routing contract for sector identity. It keeps the current depth/title/victory/defeat music lane intact, then adds a second low-gain ambience lane keyed by `snapshot.theme` so each sector theme can later receive its own subtle bed without replacing the existing music tracks.

This is next because Sessions 01 through 03 completed the browser-path audio audit, typed enemy metadata, and enemy/boss SFX pack. The remaining Phase 36 theme work needs a runtime contract before Session 05 can generate and commit the five sector ambience assets safely.

The product surface is normal AI Rogue gameplay. Theme audio remains presentation-only: it must not affect simulation state, RNG, replay behavior, save contracts, progression, public-demo boundaries, or hosted runtime capabilities.

***

## 2. Objectives

1. Add a typed theme ambience route for every `AiRogueSectorThemeId`.
2. Wire the renderer audio adapter so run start, descend, reset, load, victory, defeat, mute, volume, autoplay unlock, and silent fallback all handle theme ambience consistently.
3. Document the selected asset type, bus behavior, asset location, size policy, and Session 05 wiring contract.
4. Add focused tests proving theme selection, fallback behavior, and unchanged depth/victory/defeat music behavior.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase36-session01-current-audio-balance-audit` - Provides browser-path evidence for current title, music, SFX, mute, volume, unlock, and silent fallback behavior.
* [x] `phase36-session02-enemy-audio-metadata` - Provides the current typed audio-event precedent and preserves audio as presentation-only metadata.
* [x] `phase36-session03-enemy-and-boss-sfx-pack` - Provides the current 57-cue SFX baseline and confirms the audio runtime can expand without widening hosted or deterministic-simulation boundaries.
* [x] `phase35-session10-final-release-gate` - Provides the Production Go posture, public-demo safety boundary, asset checks, and privacy gate.

### Required Tools Or Knowledge

* Bun 1.3.14 project scripts.
* Existing Web Audio engine behavior in `src/extensions/ai-rogue/runtime/audio.ts`.
* Existing run-state adapter behavior in `src/extensions/ai-rogue/runtime/renderer-audio-adapter.ts`.
* Existing sector theme contract in `src/extensions/ai-rogue/runtime/themes.ts`.
* Media policy for AI Rogue music and non-music assets in `docs/media-policy.md`.

### Environment Requirements

* Run from the repository root.
* Do not generate or commit final theme audio files in this session.
* Keep new routing code browser-local and local-asset only.
* Keep generated session artifacts ASCII-only with Unix LF line endings.

***

## 4. Scope

### In Scope (MVP)

* AI Rogue runtime can resolve a theme ambience route from `snapshot.theme` for `cold-cache`, `corrupted-index`, `kernel-core`, `firewall`, and `model-vault`.
* AI Rogue audio engine exposes a separate ambience lane with its own active handle, fade behavior, stop behavior, and silent missing-asset fallback.
* Theme ambience uses the existing music preference and master mute state so no new user preference or persisted schema change is required.
* Renderer start, descend, reset, load, victory, defeat, and destroy paths coordinate theme ambience without disrupting depth music, title music, victory music, defeat music, heartbeat, SFX, autoplay unlock, or silent fallback.
* Documentation states that Session 05 should commit the five optimized ambience loops under `src/assets/ai-rogue/audio/music/` and treat them as AI Rogue music-loop assets under the 900 KB per-track cap.

### Out Of Scope (Deferred)

* Generating, optimizing, or committing the final five theme audio files - Reason: Session 05 owns the sector theme audio pack.
* Adaptive stingers, ducking, sidechain compression, transient combat music, or extra music gain automation - Reason: Sessions 06 and 07 own adaptive music only after this contract is stable.
* New Settings UI for ambience volume - Reason: the MVP contract ties ambience to the existing music preference and mute state.
* Remote streaming, CDN loading, runtime downloads, hosted writes, collectors, analytics, or public-demo bridge calls - Reason: Phase 36 requires committed local game media and unchanged public-demo boundaries.
* Changing simulation rules, RNG, replay behavior, save schema, or gameplay balance based on audio routing - Reason: audio remains presentation-only.

***

## 5. Technical Approach

### Architecture

Keep the primary music lane as-is: `playMusic()` continues to own title, depth sector music, victory, and defeat. Add a separate ambience lane in `audio.ts` with a dedicated `themeAmbienceGain`, active handle, pending route, and `playThemeAmbience()` / `stopThemeAmbience()` methods. The ambience lane uses the existing master mute and music volume mix so it inherits current preferences without adding persisted settings.

Define a typed `AiRogueThemeAmbienceId` and a deterministic `themeAmbienceForTheme(theme)` mapping. The mapping chooses five concrete contract IDs and future file basenames for Session 05: `theme_cold_cache_ambience`, `theme_corrupted_index_ambience`, `theme_kernel_core_ambience`, `theme_firewall_ambience`, and `theme_model_vault_ambience`. Missing files must no-op through the same lazy URL lookup and decode failure path as existing audio assets.

Update `renderer-audio-adapter.ts` so the adapter receives the selected snapshot theme, starts or changes ambience on run start and descend, and stops ambience before victory/defeat terminal music. Update `renderer.ts` reset and load paths so stopped runs do not leave stale ambience playing and saved runs revalidate the loaded snapshot theme on the next start.

### Design Patterns

* Presentation-only route: Theme selection reads `snapshot.theme` but never writes to simulation state, RNG, saves, or gameplay logic.
* Two-lane playback: Depth music remains the primary lane; theme ambience uses a lower-gain parallel lane and stops independently.
* Local asset contract: Session 04 declares future basenames and docs; Session 05 commits optimized local Ogg Opus loops with provenance.
* Silent-safe fallback: Missing ambience URLs, failed fetches, failed decodes, unavailable Web Audio, mute, reset, load, and destroy paths remain no-op safe.

***

## 6. Deliverables

### Files To Create

| File                                                                                        | Purpose                                                       | Est. Lines |
| ------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/runtime/__tests__/renderer-audio-adapter.test.ts`                  | Cover adapter-level theme ambience start, change, and stop.   | \~180      |
| `.spec_system/specs/phase36-session04-theme-audio-routing-contract/implementation-notes.md` | Record implementation, test, docs, and verification evidence. | \~160      |

### Files To Modify

| File                                                                         | Changes                                                                                                | Est. Lines |
| ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ---------- |
| `src/extensions/ai-rogue/runtime/audio.ts`                                   | Add theme ambience IDs, URL mapping, ambience gain lane, play/stop methods, resolver, and tests hook.  | \~180      |
| `src/extensions/ai-rogue/runtime/renderer-audio-adapter.ts`                  | Route `snapshot.theme` to ambience start/change/stop behavior around run lifecycle events.             | \~90       |
| `src/extensions/ai-rogue/runtime/renderer.ts`                                | Wire the ambience resolver, reset/load stops, fresh-start starts, and terminal-state cleanup.          | \~60       |
| `src/extensions/ai-rogue/runtime/themes.ts`                                  | Align sector audio hints with the new ambience contract IDs.                                           | \~40       |
| `src/extensions/ai-rogue/runtime/__tests__/audio.test.ts`                    | Cover ambience URL selection, pending unlock, missing asset fallback, stop, dispose, mute, and volume. | \~180      |
| `src/extensions/ai-rogue/runtime/__tests__/themes.test.ts`                   | Cover every sector theme has a stable ambience route.                                                  | \~40       |
| `docs/extensions/ai-rogue/game-feel.md`                                      | Document the theme ambience routing contract and Session 05 asset targets.                             | \~60       |
| `docs/media-policy.md`                                                       | Clarify that AI Rogue theme ambience loops live under `audio/music/` and use the music cap.            | \~30       |
| `.spec_system/PRD/phase_36/session_04_theme_audio_routing_contract.md`       | Mark the routing decision and implementation evidence once delivered.                                  | \~40       |
| `.spec_system/specs/phase36-session04-theme-audio-routing-contract/tasks.md` | Track implementation progress during the session.                                                      | \~40       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Every sector theme resolves to a stable theme ambience route by `snapshot.theme`.
* [ ] Start and descend paths select theme ambience without replacing current depth music.
* [ ] Victory, defeat, reset, load, destroy, unavailable Web Audio, missing ambience files, failed fetches, and failed decodes recover silently.
* [ ] Mute and music volume affect the ambience lane consistently with the current music lane.
* [ ] The product outcome is proven end to end: changing sector theme changes the selected audio route in AI Rogue while old depth/victory/defeat paths still recover safely.

### Testing Requirements

* [ ] Focused audio engine tests written and passing.
* [ ] Focused renderer audio adapter tests written and passing.
* [ ] Focused theme mapping tests written and passing.
* [ ] TypeScript validation passes.
* [ ] Asset-size validation passes with no new final theme assets committed.

### Non-Functional Requirements

* [ ] No dependency, lockfile, DB, migration, or persisted browser-state schema change is introduced.
* [ ] No remote game-content loading, hosted write, collector, analytics, public-demo bridge call, or new third-party runtime dependency is added.
* [ ] Documentation describes the implemented routing contract separately from the future Session 05 ambience assets.
* [ ] Audio selection remains presentation-only and does not affect simulation decisions, RNG consumption, replay behavior, save contracts, or gameplay balance.

### Quality Gates

* [ ] All touched text 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

* Theme audio should use five subtle ambience beds on a second ambience lane, not five replacement music loops. Evidence: the Session 04 stub names five subtle ambience beds as the default working assumption; the current runtime already has depth/title/victory/defeat music; `docs/media-policy.md` gives AI Rogue music loops a reviewed 900 KB cap. Planning can proceed because this choice preserves current music behavior and gives Session 05 a concrete asset target.
* Theme ambience assets should live under `src/assets/ai-rogue/audio/music/`. Evidence: ambience beds are looped in-game audio; the existing size-check script already grants AI Rogue music tracks the reviewed 900 KB cap by path; the stub requires a media-size decision before assets are generated. Planning can proceed because no final theme assets are committed in this session.

### Conflict Resolutions

* Current code maps music by depth while Phase 36 asks for theme-aware audio keyed by `snapshot.theme`. Chosen interpretation: keep depth music as the primary music lane and add a parallel theme ambience route. This wins because it satisfies `snapshot.theme` routing without breaking title, depth, victory, defeat, mute, volume, unlock, heartbeat, or silent fallback behavior.

### Key Considerations

* Session 04 must not generate or commit the final five theme files.
* Session 05 needs concrete basenames, asset location, bus behavior, and size policy so it can generate assets without reopening engine decisions.
* No debug UI is required; verification belongs in tests and implementation notes.

### Potential Challenges

* Missing ambience assets during Session 04: Keep URL lookup optional and no-op safe so tests can prove route selection without committed files.
* Stale ambience after reset or load: Stop ambience in reset/load paths and start it again from the current snapshot theme only when a run starts.
* Terminal music overlap: Stop the ambience lane before victory or defeat music starts.

### Relevant Considerations

* \[P31-P35] **Public-demo and AI Rogue gates stay bundled**: Preserve asset size, no-remote-loading, no-bridge, privacy, Pages, route smoke, and playthrough expectations after runtime audio changes.
* \[P34-P35] **AI Rogue is production default-enabled**: Keep production default visibility intact and do not introduce new capability gates.
* \[P30/P32/P34-P35] **Route-lazy runtime ownership scales**: Keep audio runtime changes behind the AI Rogue runtime boundary and avoid product-route debug surfaces.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Scoped Web Audio resources can leak if ambience handles survive reset, load, dispose, or decode-after-stop paths.
* Missing future ambience assets can accidentally become runtime errors unless URL, fetch, and decode failures stay silent-safe.
* Theme selection can drift from `AiRogueSectorThemeId` unless the mapping is exhaustive and tested.

***

## 9. Testing Strategy

### Unit Tests

* `audio.test.ts`: ambience pending unlock, start, duplicate start no-op, stop, dispose, mute/music-volume gain application, missing URL fallback, and decode-after-stop cleanup.
* `renderer-audio-adapter.test.ts`: start/descend theme changes, unchanged theme no-op, victory/defeat ambience stop, and unchanged depth music.
* `themes.test.ts`: every sector theme resolves to one stable ambience ID.

### Integration Tests

* Focused TypeScript validation for the expanded audio engine contract.
* Existing AI Rogue runtime tests that cover renderer lifecycle and audio-safe mount behavior.

### Runtime Verification

* Use existing AI Rogue browser route evidence or a focused Playwright path to confirm start and descend still run without product-surface diagnostics, horizontal overflow, bridge calls, or console errors.

### Edge Cases

* Web Audio unavailable.
* AudioContext construction failure.
* Missing ambience URL before Session 05 assets exist.
* Fetch or decode failure.
* Reset or load while ambience is pending decode.
* Victory or defeat reached while ambience is active.
* Muted audio with nonzero stored music and SFX volume.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase36-session01-current-audio-balance-audit`, `phase36-session02-enemy-audio-metadata`, `phase36-session03-enemy-and-boss-sfx-pack`
* Depended by: `phase36-session05-sector-theme-audio-pack`, `phase36-session06-adaptive-music-engine-expansion`, `phase36-session08-final-audio-validation-and-docs`

***

## 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/phase36-session04-theme-audio-routing-contract/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.
