"""R4 assembly through the real API: entry chain, activity thread, rituals, sync.""" import json import pytest from conftest import engineering_budget from fastapi.testclient import TestClient from test_api import CREATE, events, turn from test_r2 import LIFE, R2LLM from cybergril.api.app import create_app from cybergril.contracts import LLMDelta from cybergril.life.runtime import LifeConfig from cybergril.think.router import build_router from cybergril.think.scenes import Tier class R4LLM(R2LLM): """R2 fake plus R4 scenes: life results can drive the activity thread.""" def __init__(self): super().__init__() self.life_results = [] self.reach_reply = "刚给窗台的多肉换了位置,想让你也看看那颗新芽。" def queue_life(self, raw): self.life_results.append(raw) async def stream(self, messages, **kwargs): prompt = messages[0].content if "主动留言" in prompt: yield LLMDelta(text=json.dumps({"text": self.reach_reply}, ensure_ascii=False)) yield LLMDelta(done=True, finish_reason="stop") return if "生成此刻真实运行中的一条世界内日常经历" in prompt: raw = self.life_results.pop(0) if self.life_results else LIFE yield LLMDelta(text=json.dumps(raw, ensure_ascii=False)) yield LLMDelta(done=True, finish_reason="stop") return async for delta in super().stream(messages, **kwargs): yield delta def r4_app(tmp_path, *, enabled=True, provider=None, semantic="stub", poll=3600): provider = provider or R4LLM() router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)}, budget=engineering_budget()) app = create_app(db_path=tmp_path / "r4.db", router=router, life_config=LifeConfig(enabled=enabled, poll_seconds=poll), semantic_mode=semantic) return app, provider def test_health_capabilities_report_r4_wiring(tmp_path): app, _ = r4_app(tmp_path) with TestClient(app) as client: health = client.get("/api/health").json() assert health["version"] == "R4-assembly" assert health["backend"]["mood"] is True assert health["backend"]["reach_out"] is True assert health["backend"]["semantic"] is True assert health["backend"]["semantic_backend"] == "stub" assert health["capabilities"]["proactive"] is True assert health["capabilities"]["semantic_memory"] == "stub" def test_entry_chain_create_chat_reopen_same_state(tmp_path): app, provider = r4_app(tmp_path) with TestClient(app) as client: assert client.get("/api/companion").status_code == 404 created = client.post("/api/companion", json={**CREATE, "nickname": "小白", "boundary": "慢慢来"}) assert created.status_code == 201 identity = created.json() assert identity["relation"] == "朋友" assert identity["color"]["pillars"] response = turn(client, "今天面试结束了,等结果呢") assert [e["t"] for e in events(response)] == ["chat.delta", "chat.final"] messages = client.get("/api/messages").json()["messages"] assert [m["role"] for m in messages] == ["user", "companion"] # reopen: fresh client over the same database shows the same state epoch = client.get("/api/health").json()["epoch"] with TestClient(create_app(db_path=tmp_path / "r4.db", router=build_router(providers={t: R4LLM() for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)}), life_config=LifeConfig(enabled=True, poll_seconds=3600), semantic_mode="stub")) as client2: health = client2.get("/api/health").json() assert health["companion_created"] is True assert health["epoch"] == epoch + 1 # restart bumped the epoch messages2 = client2.get("/api/messages").json()["messages"] assert [m["role"] for m in messages2] == ["user", "companion"] assert messages2[0]["text"] == messages[0]["text"] def test_chat_turn_interrupts_activity_and_counts_ritual(tmp_path): app, provider = r4_app(tmp_path) with TestClient(app) as client: client.post("/api/companion", json=CREATE) store = app.state.store with store.conn: # she is in the middle of something store.execute( "INSERT INTO life_activity(title,place,state,started_at) " "VALUES('整理窗台','卧室','active',1)" ) before = app.state.dyad.load().intimacy turn(client, "在忙什么呢") store = app.state.store activity = store.query_one("SELECT * FROM life_activity") assert activity["state"] == "interrupted" and activity["interrupted_at"] assert app.state.dyad.load().intimacy == pytest.approx(before + 0.01) async def test_life_slots_drive_activity_and_mood(tmp_path): # poll is long: only the explicit manual generate() calls below run, no races app, provider = r4_app(tmp_path, poll=3600) with TestClient(app) as client: client.post("/api/companion", json=CREATE) life = app.state.life store = app.state.store # slot 1: she starts an activity; the real event moves her mood provider.queue_life({**LIFE, "activity": {"action": "start", "title": "给旋律换结尾", "place": "窗边沙发"}}) await life.generate("2026-10-26", 0) started = store.query_one("SELECT * FROM life_activity") assert started["state"] == "active" and started["title"] == "给旋律换结尾" assert app.state.mood.state.v != app.state.mood.baseline.v # slot 2: she continues it (same activity row, no second thread) provider.queue_life({**LIFE, "activity": {"action": "continue"}}) await life.generate("2026-10-26", 1) assert store.query_one("SELECT COUNT(*) n FROM life_activity")["n"] == 1 # chat interrupts; slot 3 resumes the same thread; slot 4 finishes it turn(client, "打断你一下") assert store.query_one("SELECT state FROM life_activity")["state"] == "interrupted" provider.queue_life({**LIFE, "activity": {"action": "resume"}}) await life.generate("2026-10-26", 2) row = store.query_one("SELECT * FROM life_activity") assert row["state"] == "active" and row["resume_count"] == 1 provider.queue_life({**LIFE, "activity": {"action": "finish"}}) await life.generate("2026-10-26", 3) assert store.query_one("SELECT state FROM life_activity")["state"] == "finished" # every event-driven change is persisted for restart recovery assert abs(store.last_state()["valence"] - app.state.mood.state.v) < 1e-6 async def test_semantic_recall_rides_into_chat_context(tmp_path): app, provider = r4_app(tmp_path, semantic="stub", poll=3600) with TestClient(app) as client: client.post("/api/companion", json=CREATE) store = app.state.store # an older public turn about the music box, already extracted with store.conn: store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES" "(1,'user','音乐盒的发条要顺时针拧','t-old','sent')") store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES" "(2,'companion','好,我记住发条的方向了','t-old','sent')") semantic = app.state.semantic semantic.enqueue_uncovered() await semantic.tick() assert store.query_one("SELECT state FROM sem_batch")["state"] == "done" turn(client, "音乐盒怎么上发条来着") # the gated recall block (or the FTS twin) reached the model context verbatim sent = " ".join(m.content for m in provider.calls[-1]) assert "发条" in sent def test_proactive_message_record_dto_flag(tmp_path): app, provider = r4_app(tmp_path) with TestClient(app) as client: client.post("/api/companion", json=CREATE) turn(client, "在忙什么呢") # an ordinary exchange first store = app.state.store with store.conn: # a persisted reach-out row exactly as the engine writes it store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status,proactive) " "VALUES(1,'companion','想让你看看窗台的新芽。','reach-1','sent',1)") messages = client.get("/api/messages").json()["messages"] flagged = [m for m in messages if m.get("proactive") is True] assert len(flagged) == 1 and flagged[0]["text"] == "想让你看看窗台的新芽。" ordinary = [m for m in messages if not m.get("proactive")] assert ordinary # normal replies never carry the flag