> For the complete documentation index, see [llms.txt](https://faction-os.gitbook.io/faction-os-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://faction-os.gitbook.io/faction-os-docs/.spec_system/specs/phase24-session06-world-cues-and-bark-reuse/spec.md).

# Session Specification

**Session ID**: `phase24-session06-world-cues-and-bark-reuse` **Phase**: 24 - Legion II - Live Tier And Combat Playback **Status**: Not Started **Created**: 2026-07-08 **Base Commit**: 971f022685f53643def9d1ba5cfb59e9e8367fa2 **Package**: apps/web **Package Stack**: TypeScript

***

## 1. Session Overview

This session adds the Phase 24 audio layer that makes live combat moments audible without changing the existing audio opt-in posture. It extends the existing bark and SFX runtime with six faction-agnostic world cues, routes them through the same file-first and synth-fallback boundary, and applies the Session 01 per-category rate limiter so long missions silence repeated cues while visuals continue.

The session is next because Session 04 created linked combat playback effects and Session 05 created the projection-owned alert-focus surface. Those completed surfaces expose the real moments needed for camp hits, camp collapse, ram crash, ram break, skirmisher spawn, flare attention, and hero-actor bark reuse.

The work stays in `apps/web`. It does not add audio files, protocol events, server routes, storage keys, rewards, hosted dependencies, or trusted-erasure claims.

***

## 2. Objectives

1. Add a typed world-cue manifest and synth fallback path for the six Phase 24 world cues.
2. Derive cue candidates only from real linked combat, live enemy, build, and alert-focus moments.
3. Reuse existing hero bark runtime semantics for wraith spawn, verified camp kill, and linked mission completion moments.
4. Prove opt-in, rate-limit, replay, unlinked, cleanup, and privacy behavior with focused tests.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase24-session01-pure-strike-and-combo-model` - Provides `shouldPlayCue`, strike categories, combo windows, and fatigue limits.
* [x] `phase24-session04-combat-playback-effects-layer` - Provides linked strike and verified kill presentation evidence.
* [x] `phase24-session05-scrying-and-alert-focus` - Provides one projection-owned alert-focus target for flare cue routing.

### Required Tools Or Knowledge

* `npm --workspace apps/web run typecheck`
* `npm test -- --run apps/web/tests/audioRuntime.test.ts apps/web/tests/fileVoiceSynth.test.ts apps/web/tests/worldCues.test.ts apps/web/tests/useWorldCues.test.tsx apps/web/tests/Battlefield.test.tsx`
* Existing audio runtime files: `sfxAssets.ts`, `voiceSynth.ts`, `fileVoiceSynth.ts`, `audioRuntime.ts`, `useAudioRuntimeStore.ts`, `useVoiceBarks.ts`, and `useFactionVoiceLine.ts`

### Environment Requirements

* Node 26.2.0+ and npm 11.16.0 per `.spec_system/CONVENTIONS.md`.
* Browser audio remains disabled by default until the persisted `audioEnabled` setting and a user gesture allow playback.

***

## 4. Scope

### In Scope (MVP)

* A web operator can hear six faction-agnostic world cue types only after audio is enabled - Extend the SFX manifest and runtime with typed world cue support.
* A web operator can hear real combat cue moments without repeated fatigue - Derive camp-hit, camp-collapse, ram-crash, ram-break-triumph, skirmisher red-slash, and flare attention cues from existing real event and presentation anchors with per-category rate limiting.
* A web operator can hear hero-actor moments through existing bark semantics - Reuse faction bark cues for error, celebration, and complete moments without overlapping or bypassing opt-in state.
* A long-running mission keeps visuals authoritative even when audio is silenced - Rate-limit decisions suppress only audio playback, not the visual presentation already produced by Session 04 and Session 05.
* Tests prove no autoplay, no replay/unlinked implication, and no sensitive label leakage - Add focused pure, hook, runtime, adapter, and integration coverage.

### Out Of Scope (Deferred)

* Recorded world audio files - Reason: Phase 24 explicitly routes these cues through the synth fallback until recorded files exist.
* Dynamic music layering - Reason: Later audio phases own music stems and dynamic mix behavior.
* Audio settings, volume, and permission redesign - Reason: Existing opt-in posture must remain unchanged.
* Replay, mock, persistence, and erasure closeout matrix - Reason: Session 07 owns the broad honesty and persistence boundary pass.
* Generated visual asset implementation - Reason: Session 08 owns generated Phase 3 visual sheet references and promotion.

***

## 5. Technical Approach

### Architecture

Add typed world cue support beside the existing bark runtime. `sfxAssets.ts` should keep current faction bark lookups intact while adding a `world` bucket and `WorldCueKind` lookup helper. `voiceSynth.ts` should add deterministic synth recipes for world cues, and `fileVoiceSynth.ts` should try `SFX_FILES.world` first before falling back to synth world playback. `audioRuntime.ts` and `useAudioRuntimeStore.ts` should expose a world-cue request path with the same opt-in, status, muted, playback-denied, failed, redaction, and duplicate in-flight semantics as existing bark cues.

Create `apps/web/src/lib/worldCues.ts` as the pure derivation boundary. It should map existing evidence into cue candidates, thread per-category histories through `shouldPlayCue`, and reject unlinked, replayed, future, duplicate, or unsupported cue moments. `apps/web/src/store/useWorldCues.ts` should own React refs for seen cue keys and histories, call the audio runtime only after audio is enabled, and clear cue scopes on unmount.

Wire `useWorldCues` from `Battlefield.tsx`, passing the already-derived `combatPlayback`, `liveLegion`, `scryingAndAlertFocus`, `eventLog`, `gameProjection`, visible heroes, missions, and audio settings. This keeps audio orchestration presentation-owned and transient, with no projection write path and no diagnostics surface in the user-facing UI.

### Design Patterns

* Pure helper before React hook: Keeps cue selection, rate limiting, replay filtering, and label bounds testable without DOM or Web Audio.
* Existing runtime boundary reuse: Preserves audio opt-in, visible-equivalent status, duplicate guards, and redacted failure details.
* Presentation-only battlefield integration: Reads existing selectors and presentations without writing projection state or creating a second game authority.
* Category history refs: Keeps 45-minute mission rate state bounded in memory and avoids new persisted counters.

***

## 6. Deliverables

### Files To Create

| File                                   | Purpose                                                                                                            | Est. Lines |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ---------- |
| `apps/web/src/lib/worldCues.ts`        | Pure world-cue and hero-bark candidate derivation, rate-limit decisions, event keying, and replay/unlinked filters | \~320      |
| `apps/web/src/store/useWorldCues.ts`   | React hook that owns cue histories, seen keys, opt-in checks, runtime calls, and cleanup                           | \~230      |
| `apps/web/tests/worldCues.test.ts`     | Pure coverage for cue selection, category limits, no replay/unlinked cues, and safe labels                         | \~360      |
| `apps/web/tests/useWorldCues.test.tsx` | Hook coverage for audio calls, disabled audio, duplicate prevention, cleanup, and bark reuse                       | \~280      |

### Files To Modify

| File                                                  | Changes                                                                                            | Est. Lines |
| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ---------- |
| `apps/web/src/lib/sfxAssets.ts`                       | Add `WorldCueKind`, `SFX_FILES.world`, and `pickWorldSfxUrl` while preserving faction bark lookups | \~90       |
| `apps/web/src/lib/voiceSynth.ts`                      | Add world cue synth recipes and `playWorldCue` fallback support                                    | \~120      |
| `apps/web/src/lib/fileVoiceSynth.ts`                  | Extend adapter contract to resolve world cue files before synth fallback                           | \~80       |
| `apps/web/src/lib/audioRuntime.ts`                    | Add world-cue request validation, playback mapping, status handling, and redaction                 | \~140      |
| `apps/web/src/store/useAudioRuntimeStore.ts`          | Expose `playWorldCue` and world cue cleanup through the existing cue guard                         | \~80       |
| `apps/web/src/store/useVoiceBarks.ts`                 | Extract or export shared hero-bark request construction for non-state-transition actor moments     | \~50       |
| `apps/web/src/components/battlefield/Battlefield.tsx` | Wire `useWorldCues` to existing combat, live enemy, focus, event, hero, mission, and audio inputs  | \~60       |
| `apps/web/tests/audioRuntime.test.ts`                 | Add world-cue validation, muted, playing, and redacted failure coverage                            | \~90       |
| `apps/web/tests/fileVoiceSynth.test.ts`               | Add world manifest fallback and file-first routing coverage                                        | \~80       |
| `apps/web/tests/Battlefield.test.tsx`                 | Add integration coverage for real event cue routing without changing visual output                 | \~90       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] All six world cue kinds have typed manifest entries and synth fallback recipes.
* [ ] Camp-hit, camp-collapse, ram-crash, ram-break-triumph, skirmisher red-slash, and flare attention cues derive from real existing moments.
* [ ] Hero actor barks fire for wraith spawn, verified camp kill, and linked mission completion using existing opt-in and runtime semantics.
* [ ] Rate limits silence repeated audio cues per category while visuals continue unchanged.
* [ ] Audio remains silent when disabled, muted, unsupported, replayed, unlinked, or duplicated in-flight.

### Testing Requirements

* [ ] Unit tests written and passing for pure cue derivation and rate limiting.
* [ ] Hook tests written and passing for runtime calls, cleanup, duplicate-trigger prevention, and disabled audio.
* [ ] Runtime and adapter tests updated for world cue validation and fallback behavior.
* [ ] Battlefield integration tests cover event-to-cue routing without adding debug UI.

### Non-Functional Requirements

* [ ] No new protocol event, server route, storage key, hosted dependency, recorded audio asset, reward system, or trusted-erasure claim.
* [ ] Audio failure details remain redacted and product-facing.
* [ ] Cue labels stay bounded and do not include raw prompts, command output, file contents, broad absolute paths, provider payloads, or secrets.

### Quality Gates

* [ ] All files ASCII-encoded
* [ ] Unix LF line endings
* [ ] Code follows project conventions
* [ ] `npm --workspace apps/web run typecheck` passes
* [ ] Focused audio, cue, hook, and battlefield tests pass

***

## 8. Implementation Notes

### Working Assumptions

* Session package is `apps/web`: The analyzer candidate, Phase 24 PRD, and session stub all name `apps/web`, and every required code anchor is in the web package.
* World cues should add no recorded files in this session: The session stub and Phase 24 PRD say recorded audio files are out of scope and all six cues should use synth fallback until recorded files exist.
* Build-fix cue routing must read `eventLog`: `build_fix` clears the ram in `gameProjection.ts`, so the ram-break-triumph cue should key off the real `build_fix` event rather than the post-clear live-legion presentation.
* Rate limiting should use `combatPlayback.ts`: Session 01 shipped `shouldPlayCue` as the pure per-category limiter; `audioRuntime.ts` currently owns duplicate in-flight guarding and opt-in status rather than category budgets.

### Conflict Resolutions

* `docs/game-design/15-phases-yet-to-be-implemented.md` says Phase 24 was only complete through Session 03 and still names Session 04 as current, while the analyzer, current Phase 24 PRD, and live Session 04/05 implementation summaries show Session 05 complete. The analyzer output and live spec artifacts are the workflow authority, so Session 06 is the next executable session.
* The Phase 24 PRD summary describes rate limiting as available in `audioRuntime.ts`, while the implemented rate-limit helper is in `combatPlayback.ts`. The plan uses `shouldPlayCue` for category budgets and keeps `audioRuntime.ts` responsible for playback state and duplicate cue IDs.

### Key Considerations

* Audio must never become the source of truth; visual state remains authoritative when audio is muted, denied by browser policy, or rate-limited.
* The hook should not create in-app explanatory or diagnostic copy. Existing audio runtime result state and tests are enough.
* Cue keys should be stable and sanitized. Raw mission ids, event ids, or tool identifiers must not become visible labels.

### Potential Challenges

* World cue support touches several audio modules: Keep bark APIs backward compatible and add focused adapter/runtime tests before wiring Battlefield.
* Duplicate cue bursts can happen on re-render: Use seen-key refs plus the existing cue guard and clear prefixes on unmount.
* Mission completion bark needs linked mission context: Derive only when the mission id is present in `campLinks` or a retained link snapshot; otherwise no cue fires.
* Replay or mock signals can look like real events: Pure derivation should accept an explicit replay flag and skip cue candidates when replaying.

### Relevant Considerations

* \[P23-apps/web] **Scanner camps are projection-owned**: Cue routing reads projection and presentation evidence without adding another game state authority.
* \[P22-apps/web] **Do not persist replay or drill progress**: Audio cue histories remain transient refs and do not create persisted counters.
* \[P23-apps/web] **Do not turn scanner camps into combat rewards**: Verified kill audio does not add XP, loot, banners, achievements, or new durable progress.
* \[P07] **Redaction is boundary-specific**: Cue labels, runtime results, tests, and adapter details must not expose raw prompts, output, file contents, provider payloads, secrets, or broad absolute paths.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Audio playback can fire repeatedly on render instead of on new evidence.
* Disabled or locked audio can silently fail without visible-equivalent runtime state.
* Cue labels can leak sensitive event details if raw source fields are reused.

***

## 9. Testing Strategy

### Unit Tests

* `apps/web/tests/worldCues.test.ts`: Six cue kinds, category histories, no replay, no unlinked combat cues, linked mission completion bark, and bounded labels.
* `apps/web/tests/audioRuntime.test.ts`: World-cue request schema, disabled audio, unsupported state, playing state, duplicate IDs, and redacted unknown failure details.
* `apps/web/tests/fileVoiceSynth.test.ts`: World cue file-first lookup, synth fallback when no world file exists, and unchanged faction bark behavior.

### Integration Tests

* `apps/web/tests/useWorldCues.test.tsx`: Hook calls `playWorldCue` and hero bark requests once per new evidence key, skips disabled audio, suppresses repeated categories after the limit, and clears cue prefixes on unmount.
* `apps/web/tests/Battlefield.test.tsx`: Real `tool_use`, `task_verification`, `build_error`, `build_fix`, `test_failure`, and flare focus inputs route to cue candidates through Battlefield without adding a visible debug surface.

### Runtime Verification

* Run `npm test -- --run apps/web/tests/audioRuntime.test.ts apps/web/tests/fileVoiceSynth.test.ts apps/web/tests/worldCues.test.ts apps/web/tests/useWorldCues.test.tsx apps/web/tests/Battlefield.test.tsx`.
* Run `npm --workspace apps/web run typecheck`.

### Edge Cases

* Audio disabled or volume zero produces no autoplay.
* Unsupported or browser-denied audio returns redacted runtime status.
* A 45-minute simulated stream cannot exceed the per-category cue budget.
* Replayed, unlinked, future-dated, and duplicate cues do not imply progress.
* Visual combat and focus layers still render when audio is silenced.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase24-session01-pure-strike-and-combo-model`, `phase24-session04-combat-playback-effects-layer`, `phase24-session05-scrying-and-alert-focus`
* Depended by: `phase24-session07-honesty-and-persistence-boundaries`, `phase24-session09-validation-and-documentation`

***

## 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://faction-os.gitbook.io/faction-os-docs/.spec_system/specs/phase24-session06-world-cues-and-bark-reuse/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.
