> 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/phase30-session04-economy-and-ledger/spec.md).

# Session Specification

**Session ID**: `phase30-session04-economy-and-ledger` **Phase**: 30 - AI Rogue Game Extension **Status**: Not Started **Created**: 2026-06-22

***

## 1. Session Overview

This session turns the AI Rogue Ledger from a readiness shell into a browser-safe `Insight Shards` claim surface. It adds a pure `deriveAiRogueEconomy(liveData)` transform over existing `LiveData` branches, applies the locked 40/25/20/10/5 weighted source model, caps daily earnings, and emits provenance labels that explain every claim without exposing private operator data.

It is next because Sessions 01-03 have locked the AI Rogue product boundary, registered the disabled-first extension shell, and proven the route-lazy PixiJS runtime. The remaining Phase 30 sessions need a deterministic economy contract before persistence, dungeon rewards, spendable upgrades, and progression depth can safely attach to wallet state.

The scope deliberately stops at a minimal browser-local claim ledger. Session 05 still owns IndexedDB persistence, versioned save contracts, broad wallet migration, and reset behavior. Session 04 provides stable redemption keys and a narrow localStorage claimed-key guard so refreshes cannot double-credit the same claim in the interim.

***

## 2. Objectives

1. Add a tested pure economy transform that derives claimable `Insight Shards` from browser-safe `LiveData` without reading raw prompts, commands, logs, private paths, credentials, or transcripts.
2. Apply the locked source blend: completed work 40%, skill usage diversity 25%, tool-class diversity 20%, capped token or spend signal 10%, and readiness or streak bonuses 5%.
3. Treat unavailable pricing, unknown tokens, example data, missing provider telemetry, and partial LiveData as unavailable source contributions rather than penalties against the rest of the claim.
4. Render the Ledger view with claimable shards, daily cap state, manual claim, idempotent redemption keys, and compact "why did I earn this?" provenance.
5. Add focused unit, component, route, and browser coverage for missing data, source weights, repeated claims, refresh behavior, and privacy boundaries.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase30-session01-direction-and-asset-readiness` - Ratified `AI Rogue`, `Insight Shards`, the locked economy weights, asset presentation, and privacy boundary.
* [x] `phase30-session02-extension-shell-and-routes` - Registered the disabled-first AI Rogue extension with Play, Ledger, Loadout, and Settings routes plus `readGeneratedData` and `localStorage` capabilities.
* [x] `phase30-session03-pixijs-runtime-boundary` - Proved the route-lazy runtime boundary and left wallet writes deferred to the Ledger/economy session.

### Required Tools Or Knowledge

* Existing LiveData contract in `src/lib/live-data-types.ts`.
* Runtime loader hooks in `src/lib/use-live-data.ts`.
* Existing AI Rogue shell and Ledger readiness view under `src/extensions/ai-rogue/views/`.
* Existing committed UI atlas metadata under `src/assets/ai-rogue/`.
* Vitest, React Testing Library, and Playwright patterns already used by extension and route tests.

### Environment Requirements

* Bun 1.3.14 project tooling.
* React 19, TanStack Router/Start, Vite 8, Tailwind CSS 4, Zod, Vitest, happy-dom, Playwright, and Chromium.
* Browser localStorage availability for the narrow claimed-key guard.

***

## 4. Scope

### In Scope (MVP)

* AI OS operator can see deterministic claimable `Insight Shards` from current browser-safe local-agent, usage, daily, activity, skill, and model-usage branches - implemented by `deriveAiRogueEconomy(liveData)`.
* AI OS operator can manually claim the current daily reward - implemented by a Ledger action that writes only minimal browser-local claimed-key entries and prevents duplicate triggers while in flight.
* AI OS operator can understand why shards are available - implemented by a compact weighted breakdown with source labels, available/unavailable state, caps, and privacy-safe evidence counts.
* AI Rogue maintainer can rely on stable redemption IDs - implemented with date, provider, activity run ID, and safe fallback source components.
* AI Rogue maintainer can test edge cases - implemented with fixtures for missing telemetry, unknown pricing, example data, repeated claims, and source weight behavior.

### Out Of Scope (Deferred)

* IndexedDB persistence, full wallet schema migration, save files, run history, and reset-all behavior - Reason: Session 05 owns persistence and save contracts.
* Spending currency on upgrades, relics, loadouts, or dungeon rewards - Reason: Session 07 owns wallet-backed upgrade integration.
* New collectors, generated content packs, script writes, network calls, auth, hosted storage, databases, or admin bridges - Reason: Phase 30 keeps AI Rogue client-local and disabled-first.
* Raw prompt, transcript, command body, command output, private path, credential, or log display - Reason: Ledger provenance must remain browser-safe.

***

## 5. Technical Approach

### Architecture

Add economy modules directly under `src/extensions/ai-rogue/` so the transform stays extension-local and testable without React or browser APIs. The schema module should define source weights, daily cap constants, contribution states, claim entries, redemption-key parts, and the public economy snapshot returned by `deriveAiRogueEconomy(liveData)`.

The transform should read only typed `LiveData` branches that are already browser-visible: `localAgents.sessions`, `localAgents.usage`, `localAgents.providers`, `localAgents.skillSources`, `usage.codexWindow`, `modelUsage`, `daily`, `activity.runs`, and `skills.active`. Source readers must sanitize labels, count bounded categories, ignore command bodies and workspace paths, and return unavailable contribution states when source data is missing, example-only, unknown-priced, or not browser-safe enough to score.

Use a narrow `claim-store` helper for Session 04 only. It should store claimed redemption entries in localStorage with schema-validated reads, explicit error mapping, and no raw LiveData payloads. The helper exists to satisfy refresh idempotency until Session 05 formalizes durable wallet, ledger, save, and reset contracts with IndexedDB.

The Ledger view should call the existing LiveData query hook, derive the economy snapshot, read claimed entries, and render an operational UI: claimable amount, claimed state, daily cap, source breakdown, unavailable-source labels, and privacy notes. The manual claim action should be scoped to one click, disable while in flight, roll back display state if localStorage write fails, and keep the button disabled after refresh for already-claimed redemption keys.

### Design Patterns

* Pure transform boundary: economy derivation accepts `LiveData` and returns serializable view data with no browser side effects.
* Source contribution model: each weighted source reports available, unavailable, capped, amount, weight, labels, and a short reason.
* Idempotent local write: manual claim writes a stable key once and handles malformed localStorage records as empty plus warning, not as a crash.
* Privacy-safe projection: provenance displays counts, dates, source categories, provider labels, and cap states only.
* Existing AI Rogue shell: keep Ledger inside `AiRogueViewShell` and reuse the current dense operational card style.

***

## 6. Deliverables

### Files To Create

| File                                                    | Purpose                                                                                         | Est. Lines |
| ------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/economy-schema.ts`             | Economy constants, weights, caps, contribution, claim, and snapshot contracts.                  | \~150      |
| `src/extensions/ai-rogue/economy.ts`                    | Pure `deriveAiRogueEconomy(liveData)` transform and source contribution helpers.                | \~320      |
| `src/extensions/ai-rogue/claim-store.ts`                | Minimal localStorage claimed-key helper with schema-validated reads and explicit write errors.  | \~180      |
| `src/extensions/ai-rogue/views/reward-icon.tsx`         | Small UI-atlas reward icon renderer for Ledger currency visuals.                                | \~110      |
| `src/extensions/ai-rogue/__tests__/economy.test.ts`     | Source weight, cap, missing telemetry, example data, unknown pricing, and redemption-key tests. | \~260      |
| `src/extensions/ai-rogue/__tests__/claim-store.test.ts` | localStorage parse, malformed record, duplicate claim, write failure, and privacy tests.        | \~190      |
| `tests/e2e/ai-rogue-ledger.spec.ts`                     | Browser proof for manual claim, refresh idempotency, and privacy-safe Ledger text.              | \~150      |

