> 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/docs/extensions/ai-rogue/plan-2026-06-21.md).

# AI Rogue Extension Plan

## Current Supersession Note

This file preserves historical 2026-06-21 planning. Guidance that audio could remain optional or absent is superseded by the current direct Web Audio runtime with committed local Ogg music and SFX, persisted mute/music/SFX preferences, autoplay unlock, lazy decode, low-HP heartbeat, silent fallback, and no sidechain or event-based music ducking. Guidance that default enablement was a future decision is superseded by the Phase 34 production default-enable decision; `VITE_CLAUDE_OS_ENABLED_EXTENSIONS=none` remains the explicit hide-all opt-out. Use [Game Feel And Audio Baseline](/ai-os-and-trend-finder-docs/docs/extensions/ai-rogue/game-feel.md), [Enablement Decision](/ai-os-and-trend-finder-docs/docs/extensions/ai-rogue/enablement-decision.md), [Runtime Data And Enablement](/ai-os-and-trend-finder-docs/docs/extensions/ai-rogue/runtime-data-and-enablement.md), and [`docs/media-policy.md`](/ai-os-and-trend-finder-docs/docs/media-policy.md) as the current contracts.

## Session Split Plan

### Session 01: Direction And Asset Readiness

**Objective**: Lock the first implementation inputs so later runtime work has stable product, economy, renderer, and art constraints.

**Scope**:

* Confirm `AI Rogue`, `ai-rogue`, `Insight Shards`, manual claims, and the locked earning source weights remain the baseline.
* Document the extension boundary, privacy constraints, media policy, and non-goals that must be preserved during implementation.
* Finalize the first pixel-art batch acceptance checklist, prompt/provenance notes, palette, tile size, and animation-frame budget.
* Record that `pixi.js@8.19.0` is installed before implementation, while runtime imports still stay lazy and out of the registry.
* Record that `Insight Shards` appear both as dungeon pickup feedback and as post-run or claim rewards for the first playable slice.

**Outputs**:

* A stable implementation baseline for product naming, capability declarations, economy weights, renderer constraints, and art acceptance.
* Reproducible asset notes for any committed first-batch player, enemy, tile, item, and UI assets.
* Recorded assumptions for deferred systems such as audio, worker simulation, gamepad support, pointer lock, collectors, and generated content packs.

**Dependencies / Notes**:

* Assumption: client-only extension work remains the default unless a concrete browser-safe generated-content need appears.
* Decision: PixiJS is installed up front, but Session 02 still must not import renderer code from the extension registry or app shell.
* Decision: first-batch prompt set, palette, tile size, animation-frame budget, atlas grouping, and shard treatment are locked in `docs/extensions/ai-rogue/visual-assets.md`.

**Acceptance Checks**:

* The first implementation can proceed without inventing names, currency rules, capability reasons, or asset policy decisions.
* Pixel-art assets selected for runtime use have committed workspace paths, provenance notes, and pass the 200 KB per-file policy where applicable.
* Deferred systems are explicitly marked out of scope unless later profiling or UX evidence justifies them.

**Session 01 Ratification**:

* Session 01 ratified these implementation inputs in [`implementation-baseline.md`](/ai-os-and-trend-finder-docs/docs/extensions/ai-rogue/implementation-baseline.md). Later Phase 30 sessions should use that baseline for product naming, extension boundary, economy weights, renderer posture, asset inventory, privacy rules, and deferred-system anchors.

### Session 02: Extension Shell And Routes

**Objective**: Add the `ai-rogue` extension shell with the expected React/TanStack host surfaces and honest capabilities.

**Scope**:

* Add the compile-time extension registration, primary `/extensions/ai-rogue/play` route, and secondary Play, Ledger, Loadout, and Settings surfaces.
* Original implementation scope: route the extension through the then-current extension visibility gate and match existing empty, disabled, and missing-data states. This is superseded by the Phase 34 production default enablement decision.
* Declare only initial `readGeneratedData` and `localStorage` capabilities with accurate reasons.
* Keep PixiJS, renderer code, and browser-only APIs out of the registry and app shell chunks.
* Add route and registry coverage for registration, disabled behavior, default-view redirect, and capability declarations.

**Outputs**:

* `src/extensions/ai-rogue/` shell with client entry, capabilities, view modules, and route integration.
* Tests proving the extension registers correctly and routes to the Play view without loading game runtime code.
* Initial accessible surrounding UI structure for Play, Ledger, Loadout, and Settings.

**Dependencies / Notes**:

* Depends on Session 01 baseline decisions.
* Assumption: the first screen remains the playable game surface, with secondary panels supporting the run instead of becoming a dashboard.

**Acceptance Checks**:

* Extension routes work when enabled and fail gracefully when disabled or when live data is absent.
* Static registry imports remain lightweight and do not import PixiJS or game runtime modules.
* Capability declarations match only the APIs actually used by the shell.

### Session 03: PixiJS Runtime Boundary

**Objective**: Prove the lazy PixiJS v8 renderer boundary inside the extension host without committing to full gameplay yet.

**Scope**:

