# Hacker Divergents
# Phase 22 — Premium Economy

Status: COMPLETE

---

## 1. Objective

Phase 22 introduces the permanent Premium Economy of Hacker Divergents.

The Premium Economy is intentionally independent from:

- the normal credits economy;
- world rounds;
- rotating virtual IPs;
- temporary competitive progression.

Its permanent premium currency is:

`diamonds`

Diamonds are account-persistent and survive world round rotation.

---

## 2. Economy Separation

Hacker Divergents has two financially distinct in-game economies.

### Credits

Credits belong to the normal game economy.

Authoritative movement service:

`CreditLedgerService`

Credits are used for normal gameplay economy.

### Diamonds

Diamonds belong to the permanent Premium Economy.

Authoritative movement service:

`DiamondLedgerService`

Diamonds are used by the Premium Shop and permanent premium systems.

The Premium module MUST NOT mutate:

`players.credits`

The Premium module MUST NOT use:

`CreditLedgerService`

---

## 3. Round Independence

Premium state is permanent.

The following structures do not belong to a world round:

- diamond_accounts
- diamond_ledger_entries
- premium_entitlements
- premium_catalog_products
- premium_purchases

They contain no operational dependency on:

- world_rounds
- round_public_id
- WorldRoundRotationService

World rotation MUST NOT:

- reset diamonds;
- replace diamond accounts;
- erase diamond ledger history;
- erase premium purchases;
- revoke premium entitlements;
- alter premium purchase state.

This contract was validated through a real WorldRoundRotationService execution inside a caller-owned transaction.

---

## 4. Domain IDs

Premium public identifiers use strict prefixes followed by 32 lowercase hexadecimal characters.

### DiamondAccountId

Prefix:

`dia_`

### DiamondLedgerEntryId

Prefix:

`dle_`

### PremiumEntitlementId

Prefix:

`pen_`

### PremiumCatalogProductId

Prefix:

`pcp_`

### PremiumPurchaseId

Prefix:

`ppr_`

All identifiers support:

- generate
- fromString
- value
- equals
- __toString

Uppercase hexadecimal characters are rejected.

Invalid prefixes and invalid lengths are rejected.

---

## 5. Diamond Accounts

Table:

`diamond_accounts`

Purpose:

Stores the permanent premium account for a player.

Important fields:

- public_id
- player_public_id
- balance_cache
- created_at
- updated_at

Contract:

- exactly one diamond account per player;
- player ownership through players.public_id;
- balance_cache is unsigned;
- balance starts at zero;
- no round_public_id.

`balance_cache` is a performance/cache representation of the ledger-derived balance.

It may only be mutated by:

`DiamondLedgerService`

---

## 6. Diamond Ledger

Table:

`diamond_ledger_entries`

The ledger is the authoritative history of every diamond movement.

Every entry contains:

- public_id
- account_public_id
- direction
- category
- amount
- balance_before
- balance_after
- source_type
- source_public_id
- idempotency_key
- description
- created_at

Directions:

- credit
- debit

The database enforces valid balance equations.

Zero-value movements are forbidden.

Negative balances are forbidden.

Every external movement requires a globally unique idempotency key.

Ledger rows are immutable historical records.

Refunds and reversals create compensating entries instead of deleting original movements.

---

## 7. Diamond Categories

Frozen DiamondCategory contract:

- purchase
- admin_grant
- promotion
- reward
- refund
- spend
- reversal
- adjustment

---

## 8. Diamond Source Types

Frozen DiamondSourceType contract:

- payment
- premium_shop
- admin
- promotion
- event
- system
- refund

---

## 9. DiamondLedgerService

Application service:

`src/Premium/Application/DiamondLedgerService.php`

Responsibilities:

- automatic diamond account creation;
- credit;
- debit;
- current balance;
- ledger history;
- idempotent replay;
- idempotency conflict detection;
- insufficient-balance protection;
- transaction ownership preservation.

The service locks the active player/account during financial movements.

If the caller already owns a transaction, the service MUST NOT commit or rollback that transaction.

