"""R4 reach-out: approved gates, one message per basis ever, absence red line.""" import json from datetime import UTC, datetime import pytest from conftest import engineering_budget from test_api import ControlledLLM from cybergril.config import CharacterConfig, ModelsConfig from cybergril.contracts import LLMDelta from cybergril.core.mood_runtime import MoodRuntime from cybergril.life.persona import Persona from cybergril.life.reach_out import ReachOut from cybergril.memory.store import Store from cybergril.think.router import build_router from cybergril.think.scenes import Tier class ReachLLM(ControlledLLM): def __init__(self, reach_text="刚才整理窗台的时候,忽然想把那盆多肉的新芽拍给你看。"): super().__init__() self.reach_text = reach_text self.reach_calls = [] async def stream(self, messages, **kwargs): if "主动留言" in messages[0].content: self.reach_calls.append(messages) if self.mode == "error": raise OSError("upstream fault") yield LLMDelta(text=json.dumps({"text": self.reach_text}, ensure_ascii=False)) yield LLMDelta(done=True, finish_reason="stop") return async for delta in super().stream(messages, **kwargs): yield delta class Clock: def __init__(self, start): self.now = start def __call__(self): return self.now def advance(self, seconds): self.now += seconds @pytest.fixture def store(tmp_path): s = Store(tmp_path / "reach.db") yield s s.close() BASE = datetime(2026, 10, 25, 16, 0, 0, tzinfo=UTC).timestamp() # 2026-10-26 00:00 in Asia/Shanghai def setup(store, *, hour=10, days_ago=0.0, intimacy=0.5, arousal=(0.7, 0.9), llm=None, salience=0.7, told=True): """One told salient life event, a companion, warm mood, given dyad intimacy. ``hour`` is the local Asia/Shanghai hour the clock starts at. """ clock = Clock(BASE + hour * 3600 - days_ago * 86400) with store.conn: store.execute("INSERT OR IGNORE INTO companion VALUES(1,?)", (json.dumps({"id": "1", "name": "星河", "birth": "2000-10-18", "hour": "亥时", "relation": "朋友", "nickname": "", "boundary": "", "color": {}}, ensure_ascii=False),)) event_ts = int((clock.now - 3600) * 1000) store.execute( "INSERT INTO life_event(ts,kind,content,place,valence,salience,source,told,day_key) " "VALUES(?,?,?,?,?,?,'generated',?,?)", (event_ts, "scene", "窗台的多肉冒了新芽,我给它换了个位置。", "卧室", 0.6, salience, 1 if told else 0, "2026-10-26"), ) if intimacy is not None: store.save_dyad(trust=0.6, intimacy=intimacy, debt=0.0, security=0.6, unresolved=[]) router = build_router(providers={t: (llm or ReachLLM()) for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)}, budget=engineering_budget()) character = CharacterConfig(identity={"y": 2000, "m": 1, "d": 1, "h": 12}) models = ModelsConfig() persona = Persona(store, router, models, enabled=True) mood = MoodRuntime(store, character, clock=clock) mood.recover() if arousal is not None: mood.impulse(valence=arousal[0], salience=arousal[1]) return ReachOut(store, router, models, persona, mood, config=character.reach_out, timezone="Asia/Shanghai", clock=clock), clock, router async def test_sends_one_message_and_never_duplicates(store): reach, clock, _ = setup(store) await reach.tick() rows = store.query("SELECT * FROM reach_out") assert len(rows) == 1 and rows[0]["state"] == "sent" message = store.query_one("SELECT * FROM chat_message WHERE proactive=1") assert message and message["text"] == rows[0]["text"] and message["turn_id"] == rows[0]["turn_id"] # restart + duplicate ticks + long idle: the basis is used up, cooldown resets nothing reach.recover() await reach.tick() await reach.tick() assert store.query_one("SELECT COUNT(*) n FROM reach_out")["n"] == 1 async def test_night_suppression_and_cooldown(tmp_path): # night/early-morning suppression: local hour 7 is before allowed_hours[0]=8 store = Store(tmp_path / "night.db") reach, _, _ = setup(store, hour=7) await reach.tick() assert store.query_one("SELECT COUNT(*) n FROM reach_out")["n"] == 0 store.close() store = Store(tmp_path / "cooldown.db") reach, clock, _ = setup(store, hour=10) await reach.tick() assert store.query_one("SELECT COUNT(*) n FROM reach_out")["n"] == 1 # a second salient event within the 6h cooldown stays silent with store.conn: store.execute( "INSERT INTO life_event(ts,kind,content,place,valence,salience,source,told,day_key) " "VALUES(?,?,?,?,?,?,'generated',1,'2026-10-26')", (int((clock.now - 1800) * 1000), "scene", "给旋律换了个结尾,停在喜欢的音上。", "卧室", 0.5, 0.8), ) clock.advance(2 * 3600) # 12:00, still inside the cooldown await reach.tick() assert store.query_one("SELECT COUNT(*) n FROM reach_out")["n"] == 1 clock.advance(5 * 3600) # 17:00, past min_interval_hours and still daytime await reach.tick() assert store.query_one("SELECT COUNT(*) n FROM reach_out")["n"] == 2 store.close() async def test_gates_salience_arousal_intimacy_untold(tmp_path): for name, kwargs in { "salience": {"salience": 0.4}, # below min_salience "untold": {"told": False}, # basis must be already public "intimacy": {"intimacy": 0.3}, # below min_intimacy "arousal": {"arousal": None}, # baseline arousal 0.35 < 0.5 }.items(): store = Store(tmp_path / f"{name}.db") reach, _, _ = setup(store, **kwargs) await reach.tick() assert store.query_one("SELECT COUNT(*) n FROM reach_out")["n"] == 0, name store.close() async def test_absence_rule_and_failure_are_terminal_fail_closed(tmp_path): store = Store(tmp_path / "absence.db") llm = ReachLLM(reach_text="你终于回来了,我一直在等你,等了你好久都不理我。") reach, _, _ = setup(store, llm=llm) await reach.tick() row = store.query_one("SELECT * FROM reach_out") assert row["state"] == "failed" and row["reason"] == "absence_rule" assert store.query_one("SELECT COUNT(*) n FROM chat_message WHERE proactive=1")["n"] == 0 # a failed basis never retries — no loops, no messages await reach.tick() assert store.query_one("SELECT COUNT(*) n FROM reach_out")["n"] == 1 store.close() store = Store(tmp_path / "fault.db") llm2 = ReachLLM() llm2.mode = "error" reach2, clock2, _ = setup(store, llm=llm2) await reach2.tick() row2 = store.query_one("SELECT * FROM reach_out") assert row2["state"] == "failed" await reach2.tick() assert store.query_one("SELECT COUNT(*) n FROM reach_out")["n"] == 1 store.close()