* Use the installed `pixi.js@8.19.0` package; do not add `@pixi/react` unless a later Pixi UI layer proves it needs declarative composition.
* Implement the lazy runtime mount, WebGL renderer configuration, resize handling, ticker loop, disposal lifecycle, and route cleanup.
* Use `preserveDrawingBuffer: true` for WebGL pixel-read verification, or add a screenshot non-blank fallback if the renderer path changes.
* Add start, pause, reset, hidden-tab throttling, reduced-motion handling, and coarse runtime events back to React.
* Measure lazy chunk output and adjust bundle-budget classification only if the PixiJS chunk requires the watched vendor allowance.

**Outputs**:

* Runtime modules for renderer ownership, loop lifecycle, input sampling, and asset-loading placeholders.
* Playwright canvas coverage for nonblank paint, resize, keyboard input smoke behavior, and route-away cleanup.
* Bundle-budget evidence showing PixiJS remains outside shared app chunks.

**Dependencies / Notes**:

* Depends on Session 02 route shell.
* Assumption: WebGL is the first accepted renderer because existing canvas pixel checks depend on WebGL contexts.
* Note: WebGPU adoption later requires a different nonblank verification strategy.

**Acceptance Checks**:

* Visiting the Play route lazily loads the runtime, paints a nonblank canvas, resizes correctly, and disposes without leaked listeners or tickers.
* Dashboard, extension index, and unrelated routes do not pay the PixiJS runtime cost.
* Build and budget checks identify no unexpected shared chunk growth from the game runtime.

### Session 04: Economy And Ledger

**Objective**: Implement the browser-safe AI OS economy projection, manual claim flow, and minimal ledger provenance.

**Scope**:

* Build `deriveAiRogueEconomy(liveData)` as a pure transform over browser-safe `LiveData` branches.
* Apply the locked weighted blend for completed work, skill diversity, tool-class diversity, capped token or spend signal, and readiness/streak bonuses.
* Treat unavailable pricing, unknown tokens, example data, and missing provider telemetry as absent contributions rather than penalties.
* Add daily earning caps, provenance labels, and idempotent redemption keys by date, provider, and activity run ID where available.
* Render the Ledger view with claimable `Insight Shards`, manual claim action, and compact "why did I earn this?" breakdown.

**Outputs**:

* Economy schema and tested transform modules.
* Manual claim UI and ledger entries with bounded, explainable rewards.
* Fixture coverage for missing data, unknown pricing, example data, repeated redemption attempts, and source-weight behavior.

**Dependencies / Notes**:

* Depends on Session 02 shell.
* Assumption: raw spend remains a capped signal and never dominates progression.
* Note: no browser writes to `src/data/live-data.json`.

**Acceptance Checks**:

* Claims are deterministic for the same input snapshot and cannot double-credit after refresh.
* Ledger provenance explains each claim without exposing prompts, transcripts, commands, private paths, credentials, or logs.
* Economy tests cover missing or partial telemetry without failing the whole claim.

### Session 05: Persistence And Save Contracts

**Objective**: Add versioned browser-local persistence for preferences, wallet, ledger, run history, saves, and reset behavior.

**Scope**:

* Define Zod schemas for preferences, wallet, ledger, save metadata, run history, and future migration boundaries.
* Store tiny preferences in `localStorage` and larger state in IndexedDB.
* Add parsers and migration tests for valid, missing, stale, and malformed local data.
* Wire save/load/reset behavior into the React shell and game runtime boundary at coarse state boundaries.
* Ensure generated private runtime data never enters committed files.

**Outputs**:

* `save-schema` and persistence helpers with versioned parsing.
* Local wallet, ledger, preferences, run history, and save storage plumbing.
* Reset controls for Settings and run-level restart behavior.

**Dependencies / Notes**:

* Depends on Session 04 for wallet and ledger contracts.
* Assumption: normal play state stays local-first and browser-owned.

**Acceptance Checks**:

* Preferences survive refresh, malformed data is handled safely, and reset clears only AI Rogue local state.
* Wallet and ledger persistence preserves claim idempotency across reloads.
* Save migration tests prove older or partial records do not crash the extension.

### Session 06: Dungeon Simulation Core

**Objective**: Build the deterministic roguelike simulation independent of PixiJS rendering.

**Scope**:

* Implement seeded RNG, grid world generation, floor/wall/door/hazard/fog tile semantics, and one short dungeon floor with a win condition.
* Add player movement, keyboard and pointer command translation, turns, health, combat log events, and turn advancement.
* Implement two enemy types with distinct simple behavior and deterministic combat resolution.
* Add field of view and fog of war.
* Keep simulation, world generation, combat, and progression rules in pure TypeScript modules.

**Outputs**:

* Simulation, world, entity, combat, RNG, input-command, and progression primitives.
* Focused unit tests for RNG determinism, world generation, movement, FOV, combat, run completion, and enemy behavior.
* Fixture seeds for repeatable Playwright and unit-test scenarios.

**Dependencies / Notes**:

* Depends on Session 01 direction and can run after or alongside Session 03 if interfaces are stable.
* Assumption: no physics engine, worker, or procedural biome system is needed for the first slice.

**Acceptance Checks**:

* The same seed produces the same map, enemy placement, combat outcomes, and win condition path.
* Simulation tests run without starting PixiJS or browser APIs.
* Combat and movement are turn-based, deterministic, and visible through coarse state snapshots.

### Session 07: Play Runtime Integration

**Objective**: Connect the simulation, renderer, assets, controls, and first spendable upgrade into a complete playable run.