It is the only application service allowed to:

- update diamond_accounts.balance_cache;
- insert diamond_ledger_entries.

---

## 10. Administrative Grants

Application service:

`DiamondGrantService`

Operation:

`grantAdministrative`

Administrative grants create:

direction:

`credit`

category:

`admin_grant`

source type:

`admin`

The administrative reference is persisted as source_public_id.

Administrative grants are idempotent.

---

## 11. Premium Spending

Application service:

`DiamondSpendService`

Operation:

`spendPremiumShop`

Premium spending creates:

direction:

`debit`

category:

`spend`

source type:

`premium_shop`

The premium product reference is persisted as source_public_id.

Spending cannot create a negative diamond balance.

---

## 12. Premium Entitlements

Table:

`premium_entitlements`

Entitlements represent permanent premium ownership.

Important fields:

- public_id
- player_public_id
- entitlement_code
- source_type
- source_public_id
- acquired_at
- revoked_at

Uniqueness:

`player_public_id + entitlement_code`

A player therefore has at most one persistent row for an entitlement code.

An entitlement is active when:

`revoked_at IS NULL`

An entitlement may be:

- acquired;
- queried;
- revoked;
- reactivated.

Application authority:

`PremiumEntitlementService`

Only PremiumEntitlementService may mutate premium entitlement records.

---

## 13. Premium Catalog

Table:

`premium_catalog_products`

Important fields:

- public_id
- code
- name
- description
- diamond_price
- entitlement_code
- is_active
- sort_order

Products use diamonds only.

The catalog does not contain:

- credit prices;
- player ownership;
- round ownership.

Inactive products are not purchasable through normal catalog lookup.

Application service:

`PremiumCatalogService`

---

## 14. Premium Purchases

Table:

`premium_purchases`

A premium purchase records a completed permanent transaction.

Important fields:

- public_id
- player_public_id
- product_public_id
- product_code_snapshot
- product_name_snapshot
- entitlement_code_snapshot
- diamond_price_snapshot
- spend_ledger_entry_public_id
- reversal_ledger_entry_public_id
- entitlement_public_id
- idempotency_key
- status
- purchased_at
- reversed_at
- created_at
- updated_at

Purchase statuses:

- completed
- reversed

Historical product information is stored as snapshots.

This guarantees that historical purchases remain understandable even if the catalog later changes.

---

## 15. PremiumPurchaseService

Application service:

`PremiumPurchaseService`

Primary flow:

1. validate request;
2. check purchase idempotency;
3. load active catalog product;
4. prevent duplicate permanent ownership;
5. debit diamonds;
6. acquire entitlement;
7. persist purchase;
8. commit atomically.

The operation is atomic.

Either all of these happen:

- diamond debit;
- entitlement acquisition;
- purchase persistence;

or none of them happen.

A player who already owns the permanent entitlement MUST NOT be charged again.

A repeated request using the same idempotency key returns the original purchase.

Changing the purchase while reusing the same idempotency key produces an idempotency conflict.

---

## 16. Purchase Reversal

Application service:

`PremiumPurchaseReversalService`

A reversal does not delete the original purchase.

Original state:

- diamond debit exists;
- entitlement is active;
- purchase status is completed.

Reversal flow:

1. lock purchase;
2. validate player ownership;
3. detect reversal replay/conflict;
4. create compensating diamond credit;
5. revoke entitlement;
6. link refund ledger entry;
7. change purchase status to reversed;
8. populate reversed_at.

Original spend ledger entry remains unchanged.

Compensating entry:

direction:

`credit`

category:

`refund`

source type:

`refund`

source reference:

original premium purchase public id.

The original spend and refund entries both remain permanently auditable.

---

## 17. Reversal Idempotency

Reversing an already reversed purchase with the same reversal request is an idempotent replay.

No second refund is created.

No second balance credit occurs.

Using a different reversal idempotency request against an already reversed purchase produces:

`premium_reversal_idempotency_conflict`

---

## 18. Transaction Contract

Premium financial services are transaction-aware.

