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

# Session Specification

**Session ID**: `phase34-session06-persistence-schema-contracts` **Phase**: 34 - AI Rogue Audit Remediation **Status**: Not Started **Created**: 2026-06-26

***

## 1. Session Overview

This session makes AI Rogue durable claim and saved-run contracts explicitly schema-owned. It is next because the analysis script reported Phase 34 active, no current session, and Sessions 01 through 05 completed, leaving Session 06 as the first unfinished candidate.

The work fixes the AR-D5 persistence findings captured in the Phase 34 stub: direct durable claims must not bypass `aiRogueClaimEntrySchema`, and saved-run snapshots must no longer be easy to confuse with live runtime controller snapshots. The implementation should preserve the browser-local localStorage and IndexedDB posture while reducing future refactor ambiguity.

The session is intentionally not a UI feature session. Product behavior should stay stable, save/load controls should keep their current loading and error paths, and public-demo safety must remain static and local-only.

***

## 2. Objectives

1. Normalize every durable AI Rogue claim write through the existing claim entry schema.
2. Prevent direct oversized claims from producing wallet and ledger amount mismatch.
3. Rename durable saved-run snapshot contracts so they are distinct from live runtime controller snapshots.
4. Add a schema-owned durable-to-runtime hydration helper and replace bridge casts with that helper.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase30-session05-persistence-and-save-contracts` - Provides the original browser-local localStorage and IndexedDB save, wallet, ledger, run-history, and save-slot contracts.
* [x] `phase34-session01-characterization-test-harness` - Provides direct oversized claim and durable saved-run characterization coverage.
* [x] `phase34-session05-runtime-api-ownership` - Provides the narrowed runtime mount boundary that this session should preserve.

### Required Tools Or Knowledge

* AI Rogue claim entry schema in `src/extensions/ai-rogue/economy-schema.ts`.
* Browser-local IndexedDB and localStorage persistence in `src/extensions/ai-rogue/persistence.ts`.
* Save-slot and runtime snapshot Zod schemas in `src/extensions/ai-rogue/save-schema.ts`.
* Runtime save/load bridge behavior 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, database server, SQL migration, remote loading, hosted writes, collectors, analytics, or Cloudflare dashboard actions are required.
* AI Rogue state remains browser-local through localStorage and IndexedDB.

***

## 4. Scope

### In Scope (MVP)

* AI Rogue direct durable claim writes parse through `aiRogueClaimEntrySchema` or a schema-owned normalization helper before wallet and ledger writes.
* Oversized direct claims fail validation or normalize consistently so wallet balance, ledger amount, and ledger `balanceAfter` cannot disagree.
* Legacy localStorage claim migration keeps using schema-valid entries and preserves idempotent duplicate handling.
* Durable saved-run snapshot schema, type names, and helper names make the durable save-slot contract distinct from live runtime controller snapshots.
* Runtime Canvas load paths use a schema-owned durable-to-runtime helper rather than casting durable `runState` back into runtime payload types.
* Focused tests cover direct claim normalization, legacy migration, durable saved-run hydration, unsafe text rejection, and bridge load behavior.

### Out Of Scope (Deferred)

* IndexedDB adapter rewrite - Reason: this session only tightens current browser-local contracts and transaction behavior.
* New wallet, economy, or shard cap rules - Reason: the goal is to enforce the existing 100-shard daily cap contract consistently.
* New save-slot UI or public product copy - Reason: runtime controls should keep their existing product surface.
* Render-model hot-loop caching or audio documentation reconciliation - Reason: assigned to Phase 34 Session 07.
* Default enablement decision or full closeout gate evidence - Reason: assigned to Phase 34 Session 08.

***

## 5. Technical Approach

### Architecture

Use the existing `aiRogueClaimEntrySchema` as the authoritative durable claim contract. `recordAiRogueClaim` should accept only schema-valid claim entries, return explicit validation failures for invalid direct input, and pass the normalized claim into the existing IndexedDB transaction. This keeps wallet and ledger writes inside the current transaction boundary while closing the custom validation drift that allowed an amount above the daily cap.

In `save-schema.ts`, rename the durable save-slot snapshot contract to a durable-specific name such as `aiRogueDurableRuntimeSnapshotSchema` and `AiRogueDurableRuntimeSnapshot`. Keep compatibility aliases only where needed to avoid broad churn. Add a schema-owned helper that converts a parsed durable snapshot into `AiRogueRuntimeSavePayload`, including metadata fallback and explicit errors for empty or malformed saved runs.

Update Runtime Canvas to import the durable snapshot type and hydration helper from `save-schema.ts`. The bridge should keep its duplicate-trigger prevention, loading state, error state, and current product copy, but the durable-to-live conversion should live with the schema that owns the persisted shape.

### Design Patterns

* Schema-owned persistence contracts: Zod schemas own accepted durable shape, defaults, and validation failures.
* Browser-local transaction boundary: wallet and ledger writes stay in one IndexedDB transaction with compensation in localStorage callers where already present.
* Durable/live type split: saved-run data and mounted runtime snapshots use distinct names so future refactors cannot accidentally mix contracts.
* Compatibility aliases: retain old exports only as a narrow migration aid when tests or callers still need a temporary import surface.

***

## 6. Deliverables

### Files To Create

| File                                                                                        | Purpose                                                     | Est. Lines |
| ------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | ---------- |
| `.spec_system/specs/phase34-session06-persistence-schema-contracts/implementation-notes.md` | Session notes, AR-D5 evidence, decisions, and gate results. | \~170      |

### Files To Modify

| File                                                        | Changes                                                                        | Est. Lines |
| ----------------------------------------------------------- | ------------------------------------------------------------------------------ | ---------- |
| `src/extensions/ai-rogue/economy-schema.ts`                 | Add or expose schema-owned claim normalization if needed.                      | \~35       |
| `src/extensions/ai-rogue/persistence.ts`                    | Replace custom direct claim validation with schema-owned parsing.              | \~70       |
| `src/extensions/ai-rogue/claim-store.ts`                    | Preserve durable write and legacy guard behavior with normalized claims.       | \~35       |
| `src/extensions/ai-rogue/save-schema.ts`                    | Rename durable snapshot contracts and add durable-to-runtime hydration helper. | \~140      |
| `src/extensions/ai-rogue/views/runtime-canvas.tsx`          | Replace local durable snapshot cast helper with schema-owned hydration.        | \~45       |
| `src/extensions/ai-rogue/use-save-state.ts`                 | Update durable save-slot type imports or helper usage if affected.             | \~25       |
| `src/extensions/ai-rogue/__tests__/persistence.test.ts`     | Update direct claim, duplicate, and migration regression expectations.         | \~90       |
| `src/extensions/ai-rogue/__tests__/save-schema.test.ts`     | Cover durable snapshot naming, hydration, defaults, and unsafe text rejection. | \~110      |
| `src/extensions/ai-rogue/__tests__/runtime-canvas.test.tsx` | Cover bridge load behavior through schema-owned hydration.                     | \~70       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Direct `recordAiRogueClaim` input that exceeds the daily shard cap cannot produce wallet balance, ledger amount, or `balanceAfter` mismatch.
* [ ] Durable claim writes use `aiRogueClaimEntrySchema` or a helper backed by that schema before entering IndexedDB transactions.
* [ ] Legacy claim migration remains idempotent and does not duplicate ledger rows for already claimed redemption keys.
* [ ] Durable saved-run snapshot schema and type names are distinct from live runtime controller snapshot names.
* [ ] Runtime Canvas load uses the schema-owned hydration helper without local casts from durable run state to runtime save payload.

### Testing Requirements

* [ ] Persistence tests cover direct oversized claim rejection or normalization and wallet/ledger consistency.
* [ ] Persistence tests cover duplicate claims and legacy localStorage claim migration after schema-owned parsing.
* [ ] Save-schema tests cover durable saved-run hydration, empty snapshot rejection, metadata fallback, legacy defaults, and unsafe text rejection.
* [ ] Runtime Canvas tests cover save-slot load success and invalid saved-run failure through the shared helper.

### Non-Functional Requirements

* [ ] AI Rogue remains explicit opt-in, browser-local, and static-demo safe.
* [ ] No SQL, hosted database, server persistence, Cloudflare Pages Function, `/__*` bridge call, collector, analytics, remote loading, or dependency change is introduced.
* [ ] Current product-facing save/load copy remains product-facing; diagnostics stay in tests and implementation notes.

### 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/__tests__/persistence.test.ts src/extensions/ai-rogue/__tests__/save-schema.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 06 is the next executable session: the analysis script reported `current_phase` 34, `current_session` null, Sessions 01 through 05 completed, and Session 06 as the first unfinished current-phase candidate. Planning can proceed because Session 06 depends on characterization coverage from Session 01 and browser-local schema contracts from earlier completed AI Rogue sessions.
* 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 database-layer planning rule maps to browser-local persistence here: repo evidence shows AI Rogue uses localStorage and IndexedDB through `save-schema.ts` and `persistence.ts`, not SQL migrations. Schema artifact work and verification therefore belong in those files and focused tests.
* Durable snapshot renaming should preserve compatibility aliases where doing so avoids unrelated churn. Source search shows current callers import `AiRogueRuntimeSnapshot` from `save-schema.ts` and alias it locally in tests and Runtime Canvas, so the safer implementation path is to introduce clearer durable names first and remove ambiguity at touched call sites.

### Conflict Resolutions

* Security posture vs Phase 34 audit blockers: `.spec_system/SECURITY-COMPLIANCE.md` reports no open security findings, while the Phase 34 stub cites AR-D5-001 and AR-D5-002. The selected interpretation is that AR-D5 findings are Phase 34 product quality and default-enablement blockers, not cumulative security findings. The plan therefore fixes the persistence contract while preserving the current clean security posture.

### Key Considerations

* Keep AI Rogue browser-local state and static public-demo safety unchanged.
* Prefer existing schemas and nearby tests over new persistence abstractions.
* Record exact claim and saved-run behavior in implementation notes because Session 08 will need closeout evidence.
* Avoid any new debug surface or user-facing diagnostic copy.

### Potential Challenges

* Existing tests characterize the broken oversized claim behavior: update them to assert the fixed contract while keeping the old risk visible in notes.
* Renaming durable snapshot exports can cause broad import churn: use compatibility aliases and focused touched-call-site updates.
* Hydration helper errors must stay product-safe: map internal failures through existing Runtime Canvas error summaries instead of exposing schema details.

### Relevant Considerations

* \[P30/P32] **AI Rogue default enablement deferred**: This session repairs blockers but must not flip default enablement.
* \[P31-P33] **Pages demo stays static-only**: Persistence changes must not add hosted writes, collectors, analytics, Functions, or `/__*` public-demo calls.
* \[P30/P32] **Schema-backed browser-local state works**: Continue using Zod defaults, migrations, localStorage, and IndexedDB adapters so runtime adapters receive concrete values.
* \[P31-P33] **Public-demo release gates stay bundled**: Any persistence change should leave final privacy, no-bridge, budget, and route smoke proof for Session 08 closeout.

### Behavioral Quality Focus

Checklist active: Yes

Top behavioral risks for this session:

* Durable write drift between schema validation, wallet balance, ledger amount, and legacy migration.
* Save-slot load failures caused by confusing durable snapshots with live runtime controller snapshots.
* Regressing product save/load controls by surfacing internal diagnostics or changing loading/error state behavior.

***

## 9. Testing Strategy

### Unit Tests

* `src/extensions/ai-rogue/__tests__/persistence.test.ts` for direct oversized claim handling, duplicate redemption keys, legacy migration, and wallet/ledger consistency.
* `src/extensions/ai-rogue/__tests__/save-schema.test.ts` for durable snapshot naming, helper hydration, default migration, metadata fallback, and unsafe text rejection.
* `src/extensions/ai-rogue/__tests__/runtime-canvas.test.tsx` for save-slot load success and failure through schema-owned hydration.

### Integration Tests

* `bun run test -- src/extensions/ai-rogue` to cover nearby AI Rogue schema, runtime bridge, persistence, and route tests.

### Runtime Verification

* Use existing Runtime Canvas tests to verify save/load state summaries remain product-facing and no new dev-only UI appears.
* Inspect source diffs for no new remote loading, hosted writes, collectors, analytics, dependencies, or public-demo bridge calls.

### Edge Cases

* Claim amount above `AI_ROGUE_DAILY_SHARD_CAP`.
* Duplicate redemption key after one successful claim.
* Legacy localStorage claim migration into IndexedDB.
* Empty save slot or ready snapshot without `runState`.
* Durable saved-run metadata missing numeric values.
* Unsafe private-looking text in saved-run summary or serialized run state.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase34-session01-characterization-test-harness`, `phase34-session05-runtime-api-ownership`.
* Depended by: `phase34-session08-default-enablement-evidence-closeout`.
* Related follow-up: `phase34-session07-render-performance-and-audio-docs` should avoid changing persistence semantics except where docs mention current IndexedDB behavior.

***

## 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-session06-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.
