> 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/phase34-session05-runtime-api-ownership/spec.md).

# Session Specification

**Session ID**: `phase34-session05-runtime-api-ownership` **Phase**: 34 - AI Rogue Audit Remediation **Status**: Not Started **Created**: 2026-06-26

***

## 1. Session Overview

This session moves AI Rogue pre-run run-state ownership out of the Pixi renderer and into simulation-owned APIs. It is next because Phase 34 Sessions 01 through 04 completed the characterization, accessibility, simulation correctness, scenario-gate, and renderer lifecycle prerequisites, and the current phase stub maps Session 05 to AR-D1-001 and AR-D1-003.

The implementation should keep the mounted Play route behavior stable while changing where state transitions are owned. Selected-upgrade and loadout changes before turn 0 should flow through simulation helpers or run creation options; renderer/controller code should request those transitions rather than editing `AiRogueRunState` fields directly.

The session also narrows the runtime public entrypoint so product code imports only mounted runtime contracts while simulation internals and fixtures remain explicit internal or test-only imports. It must not begin the large `simulation.ts`, `renderer.ts`, or `runtime/types.ts` splits reserved for later refactor work.

***

## 2. Objectives

1. Add simulation-owned pre-run APIs for selected upgrade and progression loadout state.
2. Replace renderer-local selected-upgrade and loadout mutation paths with simulation-owned transitions.
3. Narrow the AI Rogue runtime public entrypoint used by mounted product code.
4. Add focused tests and source guards that protect the new ownership boundary.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase34-session01-characterization-test-harness` - Provides selected upgrade, loadout, and boundary characterization targets.
* [x] `phase34-session03-simulation-correctness-and-scenario-gate` - Provides the current simulation correctness baseline and gated fixture behavior.
* [x] `phase34-session04-renderer-lifecycle-and-robustness` - Provides the current renderer lifecycle and runtime bridge baseline.

### Required Tools Or Knowledge

* AI Rogue simulation creation and command flow in `src/extensions/ai-rogue/runtime/simulation.ts`.
* Mounted renderer controller code in `src/extensions/ai-rogue/runtime/renderer.ts`.
* Runtime public barrel in `src/extensions/ai-rogue/runtime/index.ts`.
* Runtime bridge imports and dynamic mount path in `src/extensions/ai-rogue/views/runtime-canvas.tsx`.
* Existing AI Rogue Vitest and Playwright coverage.

### Environment Requirements

* Bun 1.3.14 project tooling.
* No new dependencies, remote loading, hosted writes, collectors, analytics, Cloudflare dashboard actions, or generated private runtime data are required.
* AI Rogue remains explicit opt-in and browser-local.

***

## 4. Scope

### In Scope (MVP)

* AI Rogue runtime maintainers can apply selected upgrade and loadout state through simulation-owned run creation or pre-run update helpers.
* Mounted renderer code no longer owns the selected-upgrade health bonus rule or direct pre-start loadout field replacement.
* Runtime controller methods still accept selected-upgrade and loadout changes before turn 0 and ignore or safely no-op after the run has started.
* Product route code imports a narrow mounted runtime entrypoint instead of a barrel that re-exports simulation internals, content modules, and fixtures.
* Combat fixture exports are available only through direct internal/test-only module imports, not through the mounted public runtime entrypoint.
* Tests or static guards prove the entrypoint boundary and pre-run state behavior.

### Out Of Scope (Deferred)

* Full split of `simulation.ts`, `renderer.ts`, or `runtime/types.ts` - Reason: this session only narrows ownership seams before larger module refactors.
* Durable saved-run type renaming, claim normalization, or schema-owned hydration helpers - Reason: assigned to Phase 34 Session 06.
* Render-model hot-loop caching or audio documentation reconciliation - Reason: assigned to Phase 34 Session 07.
* Default enablement decision - Reason: assigned to Phase 34 Session 08.

***

## 5. Technical Approach

### Architecture

Add simulation-owned helpers or options in `simulation.ts` so selected upgrade and progression loadout changes have one owner. The preferred shape is a turn-0-only helper that returns a new `AiRogueRunState` with selected upgrade, progression loadout, derived resources, objective, achievements, and player integrity updated consistently. `createAiRogueRun` can also accept the selected upgrade so fresh generated and internal combat runs start from the same simulation-owned contract.

Update `renderer.ts` so `createRuntimeRun`, `start`, `reset`, `updateSelectedUpgrade`, and `updateProgressionLoadout` call those simulation APIs and then refresh the snapshot. The renderer should still own mounted browser resources, audio, Pixi, effects, and controller lifecycle, but not the game rule for how a selected upgrade or pre-run loadout mutates core run state.

Split the mounted entrypoint from runtime internals. A narrow `src/extensions/ai-rogue/runtime/mount.ts` can own `mountAiRogueRuntime` and mounted runtime type exports. `runtime/index.ts` should either re-export that narrow surface for compatibility or stay equally narrow. Product code should avoid importing simulation internals from the mounted entrypoint, and tests that need internals should import direct modules such as `../runtime/simulation` or `../runtime/simulation-fixtures`.

### Design Patterns

* Simulation-owned transitions: game rules live with headless simulation, not renderer lifecycle code.
* Turn-0 guardrail: pre-run updates apply only while the run is active and has not advanced.
* Narrow public entrypoint: product mount code gets controller contracts; internal tests and modules import internals explicitly.
* Source guard tests: static tests protect import boundaries that TypeScript alone does not express.

***

## 6. Deliverables

### Files To Create

| File                                                                                 | Purpose                                                         | Est. Lines |
| ------------------------------------------------------------------------------------ | --------------------------------------------------------------- | ---------- |
| `.spec_system/specs/phase34-session05-runtime-api-ownership/implementation-notes.md` | Session notes, AR-D1 evidence, boundary decisions, and gates.   | \~150      |
| `src/extensions/ai-rogue/runtime/mount.ts`                                           | Narrow mounted runtime entrypoint for product bridge imports.   | \~40       |
| `src/extensions/ai-rogue/runtime/__tests__/pre-run-state.test.ts`                    | Simulation-owned selected-upgrade and loadout transition tests. | \~160      |
| `src/extensions/ai-rogue/runtime/__tests__/runtime-boundary.test.ts`                 | Static/source guard tests for runtime entrypoint exports.       | \~120      |

### Files To Modify

| File                                                           | Changes                                                                   | Est. Lines |
| -------------------------------------------------------------- | ------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/runtime/simulation.ts`                | Add selected-upgrade and loadout pre-run APIs or run creation options.    | \~150      |
| `src/extensions/ai-rogue/runtime/types.ts`                     | Add or refine pre-run transition and narrow mounted runtime type exports. | \~45       |
| `src/extensions/ai-rogue/runtime/renderer.ts`                  | Replace local selected-upgrade/loadout mutation with simulation APIs.     | \~120      |
| `src/extensions/ai-rogue/runtime/index.ts`                     | Narrow public exports and remove fixture/internal module re-exports.      | \~80       |
| `src/extensions/ai-rogue/views/runtime-canvas.tsx`             | Import/dynamically load the narrow mounted runtime entrypoint.            | \~35       |
| `src/extensions/ai-rogue/__tests__/runtime-canvas.test.tsx`    | Update mocks and assertions for the narrow mount entrypoint and updates.  | \~80       |
| `src/extensions/ai-rogue/runtime/__tests__/simulation.test.ts` | Add regression coverage if the helper needs existing simulation fixtures. | \~50       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Renderer code no longer contains a local selected-upgrade health bonus rule or direct pre-start loadout field replacement.
* [ ] Simulation-owned APIs can create or update a turn-0 active run with selected upgrade and progression loadout state.
* [ ] Pre-run updates are ignored or safely no-op once a run has advanced past turn 0 or left active status.
* [ ] Mounted product code uses a narrow runtime entrypoint for mount and controller contracts.
* [ ] `runtime/index.ts` no longer re-exports simulation fixtures or broad internal runtime/content modules.

