> 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-session02-depth-resolver-migration/spec.md).

# Session Specification

**Session ID**: `phase39-session02-depth-resolver-migration` **Phase**: 39 - AI Rogue Level Authoring Infrastructure **Status**: Not Started **Created**: 2026-06-30

***

## 1. Session Overview

This session migrates AI Rogue's current depth-based runtime decisions onto the typed level registry created in Session 01. The migration keeps the existing runtime import surfaces stable while making authored depth 1-3 behavior come from `AiRogueLevelSpec` rows instead of scattered depth branches.

It is next because Session 01 validated the baseline and dead-but-tested registry, and Session 03 cannot add full registry and save-schema parity until runtime callers actually consume level specs. The work preserves shipped depth 1-3 gameplay outputs, golden determinism, browser-local save boundaries, and route-lazy renderer ownership.

The session also adds deterministic route-safety coverage around generated floors so level-spec routing cannot silently disconnect exits, misplace exit guards, or let terminal, vault, or prefab placement block the playable path.

***

## 2. Objectives

1. Derive full-run max depth and compatibility helper outputs from `AI_ROGUE_LEVEL_SPECS` for authored depths 1-3.
2. Route world-generation decisions through one resolved level spec for theme, enemy table, room modifier, exit guard, prefab, terminal, and baseline protocol placement.
3. Split level guarantees from baseline generation by introducing an `applyLevelGuarantees()` path while preserving `applyFloorArc()` as a compatibility shim.
4. Preserve depth 1-3 deterministic outputs and add route-safety tests for generated exits, adjacent guards, prefabs, terminals, and vaults.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase39-session01-baseline-and-registry-skeleton` - Adds baseline tests, golden determinism coverage, and the initial pure runtime level registry.

### Required Tools Or Knowledge

* Bun 1.3.14 package/runtime baseline.
* Existing AI Rogue registry files in `src/extensions/ai-rogue/runtime/content/`.
* Current depth helpers in `themes.ts`, `floor-arc.ts`, `protocols.ts`, `prefabs.ts`, `terminals.ts`, `audio.ts`, `world-generator.ts`, `world-placement.ts`, `run-factory.ts`, and `simulation.ts`.
* Focused Vitest suites listed in the Session 02 stub.

### Environment Requirements

* Local repository checkout with dependencies installed or installable through `bun install`.
* Validation commands available through `bun run typecheck` and `bunx vitest run`.

***

## 4. Scope

### In Scope (MVP)

* AI Rogue runtime can resolve authored level identity from the registry - derive `AI_ROGUE_MAX_DEPTH` from `AI_ROGUE_LEVEL_SPECS.length` and keep public imports stable.
* Existing compatibility helpers can keep their names while reading level specs for authored depths - update `themeForDepth()`, `sectorThemeForDepth()`, `floorArcForDepth()`, `floorObjectiveForDepth()`, `prefabForDepth()`, `terminalForDepth()`, `protocolForDepth()`, and `musicTrackForDepth()`.
* World generation uses one resolved level spec for authored floor decisions - extend `AiRogueWorldGenerationOptions` with `levelSpec` and use spec fields for theme, enemy table, room modifier, exit guard kind, prefab, terminal, and baseline protocol.
* Level guarantees remain a separate authored layer - introduce `applyLevelGuarantees()` and keep `applyFloorArc()` as a migration shim.
* Deterministic route-safety coverage proves generated floors retain reachable exits, adjacent guards, connected prefab overlays, and non-blocking terminal or vault placement.

### Out Of Scope (Deferred)

* Adding a fourth playable floor - Reason: Session 04 owns depth 4 after registry validation and save parity are active.
* Removing compatibility exports or legacy helper names - Reason: direct consumers migrate over multiple sessions and compatibility exports remain an active consideration.
* Changing shipped depth 1-3 gameplay outputs or golden snapshots - Reason: this session is a behavior-preserving migration.
* Adding new enemies, bosses, terminals, protocols, music, ambience, assets, or persisted IDs - Reason: later sessions own save parity, asset metadata, boss contracts, and content expansion.
* Route-visible UI, PixiJS renderer import shape, public demo behavior, remote content loading, hosted writes, collectors, analytics, or telemetry - Reason: this is pure runtime migration work.

***

## 5. Technical Approach

### Architecture

Keep `src/extensions/ai-rogue/runtime/content/` as the source of authored floor identity. Runtime helpers should resolve level specs for authored depths and then project the existing helper shapes from spec fields. Existing helper names stay available so current tests, simulation, renderer state, and route code do not need a broad import rewrite in this session.

`createAiRogueWorld()` should resolve one level spec from `options.levelSpec` or `options.depth` and then use that spec consistently for generated content decisions. Explicit numeric override options such as `hazardCount`, `shardCount`, and `enemyCount` remain caller-controlled test knobs, but authored content decisions should come from `levelSpec` instead of local depth branches.

`applyLevelGuarantees()` should convert `levelSpec.guarantees` and `levelSpec.objective` into the current floor-arc behavior while preserving deterministic free-tile ordering. `applyFloorArc()` remains as a compatibility shim over the same implementation, so existing callers can be migrated without breaking public imports.

### Design Patterns

* Registry-backed compatibility wrappers: Move internals to level specs while preserving names and public call sites.
* Single resolved spec per generated floor: Avoid resolving depth policy repeatedly across modules.
* Explicit legacy fallback: Preserve non-authored helper behavior only where tests or compatibility callers still require it, not as the main authoring path.
* Deterministic safety tests: Verify route and placement invariants with fixed seeds before later content expansion.

***

## 6. Deliverables

### Files To Create

| File                                                               | Purpose                                                                                                    | Est. Lines |
| ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/runtime/__tests__/depth-resolver.test.ts` | Prove authored depth helpers project from level specs and preserve special protocol and fallback behavior. | \~140      |