### Files To Modify

| File                                                | Changes                                                                     | Est. Lines |
| --------------------------------------------------- | --------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/views/ledger-view.tsx`     | Replace the readiness view with economy, claim, cap, and provenance UI.     | \~260      |
| `src/extensions/ai-rogue/__tests__/client.test.tsx` | Add Ledger claim-state component coverage and import-boundary expectations. | \~100      |
| `src/routes/__tests__/extensions-routes.test.tsx`   | Update AI Rogue Ledger route expectations for claimable and claimed states. | \~70       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `deriveAiRogueEconomy(liveData)` returns deterministic output for the same input snapshot.
* [ ] Locked source weights are applied and visible in the output.
* [ ] Daily claim amount is capped and raw spend or token volume cannot dominate progression.
* [ ] Manual claim creates a stable redemption entry and cannot double-credit the same key after page refresh.
* [ ] Ledger provenance explains each claim with safe counts, labels, and cap states only.

### Testing Requirements

* [ ] Economy unit tests cover source weights, caps, missing data, unknown pricing, example data, repeated redemption keys, and partial telemetry.
* [ ] Claim-store tests cover valid localStorage, malformed localStorage, duplicates, write failure, and privacy-safe stored fields.
* [ ] Ledger component and route tests cover claimable, claimed, empty, error, warning, and disabled extension states.
* [ ] Playwright coverage verifies manual claim and refresh idempotency.

### Non-Functional Requirements

* [ ] No prompts, transcripts, command bodies, command outputs, private paths, credentials, secrets, logs, or raw provider payloads are stored or rendered by the Ledger.
* [ ] Economy transform remains pure and browser-safe.
* [ ] No new network, remote loading, hosted storage, database, admin bridge, collector, worker, audio, or PixiJS import is added by this session.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] Focused Vitest suite passes.
* [ ] Focused Playwright Ledger suite passes.
* [ ] `bun run typecheck` passes or any pre-existing unrelated failure is documented with evidence.

***

## 8. Implementation Notes

### Working Assumptions

* `deriveAiRogueEconomy` should use full `LiveData`, not only `ExtensionViewProps.data`: the Session 04 stub and AI Rogue plan explicitly list host branches such as `localAgents.usage`, `usage.codexWindow`, `modelUsage`, `daily`, `activity.runs`, `skills.active`, and `localAgents.skillSources`; `ExtensionViewProps.data` currently contains only the extension runtime item payload and may remain null.
* The daily cap should start as a 100-shard cap because the locked weights sum to 100 percentage points and no other cap value is specified in the PRD, phase stub, or implementation baseline. Keeping it as an exported constant makes later balance tuning explicit and testable.

### Conflict Resolutions

* Session 04 requires duplicate-credit prevention after refresh, while Session 05 defers IndexedDB persistence. The chosen interpretation is to add a narrow localStorage claimed-key helper in Session 04 because the extension already declares a `localStorage` capability and the Session 04 success criteria need refresh idempotency. Full durable wallet, ledger schema migration, IndexedDB, run history, saves, and reset flows remain Session 05 scope.

### Key Considerations

* The source model must treat missing pricing, unknown tokens, example data, and unavailable provider telemetry as absent contributions, not negative scores.
* `skills.active` may contain command-like fields; Ledger provenance should use safe names, counts, source labels, and categories, not command values.
* `activity.runs` may contain workspace or summary data; scoring can count status, IDs, tool classes, tokens, and cost, but the UI must not render raw summaries or paths.
* The UI-atlas reward icons are safe committed assets and should be used as small visual markers, not as gameplay state.

### Potential Challenges

* Incomplete real LiveData may produce zero claimable shards. Mitigation: render explicit unavailable-source rows and a useful empty state rather than failing the claim UI.
* Browser localStorage may be unavailable or full. Mitigation: map storage errors to an inline warning and do not mutate displayed claimed state unless the write succeeds.
* Existing repo-wide formatting drift may affect broad gates. Mitigation: run focused session checks first and document any unrelated pre-existing failure.

### Relevant Considerations

* \[P02] **Static extension registry requires code changes**: Keep AI Rogue inside the existing static extension model; do not add dynamic loading, remote code, marketplace behavior, or eval.
* \[P02] **Extension payloads and labels stay bounded**: Ledger output must use bounded labels and explicit unavailable/degraded states.
* \[P02] **Zod schemas with `.default()` for safe parsing**: Use schema-backed localStorage parsing so missing or stale claim records fall back safely.
* \[P21] **Claude OAuth material stays script-only**: Token-bearing fields, bearer headers, and credential-shaped strings must not enter browser output or claim-store records.
* \[P27] **Repo-wide formatting drift remains**: Treat broad format drift as a pre-existing housekeeping issue unless Session 04 edits cause new drift.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Manual claim can be triggered repeatedly before storage finishes.
* Claim storage can be malformed, denied, unavailable, or cleared between renders.
* Provenance can accidentally reveal private AI OS context if source readers use raw summaries, commands, workspace paths, or logs.

***

## 9. Testing Strategy

### Unit Tests

* Test `deriveAiRogueEconomy` with real-shaped fixtures for completed work, skill diversity, tool-class diversity, capped spend/tokens, readiness, streaks, missing telemetry, example data, and unknown pricing.
* Test redemption-key stability for date, provider, activity run IDs, and safe fallback source IDs.
* Test localStorage claim-store parsing, duplicate detection, write failure, malformed records, and stored-field privacy.

### Integration Tests

* Test `LedgerView` with ready, disabled, missing, warning, error, claimable, and claimed states.
* Test extension route rendering for `/extensions/ai-rogue/ledger` and ensure unrelated Trend Finder surfaces do not render AI Rogue Ledger UI.

### Runtime Verification

* Run focused Vitest checks: `bun run test -- src/extensions/ai-rogue src/routes/__tests__/extensions-routes.test.tsx`
* Run focused Playwright check: `bunx playwright test tests/e2e/ai-rogue-ledger.spec.ts`
* Run `bun run typecheck` after implementation.

### Edge Cases

* No local-agent sessions, no usage rows, no skills, empty daily array, and extension disabled.
* `isExample: true` data and fallback `DEFAULT_LIVE_DATA`.
* Unknown token/pricing status and null `costUsd`.
* Multiple providers with the same date and one repeated claim key.
* localStorage unavailable, malformed, or throwing on write.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase30-session01-direction-and-asset-readiness`, `phase30-session02-extension-shell-and-routes`, `phase30-session03-pixijs-runtime-boundary`
* Depended by: `phase30-session05-persistence-and-save-contracts`, `phase30-session07-play-runtime-integration`, `phase30-session08-progression-depth`, `phase30-session10-quality-gates-and-enablement`

***

## 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/phase30-session04-economy-and-ledger/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.
