> 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/phase39-session06-boss-and-finale-contracts/spec.md).

# Session Specification

**Session ID**: `phase39-session06-boss-and-finale-contracts` **Phase**: 39 - AI Rogue Level Authoring Infrastructure **Status**: Not Started **Created**: 2026-06-30

***

## 1. Session Overview

This session generalizes the current Kernel Sentinel-only boss handling into a reusable boss and finale contract. It keeps Kernel Sentinel as the only shipped boss, but moves its rendering frames, audio identity, reveal behavior, telegraph behavior, shutdown behavior, sprite scale, and finale ownership into data-backed helpers instead of scattered literal checks.

This work is next because Phase 39 Sessions 02, 03, and 05 are complete: depth helpers now route through level specs, the registry has validation and save parity gates, and Kernel Sentinel frame metadata already exists on the enemy template. Session 06 uses that foundation to make future boss or miniboss content require catalog/spec additions and focused tests instead of renderer, audio, combat, and presentation archaeology.

The implementation must preserve current Kernel Sentinel gameplay, footprint, pathing, win conditions, and visual behavior. It also moves final-defense display routing away from raw `depth >= 3` checks so the authored finale spec, not a historical depth comparison, owns finale presentation.

***

## 2. Objectives

1. Introduce `AiRogueBossSpec` and helpers that identify boss enemy kinds and project Kernel Sentinel as the first boss spec.
2. Replace Kernel Sentinel literal checks in boss presentation, render model, renderer audio, effects, and combat with boss-spec helpers while preserving current behavior.
3. Route final-defense presentation through authored finale metadata instead of raw depth thresholds.
4. Update focused tests so Kernel Sentinel behavior remains unchanged and a second boss would be added through specs plus tests, not runtime branches.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase39-session02-depth-resolver-migration` - depth helpers route through authored level specs.
* [x] `phase39-session03-registry-validation-and-save-parity` - malformed specs and saved ID drift fail fast.
* [x] `phase39-session05-enemy-metadata-and-derived-asset-checks` - enemy audio and Kernel Sentinel frame metadata are available.

### Required Tools Or Knowledge

* Bun 1.3.14 from `.bun-version`.
* Vitest focused runtime suites under `src/extensions/ai-rogue/runtime/__tests__/`.
* AI Rogue content registry and validation helpers under `src/extensions/ai-rogue/runtime/content/`.

### Environment Requirements

* Repo-local install from `bun install` is available.
* No new third-party services, credentials, remote content loading, collectors, analytics, hosted writes, or public demo bridge calls are required.

***

## 4. Scope

### In Scope (MVP)

* AI Rogue can identify boss enemy kinds through `bossSpecForEnemyKind()` or `isBossEnemyKind()` - implemented as a typed local runtime contract.
* AI Rogue can select Kernel Sentinel boss frames through boss metadata - presentation behavior remains identical to the existing Kernel Sentinel path.
* AI Rogue render, effects, audio adapter, and combat code can consume boss helpers - literal `kernel-sentinel` branching is removed from those runtime paths where boss identity is the only reason for the branch.
* AI Rogue final-defense markers can be gated by authored finale metadata - `levelSpec.finale.isFinalAuthoredLevel` or a finale presentation spec replaces raw `depth >= 3` display ownership.
* AI Rogue focused tests cover boss contract lookup, Kernel Sentinel frame parity, final-defense finale gating, audio requests, combat metadata, and content validation.

### Out Of Scope (Deferred)

* Adding a second boss or miniboss - Reason: this session proves the generalized Kernel Sentinel path first.
* Changing Kernel Sentinel gameplay logic, health, attack, footprint, pathing, or win conditions - Reason: Phase 39 requires behavior preservation.
* Changing save schema or persisted run shape - Reason: boss/finale metadata is derived from runtime catalogs and level specs, not stored wholesale.
* Adding remote content loading, mod systems, telemetry, collectors, analytics, or hosted writes - Reason: AI Rogue remains browser-local and static-demo safe.
* Adding new route-visible UI copy or debug surfaces - Reason: this is runtime contract work; diagnostics belong in tests and notes.

***

## 5. Technical Approach

### Architecture

Create a narrow boss contract owner in `src/extensions/ai-rogue/runtime/boss-contracts.ts`. The module should compose existing enemy template facts, Kernel Sentinel `bossFrameSet`, audio family, sprite scale, and authored finale metadata into typed helpers. The contract should expose a finite boss kind set, `AiRogueBossSpec`, `bossSpecForEnemyKind()`, `isBossEnemyKind()`, and finale presentation helpers that can be consumed by presentation, rendering, effects, audio, combat, and validation modules.

Keep `boss-presentation.ts` responsible for selecting display frames from combat log, status, and pending-threat facts, but make it consume a boss spec instead of checking one literal kind. Use the existing `levelSpecForDepth()` and `authoredLevelSpecForDepth()` boundary for final-defense presentation, with safe fallback behavior for malformed or out-of-range depths.

### Design Patterns

* Catalog-owned contracts: Boss identity and required frames come from typed metadata instead of scattered runtime branches.
* Behavior-preserving refactor: Tests should assert the exact current Kernel Sentinel outputs before and after the helper migration.
* Boundary helpers over broad rewrites: Existing runtime owners stay in place, with only boss/finale identity decisions delegated to the new contract module.
* Registry-backed finale ownership: The content registry owns whether a level is the final authored level; display code only projects that decision.

***

## 6. Deliverables

### Files To Create

| File                                                | Purpose                                                                           | Est. Lines |
| --------------------------------------------------- | --------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/runtime/boss-contracts.ts` | Typed boss and finale contract helpers for Kernel Sentinel and future boss specs. | \~160      |