**Scope**:

* Wire committed player, enemy, tile, fog, hazard, currency, relic, and compact UI atlas assets into PixiJS.
* Render the simulated world, player, enemies, pickups, combat feedback, health, status pips, run marker, and basic UI frames.
* Connect start, pause, reset, resume, save/load, win, loss, and run completion events between React and the runtime.
* Add one spendable upgrade that affects a run and consumes wallet state through the loadout flow.
* Add accessibility controls for reduced motion, contrast, input remapping, and pause.

**Outputs**:

* A playable first dungeon slice on `/extensions/ai-rogue/play`.
* Loadout interaction for one wallet-backed upgrade.
* Runtime asset wiring and animation frame use that stays within media and bundle budgets.

**Dependencies / Notes**:

* Depends on Sessions 03, 05, and 06.
* Depends on the Session 01 decision that `Insight Shards` use both in-run pickup feedback and post-run or claim reward banking.

**Acceptance Checks**:

* A user can start a run, move, fight, discover fogged areas, reach a win or loss state, and reset or resume without page reload.
* The first committed art set appears in runtime instead of geometric placeholders except for explicit diagnostics.
* Reduced-motion and input-remapping settings visibly affect runtime behavior.

### Session 08: Progression Depth

**Objective**: Expand the stable first slice into AI OS-flavored progression without changing the privacy boundary.

**Scope**:

* Add skill-linked classes or relic modifiers derived from `skills.active` and `localAgents.skillSources`.
* Add capped model-flavored resource drops or materials from `modelUsage` signals.
* Expand enemy behaviors, room modifiers, run objectives, and upgrade/relic choices.
* Add run history and achievement data using the existing local persistence contracts.
* Evaluate worker simulation only if profiling shows measurable input or rendering blockage.

**Outputs**:

* Additional progression rules that reflect AI OS usage diversity without exposing private activity content.
* Expanded local run history and achievements.
* Profiling notes or tests supporting any decision to keep or add a worker.

**Dependencies / Notes**:

* Depends on a stable first playable slice from Session 07.
* Assumption: optional generated content packs and collectors remain deferred unless a concrete browser-safe content need appears.

**Acceptance Checks**:

* Progression changes use counts, categories, labels, and capped signals instead of raw prompts, logs, command bodies, or private paths.
* New relics, classes, resources, or objectives are covered by deterministic unit tests.
* Added content does not require a new backend, auth service, realtime service, or remote package loading.

### Session 09: Content Polish And Mobile

**Objective**: Polish presentation, controls, compact assets, audio choice, and mobile usability while preserving build and media constraints.

**Scope**:

* Expand reviewed compact sprite atlases and add sound effects only if Web Audio API or no-audio tradeoffs are settled.
* Add seed sharing, mobile layout, pointer-first controls, and viewport-specific framing.
* Improve run feedback, reward presentation, combat readability, and status indicators.
* Validate asset sizes, atlas consistency, animation clarity, contrast, and reduced-motion behavior.
* Avoid large asset packs, unreviewed third-party art, and baked gameplay text in sprites.

**Outputs**:

* Polished compact visual and optional audio layer for the playable game.
* Mobile and pointer-first Playwright coverage.
* Updated asset provenance and media-policy notes for any expanded art or audio.

**Dependencies / Notes**:

* Depends on Session 07 and should follow any Session 08 content that affects UI or controls.
* Assumption: audio remains Web Audio API directly, or absent, until complexity justifies a wrapper.

**Acceptance Checks**:

* Desktop and mobile Play routes frame the canvas and surrounding controls without overlap or hidden critical actions.
* Asset-size checks pass for committed runtime media.
* Optional audio, if added, respects preferences and does not add unnecessary dependency or bundle weight.

### Session 10: Quality Gates And Enablement

**Objective**: Validate the extension end to end and prepare it for default enablement only after all gates pass.

**Scope**:

* Run typecheck, lint, format check, unit tests, focused browser tests, build, bundle budget, asset-size checks, and private-runtime checks.
* Verify extension docs, capabilities, route behavior, runtime cleanup, privacy posture, and media provenance remain accurate.
* Fix failures in economy, save migration, RNG, simulation, combat, canvas rendering, interaction, mobile layout, reduced motion, and route cleanup tests.
* Decide whether the extension can remain disabled, become opt-in, or be enabled by default.
* Capture remaining follow-up work for future content, collectors, WebGPU verification, worker protocol, or expanded progression.

**Outputs**:

* Passing validation evidence for the accepted AI Rogue slice.
* Updated documentation where implementation diverged from the original plan.
* A clear enablement decision and follow-up list.

**Dependencies / Notes**:

* Depends on Sessions 02 through 09.
* Assumption: enable-by-default is blocked until build, budget, asset, privacy, unit, and browser gates pass.

**Acceptance Checks**:

* Required commands pass: `bun run typecheck`, `bun run lint`, `bun run format:check`, focused Vitest suites, focused Playwright suites, `bun run build`, `bun run budget:check`, `bash scripts/check-asset-sizes.sh`, and `bun run runtime:check-private`.
* Documentation reflects the implementation state, deferred systems, and any changed decisions.
* No non-goal has slipped into the initial implementation, including remote loading, unbounded token-burn rewards, unreviewed large media, or raw private telemetry exposure.