### Testing Requirements

* [ ] Unit tests cover selected-upgrade bonus application, replacement, and clearing through simulation-owned APIs.
* [ ] Unit tests cover loadout update behavior before turn 0 and no-op behavior after turn 0.
* [ ] Boundary tests prove mounted public exports do not include `simulation-fixtures` or broad internal re-exports.
* [ ] Runtime canvas bridge tests pass with the narrowed mount import.

### Non-Functional Requirements

* [ ] AI Rogue remains explicit opt-in, browser-local, and static-demo safe.
* [ ] No gameplay rule changes are introduced beyond moving ownership of existing pre-run transitions.
* [ ] No new dependencies, remote loading, hosted writes, collectors, analytics, or `/__*` public-demo bridge calls are introduced.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] Primary user-facing surfaces contain product-facing copy only.
* [ ] `bun run test -- src/extensions/ai-rogue/runtime/__tests__/pre-run-state.test.ts src/extensions/ai-rogue/runtime/__tests__/runtime-boundary.test.ts src/extensions/ai-rogue/__tests__/runtime-canvas.test.tsx` passes or exact blockers are recorded.
* [ ] `bun run test -- src/extensions/ai-rogue` passes or exact blockers are recorded.
* [ ] `bun run typecheck`, `bun run lint`, and `bun run format:check` pass or exact blockers are recorded.

