> 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/phase35-session05-persistence-schema-contracts/spec.md).

# Session Specification

**Session ID**: `phase35-session05-persistence-schema-contracts` **Phase**: 35 - AI Rogue Audit Hardening And Refactor **Status**: Not Started **Created**: 2026-06-26

***

## 1. Session Overview

This session stabilizes the remaining AI Rogue persistence and schema contracts before the later Phase 35 module-split sessions. Sessions 01 and 02 already confirmed the original AR-D5 claim and durable hydration blockers are fixed, while Session 04 routed browser storage quota and blocked IndexedDB coverage forward to this session.

The work keeps AI Rogue production-enabled, browser-local, and static-demo safe while hardening wallet, ledger, save-slot, reset, claim idempotency, and durable saved-run conversion behavior. The main code risk is not broad new functionality; it is preventing schema-owned boundaries from drifting while removing confusing durable-vs-live runtime snapshot naming.

The session is next because Phase 35 sessions 06-08 refactor simulation, renderer, React bridge, world, and type ownership. Those refactors should start only after persistence contracts and failure-path coverage are explicit.

***

## 2. Objectives

1. Make durable saved-run schema names distinct from live runtime snapshot types and keep durable-to-runtime conversion behind named helpers.
2. Preserve and deepen schema-owned claim normalization before wallet and ledger mutation, including idempotency and rollback behavior.
3. Add focused tests for migration/defaults, save/load conversion, reset compensation, storage failures, and feasible blocked or quota IndexedDB paths.
4. Record any remaining `save-schema.ts` and `persistence.ts` split recommendations without changing AI Rogue storage scope.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase35-session01-rebaseline-audit-evidence` - Reconciled live findings, classified AR-D5-001 and AR-D5-002 as fixed, and routed storage caveats to Session 05.
* [x] `phase35-session02-fixed-blocker-regression-coverage` - Verified direct oversized claim rejection and durable saved-run hydration coverage.
* [x] `phase35-session03-runtime-accessibility-controls` - Preserved runtime load/reset product states and mobile route coverage that persistence changes must not regress.
* [x] `phase35-session04-renderer-robustness-and-scheduling` - Routed browser storage quota and blocked IndexedDB coverage to this session.

### Required Tools Or Knowledge

* Bun, Vitest, Playwright, TypeScript, Zod, browser localStorage, IndexedDB.
* Current AI Rogue persistence files under `src/extensions/ai-rogue/`.
* Existing AI Rogue browser specs under `tests/e2e/`.

### Environment Requirements

* Run from the repository root with Bun dependencies installed.
* Browser tests require the existing Playwright Chromium setup.
* Preserve the current no-new-D3 boundary: no hosted persistence, no collectors, no analytics, no Pages Functions, and no public-demo bridge requests.

***

## 4. Scope

### In Scope (MVP)

* AI Rogue players can claim daily shards only through schema-owned claim parsing before wallet and ledger writes - keep `normalizeAiRogueClaimEntry` and persistence transactions as the write boundary.
* AI Rogue players can save and load local runs through durable saved-run helpers - remove or replace confusing durable/live snapshot schema aliases and cover malformed, empty, and ready states.
* AI Rogue players can reset local game state safely - preserve scoped localStorage cleanup, IndexedDB clearing, and compensation on reset failure.
* Operators can trust storage failure behavior - add focused unavailable, read-failed, blocked, quota, or source-inspection coverage where feasible.
* Maintainers can continue Phase 35 refactors with clear follow-ups - record file-size and ownership split recommendations for `save-schema.ts` and `persistence.ts`.

### Out Of Scope (Deferred)

* Hosted persistence, remote sync, account-backed saves, or cloud save slots - Reason: Phase 35 preserves browser-local AI Rogue state.
* New AI Rogue economy rules, new rewards, or expanded game content - Reason: this session hardens existing persistence contracts only.
* Broad `save-schema.ts` or `persistence.ts` module extraction - Reason: later Phase 35 refactor sessions own larger module splits after contracts are protected.
* Public-demo deployment or final release gate reruns - Reason: Session 10 owns the full release matrix.

### Product And Debug Surfaces

* Product surfaces: AI Rogue Play save/load/reset states, Ledger claim state, Loadout wallet-backed upgrade state, and Settings reset state.
* Debug or admin surfaces: none required. Diagnostics belong in tests, implementation notes, or validation evidence.

***

## 5. Technical Approach

### Architecture

Keep the current Zod schema ownership model and IndexedDB adapter boundary. `economy-schema.ts` owns claim parsing, `save-schema.ts` owns durable save and wallet/ledger schemas plus durable-to-runtime hydration, `persistence.ts` owns localStorage and IndexedDB transactions, `claim-store.ts` bridges the legacy claim guard into durable persistence, and `runtime-canvas.tsx` consumes only a durable saved-run payload through the hydration helper.

The implementation should avoid a broad persistence rewrite. The safest path is to replace confusing durable/live snapshot aliases with explicit durable names, add narrow helper functions if the current exports are too easy to misuse, then deepen tests around existing behavior. Storage quota or blocked IndexedDB coverage should use local fake adapters or browser harnesses where reliable; if real browser quota simulation is not stable, record the exact source-inspection caveat in implementation notes.

### Design Patterns

* Schema-owned entry points: all persisted records parse through Zod schemas before storage mutation.
* Transaction boundary at the closest write: claim, upgrade, run-summary, and reset writes stay inside IndexedDB adapter methods or persistence helpers.
* Product-facing failure states: UI load/reset errors use stable player-facing messages and keep diagnostics in tests or implementation notes.
* Additive compatibility: stale or malformed saved records fall back to safe defaults without leaking private fields into browser-visible state.

***

## 6. Deliverables

### Files To Create

| File                                                                                        | Purpose                                                                              | Est. Lines |
| ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ---------- |
| `.spec_system/specs/phase35-session05-persistence-schema-contracts/implementation-notes.md` | Session evidence ledger, storage caveats, command results, and split recommendations | \~350      |

### Files To Modify

| File                                                        | Changes                                                                                                                                         | Est. Lines |
| ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/save-schema.ts`                    | Clarify durable saved-run schema exports, remove or deprecate confusing runtime snapshot aliasing, and keep hydration helper ownership explicit | \~90       |
| `src/extensions/ai-rogue/persistence.ts`                    | Harden claim, reset, read/write, and IndexedDB failure mapping where gaps remain                                                                | \~80       |
| `src/extensions/ai-rogue/claim-store.ts`                    | Preserve normalized durable claim bridge and legacy rollback behavior if tests expose drift                                                     | \~40       |
| `src/extensions/ai-rogue/views/runtime-canvas.tsx`          | Ensure load/reset paths consume durable snapshots through the schema-owned helper with product-facing error states                              | \~35       |
| `src/extensions/ai-rogue/__tests__/save-schema.test.ts`     | Cover durable snapshot naming, hydration, defaults, malformed slots, and legacy alias removal                                                   | \~80       |
| `src/extensions/ai-rogue/__tests__/persistence.test.ts`     | Cover claim parity, reset compensation, storage failure, quota/blocked adapters, and migration behavior                                         | \~110      |
| `src/extensions/ai-rogue/__tests__/claim-store.test.ts`     | Cover durable bridge rollback, invalid entries, duplicate claims, and legacy guard state                                                        | \~50       |
| `src/extensions/ai-rogue/__tests__/runtime-canvas.test.tsx` | Cover ready, empty, malformed, and failed durable saved-run load states                                                                         | \~70       |
| `tests/e2e/ai-rogue-persistence.spec.ts`                    | Verify end-to-end preferences, claims, save readiness, reset scope, and storage privacy behavior                                                | \~60       |
| `tests/e2e/ai-rogue-ledger.spec.ts`                         | Verify claim idempotency and wallet/ledger parity through browser IndexedDB                                                                     | \~35       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Direct oversized claims cannot write inconsistent wallet and ledger records.
* [ ] Duplicate claims remain idempotent across legacy guard and durable IndexedDB writes.
* [ ] Durable saved-run schemas and live runtime snapshot types have distinct names or explicitly documented compatibility exports.
* [ ] Durable saved-run hydration handles ready, empty, malformed, and unsafe snapshots through schema-owned helpers.
* [ ] Reset failures compensate localStorage when IndexedDB reset fails.
* [ ] Storage unavailable, read-failed, blocked, and quota-like paths are covered or explicitly caveated with source evidence.