> **Status:** Planning **Captured:** 2026-06-21 **Scope:** High-level plan for an AI OS roguelike game extension built on a modern PixiJS stack. **Consolidates:** Durable implementation guidance from earlier 2026-06-21 planning.

## Goal

Build a repo-local AI OS extension that is a real playable roguelike, not a demo wrapper around old example projects. The game should use a modern PixiJS runtime inside the existing React/TanStack extension host and connect back to AI OS by turning browser-safe agent telemetry into an in-game currency and progression system.

The core loop:

```
Use AI OS and local agents
  -> aggregate browser-safe usage, spend, token, skill, and tool metadata
  -> convert bounded daily activity into in-game currency
  -> spend currency on roguelike upgrades, relics, crafting, and unlocks
  -> play short dungeon runs in the AI OS extension
```

The game should make AI OS feel alive without incentivizing wasteful token burning. Raw spend is a signal, not the only reward source.

## Product Shape

Product name: `AI Rogue`.

Extension ID: `ai-rogue`.

Primary route:

```
/extensions/ai-rogue/play
```

Initial user-facing surfaces:

| Surface  | Purpose                                                                 |
| -------- | ----------------------------------------------------------------------- |
| Play     | Canvas-first roguelike run with concise surrounding controls.           |
| Ledger   | Earned currency events from AI OS usage, capped by day and source.      |
| Loadout  | Persistent upgrades, relics, classes, and skill-linked modifiers.       |
| Settings | Accessibility, reduced motion, input remapping, save reset, debug seed. |

The first screen should be the playable game. Secondary panels should support the run instead of turning the extension into a dashboard.

## Architecture

Use the standard compile-time extension model documented in [`docs/extensions/README_docs-extensions.md`](/ai-os-and-trend-finder-docs/docs/extensions/readme_docs-extensions.md). No dynamic plugin loading, no remote game package loading, and no separate app runtime.

Recommended layout:

```
src/extensions/ai-rogue/
|-- client.tsx
|-- capabilities.ts
|-- economy-schema.ts
|-- save-schema.ts
|-- game/
|   |-- runtime.ts
|   |-- renderer.ts
|   |-- assets.ts
|   |-- input.ts
|   |-- loop.ts
|   |-- simulation.ts
|   |-- world.ts
|   |-- entities.ts
|   |-- combat.ts
|   |-- progression.ts
|   `-- rng.ts
`-- views/
    |-- play-view.tsx
    |-- ledger-view.tsx
    |-- loadout-view.tsx
    `-- settings-view.tsx
```

Default stance: client-only extension first. Add a script collector only if the game later needs generated browser-safe content packs or precomputed economy rollups.

## Repository Constraints To Preserve

AI Rogue should stay inside the current AI OS platform constraints:

| Constraint                                               | Impact                                                                                                                                                                                                         |
| -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Static extension registry                                | Add source-reviewed npm dependencies only; no runtime package loading.                                                                                                                                         |
| React 19, TanStack Router/Start, Vite 8                  | The game mounts inside React views and initializes browser APIs after mount.                                                                                                                                   |
| Cloudflare Worker style production build                 | Prefer browser-native JS/WebGL/WebGPU assets over opaque engine exports.                                                                                                                                       |
| 1250 KB (1.25 MB) total client JS gzip budget            | Lazy load PixiJS and measure the runtime chunk before accepting the stack.                                                                                                                                     |
| 350 KB app chunk and 450 KB watched vendor chunk budgets | Keep game code out of shared app chunks. The budget script grants the 450 KB vendor budget only to an allowlist, so extend `is_vendor_chunk` to cover the PixiJS chunk or keep it under the 350 KB app budget. |
| Existing `three` dependency                              | Use `three` only for future 3D work; do not add another 3D engine by default.                                                                                                                                  |
| Media policy                                             | Keep committed assets small, reviewed, optimized, and under the 200 KB per-file limit.                                                                                                                         |
| Local-first privacy model                                | Browser saves stay local; no raw prompts, transcripts, commands, private paths, credentials, or logs enter game data.                                                                                          |
| Existing canvas e2e precedent                            | Reuse the memory graph style of Playwright nonblank-canvas verification.                                                                                                                                       |

## Locked Decisions

These choices are accepted for the first implementation:

| Area                  | Decision                                                                        |
| --------------------- | ------------------------------------------------------------------------------- |
| Product name          | `AI Rogue`                                                                      |
| Extension ID          | `ai-rogue`                                                                      |
| Primary currency      | `Insight Shards`                                                                |
| Daily earnings        | Auto-detect claimable earnings, but require a manual claim action.              |
| Progression weighting | Favor completed useful activity and skill/tool diversity over raw spend.        |
| First visual style    | Bespoke pixel art, generated and refined through `imagegen` plus local tooling. |
| Ledger detail         | Include a minimal "why did I earn this?" breakdown in the first Ledger slice.   |

## Modern PixiJS Stack

Use PixiJS v8 as the target renderer family. As of 2026-06-21, PixiJS v8 is the maintained modern major line, with WebGL and optional WebGPU support in the official docs.

Implementation rules:

* Lazy import `pixi.js` only from the mounted game view or runtime module.
* Keep PixiJS out of the extension registry and app shell chunks.
* Use imperative PixiJS ownership for the game loop, containers, sprites, particles, text, and texture lifetime.
* Keep React responsible for routing, menus, coarse game state, forms, and accessible UI outside the canvas.
* Do not move per-frame simulation through React state.
* Use pure TypeScript modules for simulation, economy, world generation, save migration, and deterministic tests.
* Use `@pixi/react` only if a later UI layer clearly benefits from declarative Pixi composition.
* Keep assets small, reviewed, and bundle-budgeted. Prefer compact pixel-art atlases and tiny authored/generated sprites; use procedural shapes only for throwaway renderer diagnostics.
* PixiJS was checked and installed on 2026-06-22 as `pixi.js@8.19.0`. `@pixi/react@8.0.5` was also checked as the current latest tag, but it is not installed for the first runtime shape. `@pixi/react` v8 was rebuilt exclusively for React 19, so it matches this app's React 19 baseline if a later Pixi UI layer justifies it; `@pixi/react` v7 does not run on React 19.
* Default to the WebGL renderer for the first slice. PixiJS v8's auto renderer can select WebGPU, which changes the canvas context type and breaks the WebGL `readPixels` verification reused from the memory graph e2e test.

Default implementation shape:

```
React PlayView
  -> owns the route, menus, settings, accessibility text, and coarse state
  -> mounts a div/canvas host
  -> imports the PixiJS runtime after mount
  -> passes typed snapshots into the game runtime

