feat: unlocks, inventory items, sigils, drops, and essence (Workstream C)

Implements the backend REST surface and WS wiring for
docs/superpowers/specs/2026-07-23-character-depth-ghost-log-design.md's
Workstream C:

- New models: UnlockRecord (unlocks), InventoryItem (inventory_items),
  Sigil (sigils) — brand-new tables, picked up by main.py's existing
  create_all.
- New app/inventory.py: unlock price table, item drop table/odds,
  essence economy constants, sigil design validation, and an atomic
  (row-locked) purchase_unlock() that guards against double-spend races.
- New app/routes/inventory.py: GET unlocks/items/sigils, POST sigils
  (validates the placeholder {points, rune} shape, points capped at 12),
  POST unlocks/{unlock_key} (402 on insufficient essence, 404 on unknown
  key, idempotent re-buy).
- GET /auth/me now includes unlocks: list[str] and essence: int.
- ws.py: wires essence trickle + item_drop rolls into the one trigger
  point that exists in this worktree today (_handle_summon, covering
  every successful summon plus high-rarity summons); the other two
  contract trigger points (correct judgment, successful ritual) belong
  to Workstream B's not-yet-landed ritual/judgment WS handlers, which
  should call app.inventory's same helpers once they land.
- User.essence: int added (Workstream B owns this column per the spec;
  added here per orchestrator instruction so this workstream is
  independently testable — merge controller reconciles the duplicate
  edit).

Also fast-forwarded this worktree's branch onto master (it had fallen
behind several commits) so the files this workstream depends on
(shop.py, ws.py, entities.py, etc.) were actually present to build
against.

Tests: 109 passed (drop-roll statistical sanity with seeded RNG,
inventory/sigil CRUD, purchase success/insufficient-funds/idempotency/
unknown-key paths, /auth/me shape, ws summon-trickle and item-drop
wiring).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Indiana
2026-07-24 03:02:20 +00:00
parent 6d8c6f2496
commit ff68379772
13 changed files with 1039 additions and 3 deletions

View File