### Files To Modify

| File                                                                   | Changes                                                                                                                                                    | Est. Lines |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/runtime/content/types.ts`                     | Add helper-facing projection types if needed for level guarantees or resolved generation options.                                                          | \~20       |
| `src/extensions/ai-rogue/runtime/content/index.ts`                     | Export registry helpers required by resolver modules.                                                                                                      | \~10       |
| `src/extensions/ai-rogue/runtime/run-factory.ts`                       | Derive `AI_ROGUE_MAX_DEPTH` from `AI_ROGUE_LEVEL_SPECS.length` and apply level guarantees during run creation.                                             | \~35       |
| `src/extensions/ai-rogue/runtime/floor-arc.ts`                         | Add `applyLevelGuarantees()` and make floor-arc compatibility helpers project authored specs.                                                              | \~90       |
| `src/extensions/ai-rogue/runtime/themes.ts`                            | Make theme helpers read authored level specs for depths 1-3 while keeping explicit legacy fallback behavior.                                               | \~25       |
| `src/extensions/ai-rogue/runtime/prefabs.ts`                           | Make `prefabForDepth()` read `levelSpec.placements.prefabId` for authored depths.                                                                          | \~20       |
| `src/extensions/ai-rogue/runtime/protocols.ts`                         | Make `protocolForDepth()` read `levelSpec.generation.baselineProtocolId` for authored depths while preserving rotation fallback for legacy direct callers. | \~20       |
| `src/extensions/ai-rogue/runtime/terminals.ts`                         | Make `terminalForDepth()` read `levelSpec.placements.terminalId` for authored depths.                                                                      | \~20       |
| `src/extensions/ai-rogue/runtime/audio.ts`                             | Make `musicTrackForDepth()` read `levelSpec.generation.musicTrackId` for authored depths.                                                                  | \~20       |
| `src/extensions/ai-rogue/runtime/world-placement.ts`                   | Accept a resolved exit-guard kind rather than deriving it from depth.                                                                                      | \~20       |
| `src/extensions/ai-rogue/runtime/world-generator.ts`                   | Resolve and consume `AiRogueLevelSpec` for theme, enemy table, room modifier, exit guard, prefab, terminal, and baseline protocol placement.               | \~120      |
| `src/extensions/ai-rogue/runtime/simulation.ts`                        | Use the same level-guarantee path when descending to the next floor.                                                                                       | \~30       |
| `src/extensions/ai-rogue/runtime/__tests__/content-baseline.test.ts`   | Assert baseline helper values still match current depth 1-3 behavior.                                                                                      | \~20       |
| `src/extensions/ai-rogue/runtime/__tests__/golden-determinism.test.ts` | Confirm fixed depth 1-3 world and first-turn snapshots remain unchanged.                                                                                   | \~15       |
| `src/extensions/ai-rogue/runtime/__tests__/world.test.ts`              | Add deterministic route-safety coverage for reachable exits, adjacent guards, prefabs, terminals, and vaults.                                              | \~90       |
| `src/extensions/ai-rogue/runtime/__tests__/floor-arc.test.ts`          | Cover `applyLevelGuarantees()` and `applyFloorArc()` shim parity.                                                                                          | \~50       |
| `src/extensions/ai-rogue/runtime/__tests__/themes.test.ts`             | Update helper expectations to distinguish authored depths from explicit legacy fallback behavior.                                                          | \~25       |
| `src/extensions/ai-rogue/runtime/__tests__/prefabs.test.ts`            | Cover registry-backed prefab helper behavior for authored depths.                                                                                          | \~15       |
| `src/extensions/ai-rogue/runtime/__tests__/protocols.test.ts`          | Cover baseline protocol projection and legacy rotation fallback.                                                                                           | \~20       |
| `src/extensions/ai-rogue/runtime/__tests__/terminals.test.ts`          | Cover registry-backed terminal helper behavior for authored depths.                                                                                        | \~15       |
| `src/extensions/ai-rogue/runtime/__tests__/audio.test.ts`              | Cover registry-backed music helper behavior for authored depths.                                                                                           | \~15       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `AI_ROGUE_MAX_DEPTH` is derived from `AI_ROGUE_LEVEL_SPECS.length`.
* [ ] Depth 1-3 helper outputs for theme, floor arc, objective, prefab, baseline protocol, terminal, and music match the Session 01 baseline.
* [ ] `createAiRogueWorld()` consumes one resolved level spec for authored theme, enemy table, room modifier, exit guard, prefab, terminal, and baseline protocol decisions.
* [ ] `applyLevelGuarantees()` preserves current guaranteed pickup, guaranteed protocol, introduced enemy, lesson, and objective behavior.
* [ ] Depth 1-3 golden determinism tests remain byte-identical.
* [ ] Route-safety tests prove generated exits are reachable, exit guards are adjacent to exits, prefabs do not disconnect maps, and terminals or vaults do not block the route.

### Testing Requirements

* [ ] Focused resolver and route-safety tests are written and passing.
* [ ] Existing relevant AI Rogue runtime tests pass without depth 1-3 expected-output edits.
* [ ] `bun run typecheck` passes.

### Non-Functional Requirements

* [ ] Content registry and resolver modules remain pure runtime TypeScript with no route, React, PixiJS renderer, bridge, generated-data, telemetry, or public-demo imports.
* [ ] Browser-local save shape is unchanged.
* [ ] No new persisted IDs, remote loading, hosted writes, collectors, analytics, or telemetry dependencies are introduced.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] Primary user-facing surfaces are unchanged; no debug surface is required.

***

## 8. Implementation Notes

### Working Assumptions

* Authored runtime migration applies to depths 1-3 only in this session: `AI_ROGUE_MAX_DEPTH` is currently 3, Session 01 created exactly three level specs, and Session 04 owns the first real depth-4 floor.
* Legacy helper fallback for non-authored depths may remain explicit where existing tests or direct compatibility callers still exercise it: current helpers such as `themeForDepth(99)`, `prefabForDepth(4)`, and `protocolForDepth(AI_ROGUE_PROTOCOL_ORDER.length + 1)` have historical fallback behavior, while `levelSpecForDepth()` intentionally rejects out-of-range authored-main-run depths.
* Protocol routing separates two concepts: `levelSpec.generation.baselineProtocolId` owns the generated one-per-floor protocol pickup, while `levelSpec.guarantees.protocolId` owns the floor guarantee added by `applyLevelGuarantees()`.

### Conflict Resolutions

* The Session 02 stub says to rewrite compatibility helpers over `levelSpecForDepth()` where appropriate, while existing tests still exercise some depth values outside the authored run. The chosen interpretation is to use level specs for authored depths and keep explicit legacy fallback only for non-authored direct helper calls, because Phase 39 forbids adding depth 4 before Session 04 and Session 01 documented an out-of-range authored-run rejection policy.

### Key Considerations

* Preserve `simulation.ts`, `runtime/world.ts`, and `runtime/types.ts` compatibility exports until direct consumers migrate and boundary tests stay green.
* Keep PixiJS behind route/runtime boundaries; this session must not import renderer modules into content or resolver helpers.
* Keep browser-local saved state schema untouched; do not persist whole level specs.
* Keep static public-demo and hosted surfaces unchanged.

### Potential Challenges

* World generation can drift if spec resolution changes when random calls happen: Mitigate by preserving placement ordering and running golden determinism before and after changes.
* `protocolForDepth()` currently rotates through the catalog, while level specs pin the authored baseline protocol: Mitigate by auditing call sites and keeping legacy rotation fallback outside authored depths.
* Terminal, vault, or prefab placement can accidentally block routes after refactor: Mitigate with deterministic route-safety tests across depth 1-3 seeds.

### Relevant Considerations

* \[P35] **AI Rogue compatibility exports remain**: Preserve migration exports until direct consumers migrate and boundary tests stay green.
* \[P30/P32/P34-P35] **Route-lazy runtime ownership scales**: Keep Pixi behind the Play route/local facade and avoid renderer imports in content modules.
* \[P30/P32/P34-P35] **Schema-backed browser-local state works**: Do not persist level specs or touch save migrations in this session.
* \[P30/P34-P38] **Visibility gates catch real issues**: Pair focused tests, typecheck, and deterministic proof before later content expansion.
* \[P30/P32/P34-P38] **Do not widen AI Rogue capabilities without review**: Avoid remote loading, collectors, workers, hosted writes, expanded content, or rejected-art reuse.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Generated world behavior can drift while appearing type-correct.
* External-input-like level specs can be malformed or out of range if resolver boundaries silently fall back.
* Route-safety invariants can fail if terminal, vault, prefab, or guard placement changes order.

***

## 9. Testing Strategy

### Unit Tests

* Add `depth-resolver.test.ts` for registry-backed helper projections, `AI_ROGUE_MAX_DEPTH`, protocol separation, and explicit legacy fallback.
* Extend `floor-arc.test.ts` for `applyLevelGuarantees()` and `applyFloorArc()` shim parity.
* Extend helper tests for themes, prefabs, protocols, terminals, and audio.

### Integration Tests

* Re-run Session 01 baseline and golden determinism tests for unchanged depth 1-3 behavior.
* Extend `world.test.ts` with route-safety checks using fixed seeds across depths 1-3.
* Re-run `simulation.test.ts` to verify descent uses the migrated guarantee path.

### Runtime Verification

* No browser runtime verification is required because this session does not touch route-visible UI, PixiJS mounting, controls, audio unlock behavior, or public demo surfaces.

### Edge Cases

* Non-integer and out-of-range level-spec lookups.
* Direct helper calls for non-authored depths that still need legacy fallback behavior until Session 04.
* Generated floor with no available terminal spot or vault alcove.
* Prefab placement failing to fit without disconnecting the map.
* Depth 3 objective lock and Kernel Sentinel exit guard after spec migration.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase39-session01-baseline-and-registry-skeleton`.
* Depended by: `phase39-session03-registry-validation-and-save-parity`, `phase39-session04-existing-media-floor-four`, and later Phase 39 content, asset, boss, and validation sessions.

***

## 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-session02-depth-resolver-migration/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.