PixiJS runtime
  -> owns canvas, ticker/frame loop, textures, sprites, particles, and input sampling
  -> emits coarse events back to React: paused, run ended, item selected, save completed, runtime failed
  -> destroys renderer, textures, listeners, workers, and audio nodes on unmount
```

Important references:

* PixiJS v8 docs: <https://pixijs.com/8.x/guides/getting-started/intro>
* PixiJS versions: <https://pixijs.com/versions>
* Extension docs: [`docs/extensions/README_docs-extensions.md`](/ai-os-and-trend-finder-docs/docs/extensions/readme_docs-extensions.md)
* Extension ADR: [`docs/adr/0001-extension-platform-foundation.md`](/ai-os-and-trend-finder-docs/docs/adr/0001-extension-platform-foundation.md)
* Architecture extension platform: [`docs/ARCHITECTURE.md`](/ai-os-and-trend-finder-docs/docs/architecture.md#extension-platform)
* Runtime data contract: [`docs/data-contract.md`](/ai-os-and-trend-finder-docs/docs/data-contract.md)
* Media policy: [`docs/media-policy.md`](/ai-os-and-trend-finder-docs/docs/media-policy.md)
* Bundle budget script: [`scripts/check-bundle-budget.sh`](https://github.com/moshehbenavraham/ai-os/blob/main/scripts/check-bundle-budget.sh)
* Canvas e2e precedent: [`tests/e2e/memory-graph.spec.ts`](https://github.com/moshehbenavraham/ai-os/blob/main/tests/e2e/memory-graph.spec.ts)
* Optional browser APIs: MDN Web Workers, IndexedDB, Web Audio API, Pointer Lock API, and Gamepad API docs.

## Runtime Boundary

Keep the game runtime narrow and disposable:

1. Lazy load the game runtime so the dashboard, extension index, and other extension routes do not pay the game engine cost.
2. Do not import PixiJS, physics engines, audio wrappers, or renderer addons from `src/extensions/registry.ts`.
3. Use type-only imports where possible in extension contracts.
4. Initialize browser-only APIs inside `useEffect` or runtime start functions, not during React render or module evaluation.
5. Pause or throttle the loop when `document.visibilityState` is hidden and when the route unmounts.
6. Respect `prefers-reduced-motion`; lower animation intensity, camera shake, flashing, and particle density.
7. Unregister pointer, keyboard, touch, resize, visibility, and storage listeners on unmount.
8. Avoid trapping page scroll outside the canvas.
9. Keep renderer state, transient frame state, and per-turn simulation state out of React except for throttled, UI-visible summaries.

State ownership:

| State class                     | Owner                                                            |
| ------------------------------- | ---------------------------------------------------------------- |
| Per-frame transient state       | Runtime object owned by the loop.                                |
| Deterministic simulation state  | Pure TypeScript simulation modules.                              |
| UI-visible state                | React state updated at coarse boundaries.                        |
| Tiny preferences                | `localStorage`, versioned and parsed.                            |
| Saves, run history, and ledger  | IndexedDB, versioned and parsed.                                 |
| Optional generated content pack | `LiveData.extensions.items["ai-rogue"].data`, parsed as unknown. |

## Optional Systems Defaults

Do not add these systems until the game proves a need:

| System          | Default                                                          | Add Later When                                                                                                        |
| --------------- | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| Physics         | None. Roguelike grid rules should stay in TypeScript simulation. | Matter.js is useful for light 2D rigid-body behavior; Rapier only if high-performance physics justifies WASM loading. |
| Web Worker      | None. Keep simulation on the main thread first.                  | Profiling shows pathfinding, AI, procedural generation, or asset processing blocks input or rendering.                |
| OffscreenCanvas | Do not use.                                                      | Browser support, test coverage, and deployment constraints are reviewed separately.                                   |
| Audio           | Web Audio API directly, or no audio in the first slice.          | Add a wrapper only when audio state becomes complex enough to justify the dependency.                                 |
| Pointer Lock    | Not baseline.                                                    | A future mode needs mouse-look or first-person style control.                                                         |
| Gamepad         | Not baseline.                                                    | Keyboard/pointer support is stable and controller support has a clear UX target.                                      |

If a worker is added later, keep the protocol typed and render on the main thread:

```
main thread
  -> input snapshot
  -> worker simulation step
  <- world snapshot or patches
  -> renderer interpolation
