> 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-session03-simulation-correctness-and-scenario-gate/spec.md).

# Session Specification

**Session ID**: `phase34-session03-simulation-correctness-and-scenario-gate` **Phase**: 34 - AI Rogue Audit Remediation **Status**: Not Started **Created**: 2026-06-26

***

## 1. Session Overview

This session fixes the AI Rogue simulation correctness blocker AR-D2-001 and the production scenario exposure blocker AR-D1-002. It makes lethal turn-start status damage produce the same loss/no-action outcome for Movement, Strike, Surge, and Protocol, then removes the browser query path that lets production or public-demo users load the deterministic combat fixture.

It is next because Phase 34 Session 01 added the lethal command-family characterization coverage and identified the e2e test that currently relies on `scenario=combat`. Phase 34 Session 02 has already closed the accessibility and compact-input blocker, so the dependency order now moves to simulation correctness and debug-scenario gating before renderer lifecycle and runtime API ownership work.

The implementation should preserve deterministic generated runs, existing combat semantics outside the lethal turn-start path, and deterministic browser combat coverage through a local/test-only mechanism. It must not broaden default enablement, add new content, expose diagnostics on product routes, or introduce hosted runtime behavior.

***

## 2. Objectives

1. Centralize turn-start player status handling so lethal damage stops all action resolution before resource spend, protocol consumption, attacks, healing, threat clearing, pickups, or enemy turns.
2. Update the lethal command-family regression coverage so Movement, Strike, Surge, and every Protocol branch assert the same loss/no-action contract.
3. Remove or gate the `scenario=combat` browser query behavior so production and public-demo Play routes always use generated runs.
4. Preserve deterministic combat e2e coverage with a test/local-only fixture hook and documentation that no longer treats the query parameter as a product route contract.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase34-session01-characterization-test-harness` - Provides lethal turn-start command matrix coverage and identifies the AR-D2-001 behavior gap.
* [x] `phase34-session02-accessibility-and-compact-input` - Completed the prior Phase 34 blocker and kept the Play route/runtime bridge test surface current.

### Required Tools Or Knowledge

* AI Rogue simulation command pipeline in `src/extensions/ai-rogue/runtime/simulation.ts`.
* Protocol catalog in `src/extensions/ai-rogue/runtime/protocols.ts`.
* Play route seed/query handling in `src/extensions/ai-rogue/views/play-view.tsx`.
* Runtime mount contract in `src/extensions/ai-rogue/views/runtime-canvas.tsx`, `src/extensions/ai-rogue/runtime/types.ts`, and `src/extensions/ai-rogue/runtime/renderer.ts`.
* Vitest and Playwright coverage for AI Rogue runtime behavior.

### Environment Requirements

* Bun 1.3.14 project tooling.
* Local browser-capable Playwright setup for the AI Rogue runtime e2e file when feasible.
* No remote services, hosted writes, generated private runtime data, new dependencies, or Cloudflare dashboard actions are required.

***

## 4. Scope

### In Scope (MVP)

* AI Rogue players defeated by turn-start burning or leaking cannot continue an action - centralize the turn-start status tick and lethal no-action return path for Movement, Strike, Surge, and Protocol.
* Surge cannot spend shards, damage or jam enemies, collect kill rewards, clear threats, run enemy turns, or change win/loss outcomes after lethal turn-start status damage.
* Protocol cannot consume the carried protocol, heal through Patch Kit, reveal maps, fire Trace Lance, Phase Step, jam enemies, clear threats, run enemy turns, or return to active status after lethal turn-start status damage.
* Production and public-demo Play routes ignore `?scenario=combat` and any equivalent browser query path for deterministic combat fixtures.
* Browser combat e2e coverage remains deterministic through a local/test-only setup path that is not product-facing and is ignored in production builds.
* AI Rogue docs that mention the old combat query path are updated to describe the current test-only fixture mechanism.

### Out Of Scope (Deferred)

* Combat rebalance, new enemy behavior, new protocols, new floors, or new content fixtures - Reason: this session fixes action ordering and fixture exposure only.
* Full runtime barrel narrowing or public API split - Reason: assigned to Session 05.
* Renderer lifecycle, resize coalescing, reduced-motion fallback, sprite-pool cleanup, or audio fallback work - Reason: assigned to Sessions 04 and 07.
* Durable save schema, claim normalization, or hydration helper changes - Reason: assigned to Session 06.
* Default enablement decision - Reason: Phase 34 closeout owns the renewed recommendation after all gates are recorded.

***

## 5. Technical Approach

### Architecture

Add a narrow simulation helper that performs the player turn-start status tick, collects the status events, and returns an immediate finalized loss result when the tick defeats the player. Movement and Strike already have the intended behavior, so route them through the helper with minimal semantic drift. Surge and Protocol should call the same helper before they mutate action-specific state: Surge before shard spend and pulse events, Protocol before queue dequeue and protocol branch effects.

Keep deterministic run generation in the runtime layer. The renderer can still create a combat fixture when an internal mount option explicitly requests it, but the Play route must not derive that option from browser URL query params. Use a local/test-only hook for Playwright combat coverage and make all production/public-demo route paths fall back to generated runs.

### Design Patterns

* Shared simulation finalizer: One helper prevents command families from drifting on lethal status ordering.
* Action-first invariants in tests: Assertions prove no resource spend, protocol consumption, enemy damage, threat clearing, healing, or enemy turn happens after lethal turn-start damage.
* Product-route query hardening: Browser query parsing stays limited to seed replay; fixture scenarios move behind a non-product local test hook.
* Existing deterministic fixtures: Reuse `createAiRogueScenarioWorld("combat")` for tests without adding new fixtures or dependencies.

***

## 6. Deliverables

### Files To Create

| File                                                                                                    | Purpose                                                                           | Est. Lines |
| ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ---------- |
| `.spec_system/specs/phase34-session03-simulation-correctness-and-scenario-gate/implementation-notes.md` | Session implementation notes, command evidence, and deterministic-behavior notes. | \~140      |

### Files To Modify

| File                                                                | Changes                                                                                         | Est. Lines |
| ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/runtime/simulation.ts`                     | Centralize lethal turn-start handling and apply it to Movement, Strike, Surge, and Protocol.    | \~120      |
| `src/extensions/ai-rogue/runtime/__tests__/status-expanded.test.ts` | Update AR-D2-001 tests for fixed loss/no-action semantics across commands and protocols.        | \~110      |
| `src/extensions/ai-rogue/runtime/__tests__/simulation.test.ts`      | Add deterministic same-seed or unaffected-combat regression coverage where useful.              | \~40       |
| `src/extensions/ai-rogue/views/play-view.tsx`                       | Remove browser query scenario selection and keep product route seed parsing intact.             | \~35       |
| `src/extensions/ai-rogue/views/runtime-canvas.tsx`                  | Accept only generated production scenario by default and wire any local test hook safely.       | \~35       |
| `src/extensions/ai-rogue/runtime/types.ts`                          | Update runtime scenario type/comment so combat fixtures are explicitly internal/test-only.      | \~15       |
| `src/extensions/ai-rogue/runtime/renderer.ts`                       | Preserve generated default and internal combat fixture creation on start/reset/load boundaries. | \~35       |
| `src/extensions/ai-rogue/__tests__/runtime-canvas.test.tsx`         | Cover runtime mount scenario fallback or local test hook behavior.                              | \~45       |
| `tests/e2e/ai-rogue-runtime.spec.ts`                                | Replace `?scenario=combat` usage with local fixture setup and prove the query is ignored.       | \~60       |
| `docs/extensions/ai-rogue/playtest-notes.md`                        | Replace production combat-query references with current test-only fixture language.             | \~20       |
| `docs/extensions/ai-rogue/run-loop-rebuild-notes.md`                | Update browser combat coverage notes so docs match the gated scenario path.                     | \~15       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Lethal turn-start status produces consistent `lost` status and no-action behavior for Movement, Strike, Surge, and Protocol.
* [ ] Surge does not spend shards, attack, jam, collect rewards, clear threats, or run enemy turns after lethal turn-start status damage.
* [ ] Protocol does not consume a protocol, heal, reveal, move, attack, jam, clear threats, or run enemy turns after lethal turn-start status damage.
* [ ] Production and public-demo Play routes ignore `?scenario=combat` and do not expose a user-facing fixture path.
* [ ] Deterministic browser combat coverage still exists through a local or test-only mechanism.