### Files To Modify

| File                                                                       | Changes                                                                                                         | Est. Lines |
| -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/runtime/boss-presentation.ts`                     | Replace Kernel Sentinel-specific helper internals with boss-spec-based frame and finale presentation selection. | \~140      |
| `src/extensions/ai-rogue/runtime/render-model.ts`                          | Use boss helpers for boss entity frames and finale marker projection.                                           | \~40       |
| `src/extensions/ai-rogue/runtime/render-hud.ts`                            | Use finale metadata for final-defense HUD state.                                                                | \~30       |
| `src/extensions/ai-rogue/runtime/renderer-audio-adapter.ts`                | Detect visible boss reveal through boss helpers.                                                                | \~20       |
| `src/extensions/ai-rogue/runtime/effects.ts`                               | Detect boss actor and target events through boss helpers.                                                       | \~25       |
| `src/extensions/ai-rogue/runtime/combat.ts`                                | Derive boss audio actor and boss attack cues through boss helpers.                                              | \~35       |
| `src/extensions/ai-rogue/runtime/content/types.ts`                         | Use the boss contract for finale boss kind typing where practical.                                              | \~15       |
| `src/extensions/ai-rogue/runtime/content/validate.ts`                      | Validate finale boss references against boss specs instead of a local literal set.                              | \~30       |
| `src/extensions/ai-rogue/runtime/content/index.ts`                         | Export boss/finale helpers only if needed by existing local patterns.                                           | \~5        |
| `src/extensions/ai-rogue/runtime/__tests__/boss-presentation.test.ts`      | Cover boss contract lookup, generic frame selection, and finale display gating.                                 | \~120      |
| `src/extensions/ai-rogue/runtime/__tests__/render-model.test.ts`           | Assert boss-spec frame parity and final-defense projection behavior.                                            | \~70       |
| `src/extensions/ai-rogue/runtime/__tests__/renderer-audio-adapter.test.ts` | Assert visible boss reveal continues through boss helpers.                                                      | \~30       |
| `src/extensions/ai-rogue/runtime/__tests__/combat.test.ts`                 | Assert boss combat metadata and cue parity without literal-specific branch behavior.                            | \~35       |
| `src/extensions/ai-rogue/runtime/__tests__/audio.test.ts`                  | Assert boss audio family cue parity still maps to existing SFX.                                                 | \~25       |
| `src/extensions/ai-rogue/runtime/content/__tests__/levels.test.ts`         | Assert finale boss validation uses the boss contract and rejects unknown boss references.                       | \~60       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Kernel Sentinel frame selection returns the same idle, charge, telegraph, attack, shielded, hit, and shutdown frames as before.
* [ ] Boss reveal audio, boss hit/fire/shutdown cues, and combat metadata remain unchanged for Kernel Sentinel.
* [ ] Final-defense presentation is shown because the authored level finale says it is final, not because `depth >= 3`.
* [ ] A future boss can be added by creating a boss spec, frames, audio mapping, and tests without adding new render/audio/combat literal branches.

### Testing Requirements

* [ ] Focused Vitest boss, render, audio adapter, audio, combat, content registry, and finale tests are written and passing.
* [ ] `bun run typecheck` passes.
* [ ] Runtime route smoke is run when implementation changes observable play-route rendering beyond model projection.

### Non-Functional Requirements

* [ ] No new remote loading, hosted writes, collectors, telemetry, analytics, or persisted whole-level specs are introduced.
* [ ] AI Rogue browser-local state and public-demo safety boundaries remain unchanged.
* [ ] Product-facing render and HUD labels remain free of debug, telemetry, frame, seed, path, or secret-shaped text.

### 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

* Kernel Sentinel remains the only boss in this session: Phase 39 Session 06 explicitly excludes adding a second boss, while `src/extensions/ai-rogue/runtime/entities.ts` already has one `bossFrameSet` on `kernel-sentinel`. Planning can proceed because the goal is to prove the reusable path with the existing boss.
* `src/extensions/ai-rogue/runtime/boss-contracts.ts` is the best local owner for boss contracts: existing `entities.ts` owns raw enemy templates and `boss-presentation.ts` owns frame selection. A separate helper keeps identity and finale ownership reusable without turning either existing file into a cross-module catchall.
* Browser proof is not a first-order deliverable unless implementation changes observable route rendering beyond the render model: this session mostly changes data routing and tests around existing sprites. If `implement` changes play-route rendering behavior, run the existing AI Rogue runtime Playwright smoke.

### Conflict Resolutions

* Historical final-defense display used `snapshot.depth >= 3`, but Phase 39 now has a fourth authored floor and `level.finale.isFinalAuthoredLevel` in `src/extensions/ai-rogue/runtime/content/levels.ts`. The registry-backed interpretation wins because the PRD says level authoring and finale ownership must be metadata-backed, and the current content registry marks depth 4 as final.

### Key Considerations

* Preserve Session 05 metadata ownership: `bossFrameSetForEnemyKind()` already reads Kernel Sentinel boss frames from the enemy template.
* Keep save-schema behavior unchanged: no whole level specs, boss specs, or presentation specs should be persisted into browser storage.
* Keep diagnostics in tests and implementation notes, not route-visible UI.

### Potential Challenges

* Circular imports between content validation and boss contracts: Keep shared types in low-level modules or use type-only imports so runtime cycles do not appear.
* Behavior drift in boss frame priority: Preserve the current order of shutdown, hit, shielded, attack, pending telegraph, charge, idle.
* Finale fallback for invalid depths: Use existing level lookup helpers and keep non-throwing display behavior for snapshots that may be synthetic in tests.

### Relevant Considerations

* \[P30/P32/P34-P38] **Route-lazy runtime ownership scales**: Keep Pixi and route behavior behind the current runtime owners; this session should not widen route boundaries.
* \[P30/P34-P38] **Visibility gates catch real issues**: Pair focused unit tests, typecheck, and route smoke only when rendering behavior changes.
* \[P30/P32/P34-P38] **Do not widen AI Rogue capabilities without review**: No collectors, workers, remote loading, hosted writes, saved audio state, analytics, or rejected-art reuse.
* \[P31-P38] **Pages demo stays static-only**: Do not add bridge calls or hosted runtime behavior while touching AI Rogue runtime code.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Boss contract consumers must match declared types and handle future enum growth exhaustively.
* Render and HUD paths must keep product-facing labels only, with diagnostics confined to tests and notes.
* Event handlers reading combat metadata must handle missing or unknown boss metadata without throwing or misrouting audio.

***

## 9. Testing Strategy

### Unit Tests

* `src/extensions/ai-rogue/runtime/__tests__/boss-presentation.test.ts` for boss spec lookup, frame selection priority, unknown-kind fallback, and finale display gating.
* `src/extensions/ai-rogue/runtime/__tests__/render-model.test.ts` for boss frame parity and final-defense sprite projection.
* `src/extensions/ai-rogue/runtime/__tests__/renderer-audio-adapter.test.ts` for visible boss reveal transition.
* `src/extensions/ai-rogue/runtime/__tests__/combat.test.ts` and `src/extensions/ai-rogue/runtime/__tests__/audio.test.ts` for boss cue and metadata parity.
* `src/extensions/ai-rogue/runtime/content/__tests__/levels.test.ts` for finale boss reference validation.

### Integration Tests

* Focused command:

```bash
bunx vitest run src/extensions/ai-rogue/runtime/__tests__/boss-presentation.test.ts src/extensions/ai-rogue/runtime/__tests__/render-model.test.ts src/extensions/ai-rogue/runtime/__tests__/renderer-audio-adapter.test.ts src/extensions/ai-rogue/runtime/__tests__/audio.test.ts src/extensions/ai-rogue/runtime/__tests__/combat.test.ts src/extensions/ai-rogue/runtime/content/__tests__/levels.test.ts
```

### Runtime Verification

* Run `bun run typecheck`.
* Run `bunx playwright test tests/e2e/ai-rogue-runtime.spec.ts` if implementation changes observable play-route rendering.

### Edge Cases

* Non-boss enemies return null or false from boss helpers.
* Unknown or malformed finale boss references fail validation with a precise issue.
* Depth 3 objective state does not show final-defense markers solely because depth is 3.
* Depth 4 authored finale still shows final-defense markers and win unlock behavior as before.
* Kernel Sentinel defeat, shield, attack, and telegraph events keep existing frame priority.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase39-session02-depth-resolver-migration`, `phase39-session03-registry-validation-and-save-parity`, `phase39-session05-enemy-metadata-and-derived-asset-checks`
* Depended by: `phase39-session07-real-content-expansion-path`, `phase39-session08-validation-and-documentation-hardening`

***

## 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/phase39-session06-boss-and-finale-contracts/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.