```

## AI OS Economy Connection

The extension should derive a browser-safe economy snapshot from existing `LiveData` branches:

| Input                      | Use In Game                                                     | Notes                                                           |
| -------------------------- | --------------------------------------------------------------- | --------------------------------------------------------------- |
| `localAgents.usage`        | Daily currency, provider streaks, readiness bonuses             | Prefer this as the provider-neutral source.                     |
| `usage.codexWindow`        | Codex-specific token/cost/session metadata                      | Treat unknown token or pricing values as unavailable, not zero. |
| `modelUsage`               | Model-family flavor, rare material drops, capped spend signal   | Do not expose raw provider details beyond existing labels.      |
| `daily`                    | Calendar-based earning windows and streaks                      | Prevent duplicate redemption by date.                           |
| `activity.runs`            | Run-specific rewards, tool-class bonuses, completed-work events | Use run IDs for idempotency where present.                      |
| `skills.active`            | Skill-linked unlocks, class affinities, relic modifiers         | Reward meaningful skill use, not just installed skill count.    |
| `localAgents.skillSources` | Provider/source readiness and inventory flavor                  | Counts only; no skill body reads.                               |

The first implementation uses one primary currency: `Insight Shards`.

Daily earnings should be auto-detected from the latest browser-safe `LiveData`, but wallet changes require a manual claim action. The claim action should show a compact provenance breakdown before or immediately after the claim so the user can see why the currency was available.

Currency should be earned from this weighted, capped blend:

| Source                            | Weight | Notes                                                                  |
| --------------------------------- | ------ | ---------------------------------------------------------------------- |
| Completed agent runs and sessions | 40%    | Prefer completed, non-error work when status data is present.          |
| Skill usage diversity             | 25%    | Reward meaningful skill use across categories.                         |
| Tool-class diversity              | 20%    | Reward varied productive workflows without reading command bodies.     |
| Capped token or spend signal      | 10%    | Count only browser-safe priced spend or token metadata when available. |
| Provider readiness and streaks    | 5%     | Small bonus for healthy local setup and consistent use.                |

Unknown pricing, unavailable token accounting, example data, or missing provider telemetry should reduce only the unavailable source contribution. It must not penalize the rest of the claim.

Do not make unbounded dollars or tokens the dominant source of progression. The reward model should cap daily earnings, show clear provenance, and favor balanced productive use of AI OS.

## Pixel-Art Asset Direction

AI Rogue should use pixel art from the first playable slice. Do not start with pure geometric placeholder art except for throwaway renderer diagnostics.

Initial asset strategy:

* Use the `imagegen` skill in built-in tool mode for concept sheets, sprite sheets, tiles, item icons, enemy variants, UI embellishments, and promotional key art.
* For project-bound sprites that need transparency, generate on a flat chroma-key background first, then remove the key locally with the installed imagegen helper before committing or wiring assets into PixiJS.
* Move selected final assets into the workspace; never reference assets that only live under `$CODEX_HOME/generated_images`.
* Keep all committed assets within [`docs/media-policy.md`](/ai-os-and-trend-finder-docs/docs/media-policy.md) limits, including the 200 KB maximum per committed asset in `src/assets/`.
* Prefer compact, consistent atlases over many loose large PNGs.
* Use local tools for cleanup and optimization after generation: cropping, alpha validation, palette reduction, nearest-neighbor scaling, atlas packing, WebP/PNG comparison, and asset-size checks.
* Keep the visual target consistent: readable top-down roguelike tiles, compact sprites, limited animation frames, clear silhouettes, and no text baked into gameplay sprites.

First asset set:

| Asset   | Minimum Needed                                           |
| ------- | -------------------------------------------------------- |
| Player  | Idle and move-facing sprite or compact 4-direction set.  |
| Enemies | Two enemy types with clear silhouette differences.       |
| Tiles   | Floor, wall, door, water or hazard, fog/unknown overlay. |
| Items   | `Insight Shards`, health pickup, one upgrade/relic icon. |
| UI      | Small frame, claim/reward icon, run marker, status pips. |

Generated image prompts should be saved or summarized alongside the asset so the style can be reproduced later. License and provenance notes should be kept with committed game art.

## Integration Boundary

Declare extension capabilities honestly. The expected initial capabilities are:

```ts
capabilities: [
  {
    kind: "readGeneratedData",
    reason: "Reads browser-safe AI Rogue content and economy projections from LiveData",
  },
  {
    kind: "localStorage",
    reason: "Stores local game preferences and small save metadata in this browser",
  },
];
```

Add `networkAccess` only if a future collector or client feature actually calls a public network source. The first version should not need client-side network access.

Data flow should stay narrow:

```
LiveData
  -> React view parses browser-safe AI OS telemetry
  -> deriveAiRogueEconomy(liveData)
  -> claimable Insight Shards projection
  -> manual claim writes wallet/ledger to browser storage