### Testing Requirements

* [ ] Unit tests written and passing for lethal turn-start Movement, Strike, Surge, and all Protocol branch behavior.
* [ ] Unit or integration tests written and passing for generated-run fallback when a browser query tries to request combat scenario.
* [ ] Playwright AI Rogue runtime combat smoke updated to use the gated fixture setup.
* [ ] Focused AI Rogue unit and browser checks pass or exact blockers are recorded.

### Non-Functional Requirements

* [ ] Same seed plus same inputs remain deterministic for generated runs.
* [ ] No new dependencies, remote loading, hosted writes, collectors, analytics, or public-demo bridge calls are introduced.
* [ ] User-facing Play route copy remains product-facing and does not expose debug fixture language.

### 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` passes or exact blockers are recorded.
* [ ] `bunx playwright test tests/e2e/ai-rogue-runtime.spec.ts` 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

* Browser combat coverage should remain, but not through a production query parameter. Evidence: `tests/e2e/ai-rogue-runtime.spec.ts` currently uses `?scenario=combat` to create deterministic combat, while `.spec_system/PRD/phase_35/PRD_phase_35.md` recommends a test/local-only gate or production/public-demo ignore behavior. It is safe to proceed because the fixture can stay internal to test setup without changing user-facing run generation.
* The session should fix the existing command pipeline instead of adding a large reducer split. Evidence: Session 05 owns broad runtime API ownership and module-boundary work, while this session is scoped to AR-D2-001 and AR-D1-002. It is safe to proceed because a small shared helper can remove the behavior drift without reshaping the whole simulation module.