General rule:

If the service opened the transaction:

- it commits on success;
- it rolls back on failure.

If the caller already owns the transaction:

- the service does not commit;
- the service does not rollback the caller's transaction.

This allows premium operations to participate safely in larger atomic workflows.

---

## 19. Authority Boundaries

The Phase 22 structural audit established the following mutation authorities.

### diamond_accounts.balance_cache

Allowed writer:

`DiamondLedgerService`

### diamond_ledger_entries

Allowed creator:

`DiamondLedgerService`

### premium_entitlements

Allowed writer:

`PremiumEntitlementService`

### premium_purchases

Allowed writers:

- PremiumPurchaseService
- PremiumPurchaseReversalService

No other source/application service should bypass these authorities.

---

## 20. Database Migrations

Premium Economy migrations:

### 000159

`create_diamond_accounts.sql`

### 000160

`create_diamond_ledger_entries.sql`

### 000161

`create_premium_entitlements.sql`

### 000162

`create_premium_catalog_products.sql`

### 000163

`create_premium_purchases.sql`

### 000164

`add_reversal_ledger_to_premium_purchases.sql`

All applied migrations are immutable.

Future schema changes MUST use new migration numbers.

---

## 21. Verified Premium Services

Implemented application services:

- DiamondLedgerService
- DiamondGrantService
- DiamondSpendService
- PremiumEntitlementService
- PremiumCatalogService
- PremiumPurchaseService
- PremiumPurchaseReversalService

---

## 22. Final Regression

Official runner:

`scripts/powershell/Test-Phase22PremiumRegression.ps1`

Validated result:

- Passed: 17
- Failed: 0
- Total: 17

The regression covers:

- Premium domain IDs;
- diamond accounts;
- diamond ledger persistence;
- DiamondLedgerService;
- frozen diamond contracts;
- administrative grants;
- premium spending;
- premium entitlement persistence;
- PremiumEntitlementService;
- premium catalog persistence;
- PremiumCatalogService;
- premium purchase persistence;
- PremiumPurchaseService;
- reversal persistence;
- PremiumPurchaseReversalService;
- round isolation;
- structural authority audit.

---

## 23. Structural Audit

Official audit:

`scripts/phase22-premium-audit.php`

Validated authority:

- diamond balance mutations limited to DiamondLedgerService;
- diamond ledger inserts limited to DiamondLedgerService;
- entitlement mutations limited to PremiumEntitlementService;
- purchase mutations limited to purchase services;
- no Premium -> credits economy coupling;
- no Premium -> world round coupling.

Result:

`PHASE 22N1 PREMIUM STRUCTURAL AUDIT: PASS`

---

## 24. Final Phase 22 Contract

The permanent Premium Economy is now composed as follows:

Player
    |
    v
Diamond Account
    |
    v
Diamond Ledger
    |
    +-------------------------+
    |                         |
    v                         v
Admin Grant              Premium Spend
                              |
                              v
                       Premium Purchase
                         /           \
                        v             v
                 Catalog Snapshot   Entitlement
                        |
                        v
                     Reversal
                        |
                        v
               Compensating Refund

The diamond ledger is authoritative for monetary history.

Premium entitlements are authoritative for ownership.

Premium purchases are authoritative for commercial transaction history.

Catalog products define current purchasable offerings.

World rounds do not own or reset Premium state.

---

## 25. Phase 22 Status

PHASE 22A — COMPLETE
PHASE 22B — COMPLETE
PHASE 22C — COMPLETE
PHASE 22D — COMPLETE
PHASE 22E — COMPLETE
PHASE 22F — COMPLETE
PHASE 22G — COMPLETE
PHASE 22H — COMPLETE
PHASE 22I — COMPLETE
PHASE 22J — COMPLETE
PHASE 22K — COMPLETE
PHASE 22L — COMPLETE
PHASE 22M — COMPLETE
PHASE 22N — COMPLETE
PHASE 22Z — COMPLETE

Final status:

`PHASE 22 — PREMIUM ECONOMY: COMPLETE`