[PR #5162] [MERGED] feat(music): context-bound game music — persistent per-area and per-tier tracks (#5161) #6653

Closed
opened 2026-10-23 04:12:27 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/5162
Author: @kolacheee
Created: 8/16/2026
Status: ✅ Merged
Merged: 8/16/2026
Merged by: @kolacheee

Base: staging ← Head: feat/5161-context-music


📝 Commits (6)

  • 23fa0c8 feat(music): context-track foundations — scoreable area/tier tags, encounter tiers, keyed generation (#5161)
  • 2cf4259 feat(music): client wiring, analyzer retirement, scoring context + Spotify search pagination
  • 4f21da6 fix(music): complete the free-text retirement in postprocess; update pinned regressions
  • 2468392 fix(music): linear-scan slug trimming — CodeQL polynomial-regex alert
  • 07105d5 fix(music): review round — path-independent area fill, audible tier tracks, stable legacy pool
  • 7e5deb5 fix(music): CodeRabbit round — scoped tier continuation, context-required music, Spotify partials

📊 Changes

15 files changed (+713 additions, -80 deletions)

View changed files

📝 CHANGELOG.md (+3 -0)
📝 packages/client/src/components/game/GameSurface.tsx (+251 -15)
📝 packages/server/src/routes/encounter.routes.ts (+2 -1)
📝 packages/server/src/routes/game.routes.ts (+7 -1)
📝 packages/server/src/routes/sidecar.routes.ts (+7 -1)
📝 packages/server/src/routes/tts.routes.ts (+90 -10)
📝 packages/server/src/services/sidecar/scene-analyzer.ts (+8 -21)
📝 packages/server/src/services/sidecar/scene-postprocess.ts (+10 -5)
📝 packages/server/src/services/spotify/game-spotify-music.service.ts (+41 -14)
📝 packages/shared/src/schemas/scene-analysis.schema.ts (+2 -0)
📝 packages/shared/src/types/combat-encounter.ts (+7 -0)
📝 packages/shared/src/types/game.ts (+3 -0)
📝 packages/shared/src/utils/music-score.ts (+142 -6)
➕ scripts/regressions/context-music-score.regression.ts (+127 -0)
📝 scripts/regressions/open-issues.regression.ts (+13 -6)

📄 Description

Linked issue

Closes #5161

Why this change

With Game music enabled, every scene transition writes a fresh free-text mood prompt and generates a brand-new 30-second clip — music lurches every turn or two, 30-second loops repeat, and each rephrased mood sentence is a billed generation. #5161's model instead: persistent, context-bound tracks — one per map area and per encounter tier plus the bundled library as the floor — generated once into the game-assets music library and selected during play, so music changes when context changes, never per turn.

What changed

Shipped so far (server + shared foundations):

  • music-score.ts: a second, scoreable tag grammar for context tracks — music:area:<slug>:<name> and music:tier:<tier>:<name> — parsed separately from the state library. scoreMusic takes locationSlug/enemyTier context with precedence: tier track during combat → area track elsewhere → the existing state/genre/intensity scoring. Context selection deliberately keeps the current track while it still fits (the legacy pool's rotation contract is unchanged). New MUSIC_ENEMY_TIERS taxonomy (common | miniboss | boss | special) with alias normalization.
  • combat-encounter.ts + encounter init prompt: visuals.encounterTier classifies the whole encounter; isBossFight remains the fallback signal.
  • /api/tts/game-audio: optional context {axis, key, lengthMs} (music only, tier keys validated). Context compositions land in the scoreable library at music/<axis>/<key>/ and generate once per key — any existing audio file under the key (including a user-dropped replacement) counts as covered — at a default 120 s length (clamped 10–300 s) with provider-timeout headroom. Generation locks collapse per key, so two turns racing into the same area produce one composition. Users can audition/rename/replace these tracks in the existing Game Assets panel with zero UI changes, since tags mirror folders.

Client wiring (complete):

  • GameSurface: combatMusicTier from the /encounter/init blueprint (encounterTier, falling back from isBossFight), cleared with combat state; all three scene-analysis contexts carry enemyTier; the client inline scoring passes locationSlug + enemyTier; ensureContextMusicTrack lazily fills the library (area on scene processing, tier at combat init) as a pure library fill — playback stays with the scoring pass, so music never lurches mid-narration. materializeGeneratedGameAudio is SFX-only now.
  • Scene analyzer: free-text music prompts retired — genre/intensity hints always emitted; SFX prompt generation unchanged. Both server scoring sites always score (Spotify aside) with locationSlug derived from currentLocation and the request's enemyTier.
  • New regression context-music-score (area/tier precedence, keep-current stability, legacy-pool isolation, malformed-tag rejection, variant rotation, tier aliases, slug canonicalization).

Also folded in (Game-mode half of #5163): Game Mode's Spotify Music DJ artist and generic-search sources 400'd deterministically since Spotify's February 2026 GET /search cap of 10 — the candidate pool's default of 50 was passed straight through. searchSpotifyTracks now paginates in pages of 10 with offset up to the requested pool size. The Roleplay spotify_search tool half stays on #5163.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

Agent-run so far (treat as a to-do list to reconfirm): pnpm build green (shared/server/client), pnpm lint green, and the new context-music-score regression passes via node ./scripts/run-regressions.mjs --filter context-music-score. No real ElevenLabs generations have been run (mock-only policy).

Still needs a human pass with a real ElevenLabs audio connection:

  • Manually verify: enter a new area with Game music enabled → one ~2-minute area composition appears under music/area/<slug>/ in Game Assets, and the NEXT scene transition switches to it and keeps it while you stay in the area.
  • Manually verify combat: a common encounter and a boss encounter generate music/tier/common/ and music/tier/boss/ tracks — combat music applies at encounter init (legacy pool first), and the tier composition crossfades in the moment its generation completes, including mid-fight.
  • Manually verify replacement: drop your own mp3 into an area folder, delete the generated one — your track gets selected, and no regeneration happens.
  • Manually verify the Spotify artist source in Game Mode no longer 400s (needs a linked Spotify account).

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened (see CONTRIBUTING.md § Translated documentation)
  • Version/release files updated (only if this PR includes a version bump)

CHANGELOG entries added under Unreleased (feature + the #5163 Game-mode fix).

Summary by CodeRabbit

  • New Features

    • Added persistent, context-aware music for locations and combat encounter tiers.
    • Music now selects deterministic area, miniboss, boss, and story themes with appropriate fallbacks.
    • Combat music is preserved across saved and restored game states.
    • Sound effects remain available on demand while music uses genre and intensity guidance.
  • Bug Fixes

    • Improved Spotify track searches by retrieving results in batches and retaining partial results after later-page failures.
  • Tests

    • Added regression coverage for context-based music selection, fallback behavior, normalization, and audio request handling.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/5162 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/16/2026 **Status:** ✅ Merged **Merged:** 8/16/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `feat/5161-context-music` --- ### 📝 Commits (6) - [`23fa0c8`](https://github.com/Pasta-Devs/Marinara-Engine/commit/23fa0c8037aa9cefdeb7246cb22ca119fe629523) feat(music): context-track foundations — scoreable area/tier tags, encounter tiers, keyed generation (#5161) - [`2cf4259`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2cf425905b43c4c091ab29569534922397c0fb9e) feat(music): client wiring, analyzer retirement, scoring context + Spotify search pagination - [`4f21da6`](https://github.com/Pasta-Devs/Marinara-Engine/commit/4f21da6b4d4bbdec0e3d4781692dc88e4af3f2dc) fix(music): complete the free-text retirement in postprocess; update pinned regressions - [`2468392`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2468392901e3fc944def4df668e28ff98b4a04c1) fix(music): linear-scan slug trimming — CodeQL polynomial-regex alert - [`07105d5`](https://github.com/Pasta-Devs/Marinara-Engine/commit/07105d5fd8e50d5b5d8b3b2876b265c9a079658f) fix(music): review round — path-independent area fill, audible tier tracks, stable legacy pool - [`7e5deb5`](https://github.com/Pasta-Devs/Marinara-Engine/commit/7e5deb595c3df1871717076d23ecf89d8de9dbdc) fix(music): CodeRabbit round — scoped tier continuation, context-required music, Spotify partials ### 📊 Changes **15 files changed** (+713 additions, -80 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+3 -0) 📝 `packages/client/src/components/game/GameSurface.tsx` (+251 -15) 📝 `packages/server/src/routes/encounter.routes.ts` (+2 -1) 📝 `packages/server/src/routes/game.routes.ts` (+7 -1) 📝 `packages/server/src/routes/sidecar.routes.ts` (+7 -1) 📝 `packages/server/src/routes/tts.routes.ts` (+90 -10) 📝 `packages/server/src/services/sidecar/scene-analyzer.ts` (+8 -21) 📝 `packages/server/src/services/sidecar/scene-postprocess.ts` (+10 -5) 📝 `packages/server/src/services/spotify/game-spotify-music.service.ts` (+41 -14) 📝 `packages/shared/src/schemas/scene-analysis.schema.ts` (+2 -0) 📝 `packages/shared/src/types/combat-encounter.ts` (+7 -0) 📝 `packages/shared/src/types/game.ts` (+3 -0) 📝 `packages/shared/src/utils/music-score.ts` (+142 -6) ➕ `scripts/regressions/context-music-score.regression.ts` (+127 -0) 📝 `scripts/regressions/open-issues.regression.ts` (+13 -6) </details> ### 📄 Description ## Linked issue Closes #5161 ## Why this change With Game music enabled, every scene transition writes a fresh free-text mood prompt and generates a brand-new 30-second clip — music lurches every turn or two, 30-second loops repeat, and each rephrased mood sentence is a billed generation. #5161's model instead: **persistent, context-bound tracks** — one per map area and per encounter tier plus the bundled library as the floor — generated once into the game-assets music library and *selected* during play, so music changes when context changes, never per turn. ## What changed **Shipped so far (server + shared foundations):** - `music-score.ts`: a second, scoreable tag grammar for context tracks — `music:area:<slug>:<name>` and `music:tier:<tier>:<name>` — parsed separately from the state library. `scoreMusic` takes `locationSlug`/`enemyTier` context with precedence: tier track during combat → area track elsewhere → the existing state/genre/intensity scoring. Context selection deliberately **keeps the current track while it still fits** (the legacy pool's rotation contract is unchanged). New `MUSIC_ENEMY_TIERS` taxonomy (`common | miniboss | boss | special`) with alias normalization. - `combat-encounter.ts` + encounter init prompt: `visuals.encounterTier` classifies the whole encounter; `isBossFight` remains the fallback signal. - `/api/tts/game-audio`: optional `context {axis, key, lengthMs}` (music only, tier keys validated). Context compositions land in the scoreable library at `music/<axis>/<key>/` and generate **once per key** — any existing audio file under the key (including a user-dropped replacement) counts as covered — at a default 120 s length (clamped 10–300 s) with provider-timeout headroom. Generation locks collapse per key, so two turns racing into the same area produce one composition. Users can audition/rename/replace these tracks in the existing Game Assets panel with zero UI changes, since tags mirror folders. **Client wiring (complete):** - GameSurface: `combatMusicTier` from the `/encounter/init` blueprint (`encounterTier`, falling back from `isBossFight`), cleared with combat state; all three scene-analysis contexts carry `enemyTier`; the client inline scoring passes `locationSlug` + `enemyTier`; `ensureContextMusicTrack` lazily fills the library (area on scene processing, tier at combat init) as a pure library fill — playback stays with the scoring pass, so music never lurches mid-narration. `materializeGeneratedGameAudio` is SFX-only now. - Scene analyzer: free-text music prompts retired — genre/intensity hints always emitted; SFX prompt generation unchanged. Both server scoring sites always score (Spotify aside) with `locationSlug` derived from `currentLocation` and the request's `enemyTier`. - New regression `context-music-score` (area/tier precedence, keep-current stability, legacy-pool isolation, malformed-tag rejection, variant rotation, tier aliases, slug canonicalization). **Also folded in (Game-mode half of #5163):** Game Mode's Spotify Music DJ artist and generic-search sources 400'd deterministically since Spotify's February 2026 `GET /search` cap of 10 — the candidate pool's default of 50 was passed straight through. `searchSpotifyTracks` now paginates in pages of 10 with `offset` up to the requested pool size. The Roleplay `spotify_search` tool half stays on #5163. ## Validation - [x] `pnpm check` passes locally - [x] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [x] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [x] Above manual verification completed (describe below) - [x] Read and followed `CONTRIBUTING.md` ### Manual verification notes Agent-run so far (treat as a to-do list to reconfirm): `pnpm build` green (shared/server/client), `pnpm lint` green, and the new `context-music-score` regression passes via `node ./scripts/run-regressions.mjs --filter context-music-score`. No real ElevenLabs generations have been run (mock-only policy). Still needs a human pass with a real ElevenLabs audio connection: - Manually verify: enter a new area with Game music enabled → one ~2-minute area composition appears under `music/area/<slug>/` in Game Assets, and the NEXT scene transition switches to it and keeps it while you stay in the area. - Manually verify combat: a common encounter and a boss encounter generate `music/tier/common/` and `music/tier/boss/` tracks — combat music applies at encounter init (legacy pool first), and the tier composition crossfades in the moment its generation completes, including mid-fight. - Manually verify replacement: drop your own mp3 into an area folder, delete the generated one — your track gets selected, and no regeneration happens. - Manually verify the Spotify artist source in Game Mode no longer 400s (needs a linked Spotify account). ## Docs and release impact - [ ] No docs changes needed - [x] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened (see CONTRIBUTING.md § Translated documentation) - [ ] Version/release files updated (only if this PR includes a version bump) CHANGELOG entries added under Unreleased (feature + the #5163 Game-mode fix). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added persistent, context-aware music for locations and combat encounter tiers. * Music now selects deterministic area, miniboss, boss, and story themes with appropriate fallbacks. * Combat music is preserved across saved and restored game states. * Sound effects remain available on demand while music uses genre and intensity guidance. * **Bug Fixes** * Improved Spotify track searches by retrieving results in batches and retaining partial results after later-page failures. * **Tests** * Added regression coverage for context-based music selection, fallback behavior, normalization, and audio request handling. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-23 04:12:27 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#6653
No description provided.