@@ -1,12 +1,16 @@
import asyncio
import uuid
import pytest
from sqlalchemy import select
import app.ws
from app.entities import fallback_profile
from app.inventory import SUMMON_ESSENCE_TRICKLE
from app.models.contact_session import ContactSession
from app.models.event import Event
from app.models.inventory_item import InventoryItem
from app.models.user import User
from app.rate_limit import RateLimiter
@@ -266,3 +270,168 @@ async def test_summon_per_ip_bucket_follows_cf_connecting_ip_not_socket_peer(
# A different visitor IP behind the same tunnel — must not be
# rejected by visitor A's already-spent bucket.
_read_until(ws, "entity")
@pytest.mark.asyncio
async def test_summon_credits_essence_trickle(sync_client, db_session, monkeypatch):
# The module-level summon_ip_limiter/summon_limiter are shared singletons
# that persist real hit counts across every test in this file (they're
# only overridden where a test explicitly monkeypatches them, as earlier
# tests above do) — fresh, generous instances here keep this test from
# depending on how many summons ran before it.
monkeypatch.setattr(app.ws, "summon_ip_limiter", RateLimiter(max_requests=1000, window_seconds=60))
monkeypatch.setattr(app.ws, "summon_limiter", RateLimiter(max_requests=1000, window_seconds=60))
token = _login(sync_client, "trickle-earner")
user_id = uuid.UUID(
sync_client.get("/auth/me", headers={"cookie": f"qm_session={token}"}).json()["id"]
)
with _ws_connect(sync_client, token) as ws:
_read_until(ws, "session")
ws.send_json({"type": "summon"})
_read_until(ws, "entity")
_read_until(ws, "utterance", kind="greeting")
for _ in range(40):
db_session.expire_all()
user = await db_session.get(User, user_id)
if user.essence == SUMMON_ESSENCE_TRICKLE:
break
await asyncio.sleep(0.05)
assert user.essence == SUMMON_ESSENCE_TRICKLE
@pytest.mark.asyncio
async def test_summon_high_rarity_item_drop_is_persisted_and_sent(
sync_client, db_session, monkeypatch
):
# Force a hit so the wiring is exercised deterministically rather than
# relying on the real roll odds (those are covered statistically in
# test_inventory.py).
forced_item = {
"item_type": "curio",
"item_key": "veil_thread",
"payload": {"trigger": "summon_mythic"},
}
monkeypatch.setattr(app.ws, "roll_item_drop", lambda trigger: forced_item)
# See test_summon_credits_essence_trickle above re: why this is reset.
monkeypatch.setattr(app.ws, "summon_ip_limiter", RateLimiter(max_requests=1000, window_seconds=60))
monkeypatch.setattr(app.ws, "summon_limiter", RateLimiter(max_requests=1000, window_seconds=60))
class MythicSpiritService:
async def mint_profile(self, signature, channel, anomalies, language="en"):
profile = fallback_profile(signature)
profile["rarity"] = "mythic"
return profile
async def fragment(self, source, anomaly, language="en"):
return "listen"
async def wire_whisper(self, telemetry, language="en"):
return "the wire hums"
def chat_stream(self, entity, question, history, language="en"):
async def gen():
yield "hi"
return gen()
def ambient_ready(self):
return False
monkeypatch.setattr(app.ws, "spirit_service", MythicSpiritService())
token = _login(sync_client, "jackpot-seeker")
user_id = uuid.UUID(
sync_client.get("/auth/me", headers={"cookie": f"qm_session={token}"}).json()["id"]
)
with _ws_connect(sync_client, token) as ws:
_read_until(ws, "session")
ws.send_json({"type": "summon"})
entity_frame = _read_until(ws, "entity")
assert entity_frame["entity"]["rarity"] == "mythic"
drop_frame = _read_until(ws, "item_drop")
assert drop_frame["item"] == forced_item
for _ in range(40):
db_session.expire_all()
items = (
await db_session.execute(
select(InventoryItem).where(InventoryItem.user_id == user_id)
)
).scalars().all()
if items:
break
await asyncio.sleep(0.05)
assert len(items) == 1
assert items[0].item_key == "veil_thread"
assert items[0].item_type == "curio"
@pytest.mark.asyncio
async def test_summon_common_rarity_does_not_roll_a_drop(sync_client, db_session, monkeypatch):
# See test_summon_credits_essence_trickle above re: why this is reset.
monkeypatch.setattr(app.ws, "summon_ip_limiter", RateLimiter(max_requests=1000, window_seconds=60))
monkeypatch.setattr(app.ws, "summon_limiter", RateLimiter(max_requests=1000, window_seconds=60))
# Common is the overwhelmingly likely fallback rarity (55% weight) but
# not guaranteed — force it explicitly so this test can't flake.
def _common_only(signature: str) -> dict:
profile = fallback_profile(signature)
profile["rarity"] = "common"
return profile
class CommonSpiritService:
async def mint_profile(self, signature, channel, anomalies, language="en"):
return _common_only(signature)
async def fragment(self, source, anomaly, language="en"):
return "listen"
async def wire_whisper(self, telemetry, language="en"):
return "the wire hums"
def chat_stream(self, entity, question, history, language="en"):
async def gen():
yield "hi"
return gen()
def ambient_ready(self):
return False
monkeypatch.setattr(app.ws, "spirit_service", CommonSpiritService())
# If a drop were (incorrectly) rolled for a common-rarity summon, this
# would make it always hit — proving the rarity gate, not just the odds,
# is what's preventing a drop here.
monkeypatch.setattr(
app.ws, "roll_item_drop", lambda trigger: {"item_type": "x", "item_key": "y", "payload": {}}
)
token = _login(sync_client, "commoner")
user_id = uuid.UUID(
sync_client.get("/auth/me", headers={"cookie": f"qm_session={token}"}).json()["id"]
)
with _ws_connect(sync_client, token) as ws:
_read_until(ws, "session")
ws.send_json({"type": "summon"})
entity_frame = _read_until(ws, "entity")
assert entity_frame["entity"]["rarity"] == "common"
greeting = _read_until(ws, "utterance", kind="greeting")
assert greeting["kind"] == "greeting"
# Give the (already-awaited, so this should be immediate) reward path a
# moment to land, then assert no item was ever persisted for this user —
# the rarity gate, not just the roll odds, is what prevents a drop here.
for _ in range(20):
db_session.expire_all()
items = (
await db_session.execute(
select(InventoryItem).where(InventoryItem.user_id == user_id)
)
).scalars().all()
await asyncio.sleep(0.02)
assert items == []