Files
CyberGril/tests/test_r4_api.py
T
zonggongandmultica-agent 31970c4dd3 HEL-870 assembly: memory/persona/mood/life/proactive-contact joined into one runnable candidate on an additive R4 migration (no existing table or row replaced; no visual changes beyond mechanical proactive flag passthrough) - src/cybergril/memory/semantic.py productizes the audited Mem0 path per plan-next-HEL-869: input-side pre-grouping sends only public rows outbound (user rows always; companion rows only judged+acked with all-told candidates), every batch anchor turn_ids/turn_roles/input_sha256 equals that exact input set, and the read-time gate independently recomputes the fingerprint against the live archive and re-checks every companion row's share state, fail-closed rejecting no_payload/unknown_source/archive_missing/source_mismatch/hit_text_mismatch/anchor_turn_mismatch/role_text_conflict/companion_unshared with honest row_verbatim/row_anchor/batch provenance; main archive chat_message remains the ONLY permanent quote layer; sem_batch/sem_covered carry a lease-recovered idempotent job loop; EmbedLedgerGuard continues the single authoritative embed ledger and with embed_cap=0 (no approved budget) refuses every real embedding so the frozen 498/500 and 39/60 accounts and the HEL-835 gate stay untouched; fixed Mem0 2c81af3 is lazily imported with zero upstream fork, a deterministic stub backend exists for engineering verification and is never claimed semantic; MoodRuntime makes core.mood live (event impulses scaled by bazi strength sensitivity, heartbeat decay, state_snapshot persistence, restart recovery, model sees one word only); DyadRuntime makes the relationship ledger live (completed exchanges are rituals, daily regression, behavior hints stay instructions); life_activity adds start/continue/interrupt/resume/finish continuity across slots and restarts with chat-completion interrupts; reach_out implements the approved R4 scope from character.yaml (>=6h interval, hours 8-23, salience>=0.6, arousal>=0.5, intimacy>=0.4) with traceable already-public bases only, UNIQUE(basis) so restarts and duplicate tasks can never multiply messages, night suppression, absence-rule fail-closed, phi projection, and messages persisted as companion rows (proactive=1) fully synced on reopen; API health reports R4-assembly with per-capability honesty (voice/vision/weather/materials/backup stay false, semantic_memory names its backend); config/semantic.example.yaml sanitized config and docs/runbook-hel870.md (startup, locked deps, health, independent data dir, disable/rollback, experience chain list, budget request, R1-R7 seams); verification: 250 python tests pass on 3.11 venv + requirements.lock (61 new deterministic/fake-provider cases covering every gate negative, restart recovery, dedupe, red line and the full entry chain incl. reopen epoch sync), ruff clean, web typecheck + 42 vitest + build pass with the original author frontend untouched except the one-line proactive passthrough; dual-target requirement checks 4/4 pass vs origin/main and origin/agent/agent/de8874a3803b with handoff-HEL-870.json; zero real model calls, zero embeddings, zero outbound network this card; local unified-instance smoke on port 8360 (stub semantic) serves the built web and reports the life loop waiting; read-only server check recorded in the runbook (existing 8300-8350 services and voice ports observed, end-to-end voice availability NOT verified); not merged, not deployed, no production or shared services touched
Co-authored-by: multica-agent <github@multica.ai>
2026-10-26 21:03:42 +08:00

179 lines
8.8 KiB
Python

"""R4 assembly through the real API: entry chain, activity thread, rituals, sync."""
import json
import pytest
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)})
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