Files
CyberGril/tests/test_reach_out.py
T
zonggongandmultica-agent e291058754 HEL-882 rework: execution-table caps become real hard gates at the wire, SDK hidden retries and mid-add failures recover without loss, the 8360 release package runs offline, and the HEL-874 embedding evidence is corrected - every real provider exit (create/dialogue/life/gist/judgment/growth/proactive phrasing + mem0's internal extraction LLM) now persistently pre-allocates request count (per-category daily + one-shot totals in request_usage/budget_total, BEGIN IMMEDIATE) and a conservative token estimate before sending, refuses at the tightest cap (BudgetStop, no more downgrade-and-keep-calling) and survives restarts; known usage settles to actual, unknown/disconnect/failure keeps the full reservation; ledger guards gain per-day tops (embed_daily/llm_daily) and verify_ledger_authority rejects a fresh file bypassing the frozen 498/500 prefix; the mem0 SDK client's hidden OpenAI retries are disabled (max_retries=0) so every actual send is gated and answered failures (even 5xx) settle as used with only httpx.ConnectError-grade unsent requests released; embed refusals the SDK swallows into empty adds are re-raised as budget errors so the batch re-queues without burning an attempt and resumes when the cap returns, add_group resumes at vector-store level (src_group anchors: only missing rows resent, crash/restart/concurrency never duplicate), sem coverage is per-backend (stub batches no longer block a real rebuild, real done batches never resend) with backend-scoped batch keys; the release package is offline-executable: fresh-dir git clone, cybergril service account, PYTHONPATH in the unit so the lock-only venv imports the product, shipped caps explicitly 0 (=refuse by design until approved), deploy/mem0-stack.lock + accurate 3.11 wheel gap with a no-download path (hel857-venv is 3.10; never present stub/FTS as the real memory experience), and tools/check_release_offline_hel882.py verifies checkout/import/health/fail-closed/approved-run/data-preservation on loopback with echo stand-ins; evidence corrected per manager review: docs/rework/hel874/erratum-hel882.json + README appendix record that e978e87's verification did real local embeddings from cache (provable lower bound 12, exact total unrecoverable, temp sandbox gone) while zero-real-LLM/zero-download/zero-outbound stand, old JSONs and authoritative ledgers untouched, and tools/verify_mem0_real_hel874.py now installs the deterministic 512-dim stand-in before TextEmbedding construction plus non-loopback socket rejection (zero model loads) with final_embed_rows persisted before temp cleanup; verification: 272 python tests pass on 3.11.16 venv + requirements.lock offline (16 new: manager api repro blocked with 0 provider calls, sdk repro 1-HTTP/max_retries=0/llm_ops=1, mid-add swallow requeued-then-resumed, resume-no-duplicate, stub-to-mem0 rebuild, daily embed cap, unified mem0-LLM gate, authority refusal, restart-persistent counters, tightest-constraint settle/release), ruff clean (src/tests/tools), web tsc + 42 vitest + build via npm ci --offline, pinned-install deterministic re-run 12/12, manager review scripts re-run evidence attached in delivery, dual-target requirement checks 4/4 with handoff-HEL-882.json; zero real calls, zero real embeddings, zero non-loopback outbound, authoritative ledgers and freezes untouched, not deployed, PR not merged, no visual changes
Co-authored-by: multica-agent <github@multica.ai>
2026-10-26 23:20:18 +08:00

172 lines
7.0 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 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()