Files
CyberGril/tests/test_reach_out.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

170 lines
6.9 KiB
Python

"""R4 reach-out: approved gates, one message per basis ever, absence red line."""
import json
from datetime import UTC, datetime
import pytest
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)})
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()