feat: spirit engine — seance WS, entity minting/Codex, Piper TTS voices, wire telemetry

- WS /ws/session: modes, summon, anomaly fragments, streaming direct contact,
  passive wire-ghost ambient loop, per-user rate limits, event transcript
- entities: anomaly-signature fingerprinting, LLM minting + procedural
  fallback, Codex matching with contact counts and sightings
- tts: 8 local Piper voices (EN/ES), per-entity voice profiles, numpy
  effects chain (pitch/rate/bitcrush/echo/static)
- llm: streaming client, submit_stream in bounded queue, SpiritService
  with offline fallbacks for every channel
- routes: public /api/codex, /api/codex/{id}, /api/stats; /audio static mount
- models: Entity, EntitySighting, Event, ContactSession(entity_id, language)
This commit is contained in:
Indiana
2026-07-20 20:13:28 +00:00
parent 52afad1ad5
commit b9110f45de
28 changed files with 1997 additions and 4 deletions

View File

@@ -0,0 +1,177 @@
import asyncio
import pytest
from sqlalchemy import select
import app.ws
from app.entities import fallback_profile
from app.models.contact_session import ContactSession
from app.models.event import Event
class FakeSpiritService:
async def mint_profile(self, signature, channel, anomalies, language="en"):
return fallback_profile(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():
for token in ["I ", "am ", "here."]:
yield token
return gen()
def ambient_ready(self):
return False
async def _fake_synth(text, voice, profile):
return b"RIFFfake wav bytes"
@pytest.fixture(autouse=True)
def _fake_spirits(monkeypatch):
monkeypatch.setattr(app.ws, "spirit_service", FakeSpiritService())
monkeypatch.setattr(app.ws, "synthesize_spirit_voice", _fake_synth)
def _read_until(ws, msg_type, max_frames=30, **match):
for _ in range(max_frames):
frame = ws.receive_json()
if frame.get("type") != msg_type:
continue
if all(frame.get(key) == value for key, value in match.items()):
return frame
raise AssertionError(f"never saw frame of type {msg_type!r} matching {match!r}")
def _login(sync_client, username="wsmedium"):
sync_client.post("/auth/register", json={"username": username, "password": "spookyspooky"})
sync_client.post("/auth/login", json={"username": username, "password": "spookyspooky"})
return sync_client.cookies.get("qm_session")
def _ws_connect(sync_client, token):
# TestClient upgrades over ws:// (insecure), so the jar withholds the
# Secure qm_session cookie. Pass it explicitly — real browsers on https
# send it on the upgrade automatically.
return sync_client.websocket_connect(
"/ws/session", headers={"cookie": f"qm_session={token}"}
)
def test_websocket_requires_authentication(sync_client):
with pytest.raises(Exception):
with sync_client.websocket_connect("/ws/session"):
pass
@pytest.mark.asyncio
async def test_websocket_ping_pong_and_session_lifecycle(sync_client, db_session):
_login(sync_client)
with _ws_connect(sync_client, sync_client.cookies.get("qm_session")) as ws:
_read_until(ws, "session")
ws.send_json({"type": "ping"})
assert _read_until(ws, "pong") == {"type": "pong"}
sessions = (await db_session.execute(select(ContactSession))).scalars().all()
assert len(sessions) == 1
assert sessions[0].ended_at is None
# The server marks the session ended in its disconnect handler; give the
# portal loop a moment to commit before asserting.
for _ in range(40):
await asyncio.sleep(0.05)
db_session.expire_all()
sessions = (await db_session.execute(select(ContactSession))).scalars().all()
if sessions[0].ended_at is not None:
break
assert sessions[0].ended_at is not None
@pytest.mark.asyncio
async def test_summon_mints_entity_and_greets(sync_client, db_session):
_login(sync_client, "summoner")
with _ws_connect(sync_client, sync_client.cookies.get("qm_session")) as ws:
_read_until(ws, "session")
ws.send_json({"type": "summon"})
entity_frame = _read_until(ws, "entity")
assert entity_frame["is_new"] is True
assert entity_frame["entity"]["name"]
assert entity_frame["entity"]["rarity"] in ("common", "uncommon", "rare", "mythic")
assert entity_frame["entity"]["voice"]["voice_id"]
greeting = _read_until(ws, "utterance")
assert greeting["kind"] == "greeting"
assert greeting["text"]
sessions = (await db_session.execute(select(ContactSession))).scalars().all()
assert sessions[0].entity_id is not None
@pytest.mark.asyncio
async def test_question_streams_reply_and_records_history(sync_client, db_session):
_login(sync_client, "seeker")
with _ws_connect(sync_client, sync_client.cookies.get("qm_session")) as ws:
_read_until(ws, "session")
ws.send_json({"type": "question", "text": "Are you at peace?"})
_read_until(ws, "entity") # auto-summoned before answering
_read_until(ws, "reply_start")
reply_end = _read_until(ws, "reply_end")
assert reply_end["text"] == "I am here."
events = (await db_session.execute(select(Event).order_by(Event.created_at))).scalars().all()
kinds = [event.kind for event in events]
assert "question" in kinds
assert "reply" in kinds
reply_event = next(event for event in events if event.kind == "reply")
assert reply_event.text == "I am here."
@pytest.mark.asyncio
async def test_anomalies_attune_then_produce_fragments(sync_client):
_login(sync_client, "listener")
with _ws_connect(sync_client, sync_client.cookies.get("qm_session")) as ws:
_read_until(ws, "session")
for i in range(3):
ws.send_json(
{"type": "anomaly", "source": "radio", "frequency": 101.1 + i, "magnitude": 6.5}
)
entity_frame = _read_until(ws, "entity")
assert entity_frame["is_new"] is True
ws.send_json({"type": "anomaly", "source": "radio", "frequency": 104.0, "magnitude": 7.1})
fragment = _read_until(ws, "utterance", kind="fragment")
assert fragment["text"] == "listen"
@pytest.mark.asyncio
async def test_same_signature_recontacts_same_entity(sync_client):
_login(sync_client, "mediumx")
anomalies = [
{"type": "anomaly", "source": "radio", "frequency": 101.0 + i, "magnitude": 5.0 + i}
for i in range(4)
]
with _ws_connect(sync_client, sync_client.cookies.get("qm_session")) as ws:
_read_until(ws, "session")
for anomaly in anomalies:
ws.send_json(anomaly)
first = _read_until(ws, "entity")["entity"]["name"]
with _ws_connect(sync_client, sync_client.cookies.get("qm_session")) as ws:
_read_until(ws, "session")
for anomaly in anomalies:
ws.send_json(anomaly)
second_frame = _read_until(ws, "entity")
assert second_frame["entity"]["name"] == first
assert second_frame["is_new"] is False
assert second_frame["entity"]["contact_count"] == 2