***

## 8. Implementation Notes

### Working Assumptions

* Phase 34 Session 05 is the next executable session: the analysis script reported `current_phase` 34, `current_session` null, Sessions 01 through 04 completed, and Session 05 as the first unfinished current-phase candidate. Planning can proceed because the Session 05 stub depends on coverage from Sessions 01 and 03, and both are complete.
* The repository is treated as a single package: the analysis script reported `monorepo` as null and no packages. All paths are repo-root-relative.
* The runtime barrel can be narrowed without a broad product migration: current source search found product use of the barrel in `src/extensions/ai-rogue/views/runtime-canvas.tsx`, with tests importing internals directly from their owned modules. It is safe to proceed with a focused bridge import change and boundary tests.

### Key Considerations

* Session 06 owns durable schema and save hydration naming, so this session should not rename durable snapshot types or replace save-schema contracts.
* Session 07 owns render hot-loop caching and audio documentation drift, so this session should not add projection caching or audio behavior changes.
* AI Rogue public-demo safety remains static and browser-local; any import boundary change must not expose local bridge calls, hosted writes, or fixture route controls.

### Relevant Considerations

* \[P30/P32] **Route-lazy runtime ownership scales**: Keep Pixi behind the Play route/local facade while simulation owns game-rule transitions.
* \[P30/P32] **Schema-backed browser-local state works**: Preserve Zod-backed durable state contracts and defer schema naming/hydration changes to Session 06.
* \[P31-P33] **Pages demo stays static-only**: Runtime boundary changes must not introduce hosted reads, writes, bridge calls, Functions, or collectors.
* \[P31-P33] **Route smoke is a privacy gate**: Keep no-bridge and public-demo smoke checks in the implementation evidence.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Pre-run update drift: selected upgrade, loadout, resources, objective, and snapshot data can diverge if renderer and simulation own different rules.
* Boundary regression: broad runtime exports can quietly re-expose fixtures or internals through product imports.
* Re-entry state mismatch: updates after reset, load, or turn advancement can apply when they should be revalidated or ignored.

***

## 9. Testing Strategy

### Unit Tests

* Add `pre-run-state.test.ts` for selected upgrade application, replacement, clearing, loadout update behavior, and turn-0-only guardrails.
* Add `runtime-boundary.test.ts` for `runtime/index.ts` and mounted entrypoint export boundaries.
* Update runtime canvas tests so bridge mocks and controller update assertions use the narrowed mounted runtime import.

### Integration Tests

* Run the focused AI Rogue suite to catch import, controller, save/load, and simulation regressions across existing runtime coverage.

### Runtime Verification

* Use existing Playwright runtime coverage only if the implementation changes product route mount behavior materially; otherwise focused unit and bridge tests cover the planned surface.

### Edge Cases

* Clearing selected upgrade at turn 0 removes the selected-upgrade marker without corrupting player integrity.
* Replacing the same selected upgrade does not double-apply max-health bonus.
* Updating loadout after turn 0 or after a terminal run state does not mutate active run state.
* Internal combat fixtures remain directly importable by tests but are not exported from the mounted public runtime entrypoint.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase34-session01-characterization-test-harness`, `phase34-session03-simulation-correctness-and-scenario-gate`, `phase34-session04-renderer-lifecycle-and-robustness`
* Depended by: `phase34-session06-persistence-schema-contracts`, `phase34-session07-render-performance-and-audio-docs`, `phase34-session08-default-enablement-evidence-closeout`

***

## 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/phase34-session05-runtime-api-ownership/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.