### Conflict Resolutions

* Existing e2e and docs treat `scenario=combat` as a browser route input, while Phase 34 and the audit classify that as a production/debug-surface exposure. Chosen interpretation: generated runs remain the only product route behavior; deterministic combat setup moves to local/test-only machinery. This wins because it satisfies AR-D1-002 while preserving the test coverage that made the fixture useful.

### Key Considerations

* Preserve browser-local state and static public-demo boundaries. This session must not add `/__*` bridge calls, hosted writes, collectors, analytics, Functions, or remote asset loading.
* Keep all gameplay changes limited to lethal turn-start ordering. Non-lethal Surge, Protocol, Movement, Strike, enemy-turn, pickup, and compile behavior should remain unchanged.
* Keep product surfaces clean. Fixture names and debug setup should appear in tests or docs for developers, not visible Play route copy.

### Potential Challenges

* Protocol branches mutate many state slices. Guard lethal turn-start defeat before queue mutation so no branch-specific rollback is needed.
* Surge currently validates resources and targets before the turn tick. Preserve existing blocked/no-turn behavior for insufficient shards and no adjacent enemies while changing only the lethal turn-start path after a valid Surge attempt begins.
* Playwright needs deterministic combat without the query. Use an init script or equivalent local test setup that is unavailable in production builds and ignored in public-demo routes.

### Relevant Considerations

* \[P30/P32] **AI Rogue default enablement deferred**: This session closes correctness blockers but does not make AI Rogue default-enabled.
* \[P31-P33] **Pages demo stays static-only**: Public-demo AI Rogue must remain browser-local with no bridge calls, hosted writes, collectors, analytics, Functions, or advanced Workers.
* \[P30/P32] **Route-lazy runtime ownership scales**: Keep Pixi behind the Play route/runtime facade while simulation stays free of DOM, React, persistence, browser globals, route state, and host LiveData.
* \[P30/P32] **PixiJS v8 route and input tests**: Preserve browser combat proof through deterministic route tests while removing product debug inputs.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Lethal status handling can partially mutate run state before loss, so tasks must assert no resource spend, protocol consumption, enemy damage, healing, threat clearing, or enemy turn after lethal turn-start defeat.
* Scenario selection is browser input, so tasks must validate it at the route or mount boundary and fall back deterministically to generated runs.
* E2E fixture setup can become a hidden product path, so tasks must keep it local/test-only and verify public-demo or production-style routes ignore the query.

***

## 9. Testing Strategy

### Unit Tests

* `src/extensions/ai-rogue/runtime/__tests__/status-expanded.test.ts`: update the lethal command matrix so Movement, Strike, Surge, Patch Kit, Trace Map, Signal Jammer, Trace Lance, and Phase Step all end lost with only status/loss events and no action-specific mutations.
* `src/extensions/ai-rogue/runtime/__tests__/simulation.test.ts`: add a same-seed or non-lethal regression proving generated combat semantics remain deterministic outside the lethal path.
* `src/extensions/ai-rogue/__tests__/runtime-canvas.test.tsx`: prove runtime mount defaults to generated scenario and any test hook is explicit.

### Integration Tests

* `tests/e2e/ai-rogue-runtime.spec.ts`: update the scripted combat encounter to set the deterministic fixture through the local/test-only setup and assert attack feedback still changes rendered pixels.
* `tests/e2e/ai-rogue-runtime.spec.ts`: add a regression proving `/extensions/ai-rogue/play?scenario=combat` does not expose the combat fixture on the product route.

### Runtime Verification

* Run `bun run test -- src/extensions/ai-rogue`.
* Run `bunx playwright test tests/e2e/ai-rogue-runtime.spec.ts` when local browsers are available.
* Run `bun run typecheck`, `bun run lint`, and `bun run format:check`.
* Run ASCII/LF and no-bridge spot checks over changed files.

### Edge Cases

* Lethal burning or leaking at turn start with one health.
* Protocol queue containing each protocol ID.
* Surge valid target and sufficient shards versus existing blocked Surge paths.
* Pending sentry threats and adjacent enemies should not be cleared or jammed when lethal turn-start defeat occurs.
* Reset and restart after a completed run should continue to use generated scenario unless a local test hook explicitly requests combat.
* Public-demo mode and production-style URLs must ignore fixture queries.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase34-session01-characterization-test-harness`, `phase34-session02-accessibility-and-compact-input`
* Depended by: `phase34-session04-renderer-lifecycle-and-robustness`, `phase34-session05-runtime-api-ownership`, `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-session03-simulation-correctness-and-scenario-gate/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.