### Testing Requirements

* [ ] Focused AI Rogue unit tests written and passing.
* [ ] Focused AI Rogue Playwright persistence and ledger specs passing.
* [ ] Verification scenarios completed for claim, save/load, reset, and storage failure behavior.

### Non-Functional Requirements

* [ ] No hosted persistence, collectors, analytics, Functions, remote game content, or public-demo bridge requests added.
* [ ] Browser-visible state contains no raw prompts, provider bodies, private paths, credentials, source dumps, or raw telemetry.
* [ ] Existing bundle and asset posture is not worsened by new dependencies or assets.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] Primary user-facing surfaces contain product-facing copy only.

***

## 8. Implementation Notes

### Working Assumptions

* AR-D5-001 and AR-D5-002 are fixed contracts to preserve rather than live blockers to re-solve: Session 01 classified both as fixed, and Session 02 validated direct oversized claim rejection plus durable saved-run hydration. Planning can proceed because the next work is hardening and naming cleanup around the same source paths.
* The concrete durable/live snapshot naming target is in `save-schema.ts`: current source exports `aiRogueRuntimeSnapshotSchema` as an alias of `aiRogueDurableRuntimeSnapshotSchema`, and the current test asserts that alias. Planning can proceed because the alias is repo-local and unused outside `save-schema.test.ts`.
* Blocked or quota IndexedDB behavior should be covered with fake adapters or a reliable browser harness where feasible: Sessions 01 and 04 route that AR-D8-002 storage caveat to Session 05, while current tests already cover unavailable and read-failed states. Planning can proceed because a documented source-inspection caveat is acceptable only if browser simulation is unstable.