browser play session
  -> runtime state in memory
  -> tiny preferences in localStorage
  -> saves, run history, wallet, and ledger in IndexedDB
  -> no browser writes to src/data/live-data.json
```

If generated game content is needed later:

```
optional collector
  -> validates generated browser-safe payload
  -> writes LiveData.extensions.items["ai-rogue"]
  -> React view parses unknown extension data
  -> game runtime receives typed content config
```

Validate that unknown payload with a Zod `parseAiRogueData` helper in the client before the runtime consumes it, following the `parse<Ext>Data` pattern in the extension README.

## Persistence

Use browser-local persistence for game state:

* `localStorage` for tiny preferences and feature flags.
* IndexedDB for saves, run history, economy ledger, and larger unlock state.
* Version every save and ledger schema with Zod.
* Store redeemed earning events by stable keys such as date, provider, and activity run ID to prevent double-crediting after refreshes.
* Keep generated private runtime data out of committed files.

The game can read `LiveData`, but normal play state should not write to `src/data/live-data.json`.

## Reference Repositories

The old example codebases are references, not foundations:

| Repo                   | Use For                                                                                                                                                                                    | Do Not Use For                                                                                                                        |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| `EXAMPLES/Rotten-Soup` | Larger roguelike feature inventory: generated maps, FOV, minimap, combat, inventory, equipment, ranged/magic targeting, goal-based AI, NPC dialogue, and quest patterns.                   | Direct imports, Vue shell, PixiJS 4 patterns, global runtime shape, Tiled/resource-loader assumptions, assets without license review. |
| `EXAMPLES/frogue`      | Compact mechanic ideas: event/system loop shape, directional abilities, room progression, jump mode, tongue/lick raycast, water/gills traversal, poison, bleed, tired, eggs, and powerups. | ClojureScript runtime, PixiJS 5 patterns, wholesale game logic, large media imports.                                                  |

Only pull ideas from these repos when they provide value beyond normal roguelike knowledge. The implementation should be clean TypeScript built for AI OS.

License cautions from the prior research:

* `EXAMPLES/Rotten-Soup` includes a GPLv3 license file.
* `EXAMPLES/frogue` declares Eclipse Public License in `project.clj`; no separate license file was found in that note.
* Treat both as design references unless a later reuse decision receives explicit license review.

## First Playable Slice

The first slice should prove the full loop with minimal content:

1. Env-gated `ai-rogue` extension registered in the host.
2. Lazy-loaded PixiJS canvas that mounts, paints, resizes, and disposes cleanly.
3. Deterministic grid simulation with seed support.
4. Keyboard and pointer controls.
5. Player, walls, doors, three tile types, two enemy types, combat log, health, and turn advancement.
6. Field of view and fog of war.
7. One short dungeon floor with a win condition.
8. Start, pause, reset, and resume controls in React outside the canvas.
9. One small preference stored in `localStorage` through a versioned schema.
10. Economy projection from fixture/live `LiveData`.
11. Currency ledger with capped daily redemption.
12. Minimal claim breakdown explaining why `Insight Shards` were earned.
13. One spendable upgrade that affects a run.
14. First-pass pixel-art assets for the player, two enemies, core tiles, one currency pickup, one relic, and compact UI markers.

Avoid inventory, crafting, NPCs, meta-progression trees, procedural biomes, and large asset packs until this slice is stable.

## Phase Plan

### Phase 0: Direction Lock

* Use `AI Rogue`, `ai-rogue`, and `Insight Shards`.
* Document economy inputs, caps, and the locked source weights before implementation.
* Prepare the first pixel-art prompt set and asset acceptance checklist.
* PixiJS is installed up front as `pixi.js@8.19.0`; implementation must still lazy import it only from the mounted game runtime.

### Phase 1: Extension Shell

* Add `ai-rogue` client extension with Play, Ledger, Loadout, and Settings views.
* Gate it through `VITE_CLAUDE_OS_ENABLED_EXTENSIONS`.
* Add empty, disabled, and missing-data states consistent with current extension patterns.
* Add route tests for registration and default-view redirect.
* Declare only the initial capabilities actually used.

### Phase 2: Game Runtime Spike

* Use the installed PixiJS v8 package.
* Initialize PixiJS with the WebGL renderer and `preserveDrawingBuffer: true` so the `readPixels` canvas check works, or wire a screenshot non-blank fallback.
* Build the lazy runtime boundary and disposal lifecycle.
* Confirm the lazy PixiJS chunk fits the bundle budget; extend `scripts/check-bundle-budget.sh` `is_vendor_chunk` to grant it the 450 KB vendor budget if it exceeds the 350 KB app-chunk budget.
* Add canvas-pixel Playwright coverage for nonblank render, resize, keyboard movement, and route cleanup.
* Add start, pause, reset, and hidden-tab throttling behavior.
* Use throwaway generated or diagnostic art only until the first committed pixel-art set is ready.

### Phase 3: Economy And Ledger

* Build `deriveAiRogueEconomy(liveData)` as a pure, tested transform.
* Add the locked source weights, earning caps, provenance labels, and idempotent redemption keys.
* Add manual claim behavior for `Insight Shards`.
* Render a minimal "why did I earn this?" breakdown for each claim.
* Persist ledger and wallet state locally.
* Add fixture tests covering missing token data, unknown pricing, example data, and repeated redemption attempts.

### Phase 4: First Dungeon Run

* Implement deterministic world generation, FOV, combat, simple enemies, and run completion.
* Connect one loadout upgrade to the wallet.
* Wire the first committed pixel-art player, enemy, tile, currency, relic, and UI assets into the PixiJS runtime.
* Add save/load and reset behavior.
* Add accessibility controls for reduced motion, contrast, input remapping, and pause.

### Phase 5: Progression Depth

* Add skill-linked classes or relics based on `skills.active` and `localAgents.skillSources`.
* Add model-flavored resources from capped `modelUsage` signals.
* Add more enemy behaviors, room modifiers, and run objectives.
* Consider a worker only if simulation cost becomes measurable.

### Phase 6: Content And Polish

* Expand reviewed compact sprite atlases and sound effects.
* Add run history, achievements, and seed sharing.
* Add mobile layout and pointer-first controls.
* Run bundle, asset, type, unit, and browser gates before enabling by default.

## Quality Gates

Before treating the stack as accepted:

* `bun run typecheck`
* `bun run lint` and `bun run format:check`
* focused Vitest coverage for economy, save migration, RNG, simulation, and combat
* Playwright checks for canvas paint, input, resize, mobile framing, reduced motion, and route cleanup
* `bun run build`
* `bun run budget:check`
* `bash scripts/check-asset-sizes.sh`
* `bun run runtime:check-private`

## Testing Strategy

Use focused tests around the highest-risk contracts:

| Risk                                  | Test                                                                      |
| ------------------------------------- | ------------------------------------------------------------------------- |
| Extension registry and view wiring    | Vitest route/registry test.                                               |
| Capability declarations               | Unit or route test confirming only used capabilities are declared.        |
| Unknown `LiveData` and extension data | Zod parser tests.                                                         |
| Economy calculation                   | Pure unit tests for source weights, caps, missing data, and example data. |
| Manual claim idempotency              | Unit tests for repeated claim attempts by date, provider, and run ID.     |
| Save migration                        | Unit tests for versioned preference, wallet, ledger, and save parsers.    |
| Simulation correctness                | Pure TypeScript tests without renderer startup.                           |
| RNG determinism                       | Seeded world-generation and combat tests.                                 |
| Worker protocol, if added             | Unit tests for message schemas and reducer logic.                         |
| Canvas rendering                      | Playwright nonblank canvas pixel check.                                   |
| Interaction                           | Playwright keyboard and pointer smoke tests.                              |
| Mobile layout                         | Playwright mobile viewport screenshot/assertions.                         |
| Reduced motion                        | Playwright or component test for low-motion mode.                         |
| Route cleanup                         | Playwright route-away test for disposed canvas/listeners/ticker.          |
| Bundle size                           | `bun run build` then `bun run budget:check`.                              |
| Asset policy                          | `bash scripts/check-asset-sizes.sh`.                                      |

For canvas verification, reuse the approach from [`tests/e2e/memory-graph.spec.ts`](https://github.com/moshehbenavraham/ai-os/blob/main/tests/e2e/memory-graph.spec.ts): wait for the canvas, read pixels from WebGL, and assert that painted pixels exist. That test reads pixels through `getContext("webgl2"/"webgl", { preserveDrawingBuffer: true })`, so it only works if the PixiJS `Application` is created with the WebGL renderer and `preserveDrawingBuffer: true`. A WebGPU canvas returns `null` for those contexts and fails the check. If WebGPU is adopted later, switch this gate to a Playwright screenshot non-blank assertion instead.

## Non-Goals

* No direct port of Rotten-Soup or Frogue.
* No Phaser, Unity, Godot, or separate embedded game app for the initial plan.
* No separate Vite app or iframe-wrapped game for the initial plan.
* No dynamic executable plugin or mod loading.
* No remote package loading.
* No server-authoritative multiplayer; the current product has no database, auth, session service, or realtime backend for that architecture.
* No raw prompt, transcript, command output, private path, credential, or log exposure.
* No currency model that rewards unlimited token burn.
* No committed large asset packs, unoptimized generated media, or unreviewed third-party art.
* No collector until there is a concrete browser-safe generated-content need.

## Closed Questions

* Product name is `AI Rogue`.
* Extension ID is `ai-rogue`.
* First currency is `Insight Shards`; additional currencies are deferred.
* Daily earnings are detected automatically but claimed manually.
* First-pass source weights are 40% completed agent runs and sessions, 25% skill usage diversity, 20% tool-class diversity, 10% capped token or spend signal, and 5% provider readiness and streaks.
* The first visual style is pixel art generated and refined through `imagegen` plus local asset tooling.
* The first Ledger includes a compact "why did I earn this?" breakdown.
* PixiJS is installed up front as `pixi.js@8.19.0`; `@pixi/react` is not installed for the first runtime shape.
* First-batch prompt set, palette, tile size, animation-frame budget, atlas grouping, and shard treatment are locked in `docs/extensions/ai-rogue/visual-assets.md`.
* `Insight Shards` appear both inside dungeon runs as pickup feedback and in claim or post-run screens as banked rewards.

## Remaining Questions

* None for the first playable slice.


---

# 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/docs/extensions/ai-rogue/plan-2026-06-21.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.