### Conflict Resolutions

* The Session 05 stub lists Session 01 and 02 prerequisites as unchecked, but the analyzer and Phase 35 PRD show Sessions 01-04 complete on 2026-06-26. The analyzer is authoritative for workflow state, so Session 05 is executable now.
* The master PRD phase table still labels Phase 35 as Not Started while the analyzer and Phase 35 PRD record 4/10 sessions complete. The chosen interpretation is that Phase 35 is in progress because deterministic state and phase-local artifacts are newer and more specific.

### Key Considerations

* Keep AI Rogue browser-local state and static public demo boundaries intact.
* Prefer focused tests and narrow helper changes over broad module extraction.
* Treat storage failure messages as product-facing in UI and diagnostics-only in tests or notes.
* Do not add dependencies, assets, remote calls, or environment requirements.

### Potential Challenges

* Browser quota simulation can be flaky: Prefer deterministic fake adapter coverage and record an explicit caveat if real Chromium quota behavior cannot be made reliable.
* Large files make ownership drift easy: Keep changes narrow and document split recommendations instead of extracting broad modules in this session.
* Snapshot names overlap across runtime and durable schemas: Rename or remove repo-local aliases carefully and update tests before changing consumers.

### Relevant Considerations

* \[P34] **AI Rogue is production default-enabled**: Preserve default visibility and the explicit `VITE_CLAUDE_OS_ENABLED_EXTENSIONS=none` disable path.
* \[P31-P34] **Pages and AI Rogue CI guards deferred**: Keep manual Pages and AI Rogue privacy gates in mind, but do not widen scope into release gating.
* \[P30/P32/P34] **Schema-backed browser-local state works**: Preserve Zod defaults, migrations, claim parsing, and durable hydration helpers.
* \[P02/P34] **Zod schemas with owned entry points**: Additive defaults and schema-owned helpers should remain the persistence boundary.
* \[P31-P34] **Do not let public demo become live runtime**: Do not add bridge calls, hosted writes, Functions, collectors, or public AI Rogue storage.
* \[P30/P32/P34] **Do not widen AI Rogue capabilities without review**: Collectors, WebGPU, workers, remote loading, hosted writes, and expanded content remain out of scope.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Write paths can partially mutate wallet, ledger, or localStorage if failures are not transaction-bound or compensated.
* Storage unavailable, blocked, or quota states can collapse into generic runtime failures instead of stable product-facing states.
* Durable saved-run payloads can be confused with live runtime snapshots unless types and helper names make the boundary explicit.

***

## 9. Testing Strategy

### Unit Tests

* `src/extensions/ai-rogue/__tests__/save-schema.test.ts`: durable snapshot naming, hydration helper, malformed and empty saved-run snapshots, migration defaults, and private-field rejection.
* `src/extensions/ai-rogue/__tests__/persistence.test.ts`: claim parity, duplicate idempotency, transaction rollback, reset compensation, storage unavailable/read-failed, and quota/blocked adapter coverage.
* `src/extensions/ai-rogue/__tests__/claim-store.test.ts`: legacy claim guard, durable write rollback, duplicate claims, and invalid oversized entries.
* `src/extensions/ai-rogue/__tests__/runtime-canvas.test.tsx`: ready, empty, malformed, and failed durable load product states.

### Integration Tests

* `tests/e2e/ai-rogue-persistence.spec.ts`: preferences, claims, save readiness, reset scope, private-field absence, and durable IndexedDB state.
* `tests/e2e/ai-rogue-ledger.spec.ts`: claim-once behavior and wallet/ledger parity after refresh.

### Runtime Verification

* Run focused Vitest files for save-schema, persistence, claim-store, and runtime-canvas.
* Run focused Playwright specs for AI Rogue persistence and ledger.
* Run `bun run typecheck`, `bun run lint`, `bun run format:check`, and targeted privacy/source scans if persistence code changes touch browser storage boundaries.

### Edge Cases

* Oversized direct claim amount such as 250.
* Duplicate claim with a different amount and the same redemption key.
* Legacy claim storage write succeeds but durable persistence fails.
* IndexedDB unavailable, read-failed, blocked, quota-like, or reset-failed behavior.
* Empty, malformed, unsafe, future-version, and ready durable saved-run snapshots.
* Reset removes only AI Rogue localStorage keys and IndexedDB stores while preserving unrelated browser storage.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase35-session01-rebaseline-audit-evidence`, `phase35-session02-fixed-blocker-regression-coverage`, `phase35-session03-runtime-accessibility-controls`, `phase35-session04-renderer-robustness-and-scheduling`
* Depended by: `phase35-session06-simulation-ownership-refactor`, `phase35-session07-renderer-and-react-bridge-refactor`, `phase35-session08-world-types-and-fixture-cleanup`, `phase35-session09-documentation-and-media-policy-sync`, `phase35-session10-final-release-gate`

***

## 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/phase35-session05-persistence-schema-contracts/spec.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
