322 lines
15 KiB
Python
322 lines
15 KiB
Python
"""HEL-916 concentrated fixes: dialogue input structure, natural boundary,
|
|
activity wiring, bounded judgment retry, chat-driven mood.
|
|
|
|
All cases run on isolated temp databases and fake providers; no real calls.
|
|
"""
|
|
import json
|
|
import time
|
|
from uuid import uuid4
|
|
|
|
import pytest
|
|
from conftest import engineering_budget
|
|
from fastapi.testclient import TestClient
|
|
from test_api import CREATE, events, turn
|
|
from test_r2 import INTERP, ack, add_life, final_and_receipt, judge, selected
|
|
from test_r4_api import R4LLM
|
|
|
|
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 H916LLM(R4LLM):
|
|
"""R4 fake plus the HEL-916 PATTERN_DETECT scene."""
|
|
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.affect = {"kind": "none", "severity": 0}
|
|
self.affect_calls = []
|
|
self.affect_error = False
|
|
|
|
async def stream(self, messages, **kwargs):
|
|
prompt = messages[0].content
|
|
if "判断这轮已完成对话里是否出现明确的伤害或修复事件" in prompt:
|
|
self.affect_calls.append(messages)
|
|
if self.affect_error:
|
|
raise OSError("classification upstream fault")
|
|
yield LLMDelta(text=json.dumps(self.affect, ensure_ascii=False))
|
|
yield LLMDelta(done=True, finish_reason="stop")
|
|
return
|
|
async for delta in super().stream(messages, **kwargs):
|
|
yield delta
|
|
|
|
|
|
def h916_app(tmp_path, *, enabled=True, poll=3600, provider=None):
|
|
provider = provider or H916LLM()
|
|
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 / "h916.db", router=router,
|
|
life_config=LifeConfig(enabled=enabled, poll_seconds=poll),
|
|
semantic_mode="off")
|
|
return app, provider
|
|
|
|
|
|
def test_dialogue_input_is_labeled_facts_instructions_and_past_life(tmp_path):
|
|
app, provider = h916_app(tmp_path)
|
|
with TestClient(app) as client:
|
|
client.post("/api/companion", json=CREATE)
|
|
store = app.state.store
|
|
with store.conn: # she is mid-activity; an old untold candidate exists
|
|
store.execute("INSERT INTO life_activity(title,place,state,started_at) "
|
|
"VALUES('整理窗台','卧室','active',1)")
|
|
old_ts = int(time.time() * 1000) - 2 * 86400000
|
|
with store.conn:
|
|
store.execute(
|
|
"INSERT INTO life_event(ts,kind,content,place,valence,salience,source,told,day_key,tz) "
|
|
"VALUES(?,'thought','前天试着给旋律换了个结尾','房间',.3,.7,'generated',0,'2026-10-30','Asia/Shanghai')",
|
|
(old_ts,))
|
|
turn(client, "在忙什么呢")
|
|
system = provider.calls[-1][0].content
|
|
# fact / instruction boundary is auditable section by section
|
|
assert "【事实:她是谁" in system and "【指令:怎么说话】" in system
|
|
assert "【事实:她此刻的状态】" in system
|
|
# existing persona text rides verbatim — no regeneration, no template
|
|
assert INTERP in system
|
|
assert "原始出生事实" in system
|
|
# the live activity is wired in and is the authority for "now"
|
|
assert "整理窗台" in system and "活动状态为准" in system
|
|
# candidates carry their own occurrence time and are framed as the past
|
|
assert "发生时间" in system and "给旋律换了个结尾" in system
|
|
assert "不是此刻" in system
|
|
# the boundary is expressed without the old flat refusal line
|
|
assert "只有信息能穿过两个世界,不能触碰或给予实物" not in system
|
|
assert "自然接住" in system and "不声称听见声音" in system
|
|
|
|
|
|
def test_history_stitching_survives_failure_then_retry_same_turn(tmp_path):
|
|
app, provider = h916_app(tmp_path)
|
|
with TestClient(app) as client:
|
|
client.post("/api/companion", json=CREATE)
|
|
tid = str(uuid4())
|
|
provider.mode = "error"
|
|
assert events(turn(client, "上次没说完的话", turn_id=tid))[-1]["t"] == "chat.error"
|
|
provider.mode = "normal"
|
|
final = events(turn(client, "上次没说完的话", turn_id=tid))[-1]
|
|
assert final["t"] == "chat.final"
|
|
turn(client, "接着说")
|
|
context = provider.calls[-1]
|
|
roles = [m.role for m in context]
|
|
# system + the retried exchange stitched exactly once + the new message
|
|
assert roles == ["system", "user", "assistant", "user"]
|
|
assert sum("上次没说完的话" in m.content for m in context if m.role == "user") == 1
|
|
assert sum(provider.reply in m.content for m in context if m.role == "assistant") == 1
|
|
|
|
|
|
def test_transient_judgment_failure_requeues_once_then_publishes(tmp_path):
|
|
app, provider = h916_app(tmp_path)
|
|
with TestClient(app) as client:
|
|
client.post("/api/companion", json=CREATE)
|
|
eid = add_life(app.state.store)
|
|
selected(provider, eid)
|
|
_, receipt = final_and_receipt(client)
|
|
assert ack(client, receipt).status_code == 200
|
|
provider.mode = "background_error"
|
|
judge(client, app, receipt["message_id"])
|
|
s = app.state.store
|
|
row = s.query_one("SELECT state,judge_attempts FROM sharing_attempt")
|
|
assert row["state"] == "pending" and row["judge_attempts"] == 1
|
|
assert not s.query("SELECT * FROM telling_log")
|
|
provider.mode = "normal"
|
|
judge(client, app, receipt["message_id"])
|
|
assert s.query_one("SELECT state FROM sharing_attempt")["state"] == "judged"
|
|
assert len(s.query("SELECT * FROM telling_log")) == 1
|
|
|
|
|
|
def test_second_transient_failure_and_invalid_judgment_are_terminal(tmp_path):
|
|
app, provider = h916_app(tmp_path)
|
|
with TestClient(app) as client:
|
|
client.post("/api/companion", json=CREATE)
|
|
eid = add_life(app.state.store)
|
|
selected(provider, eid)
|
|
_, receipt = final_and_receipt(client)
|
|
ack(client, receipt)
|
|
provider.mode = "background_error"
|
|
judge(client, app, receipt["message_id"])
|
|
judge(client, app, receipt["message_id"]) # second transient: terminal
|
|
s = app.state.store
|
|
assert s.query_one("SELECT state,judge_attempts FROM sharing_attempt")["state"] == "failed"
|
|
provider.mode = "normal"
|
|
calls_before = len(provider.background_calls)
|
|
judge(client, app, receipt["message_id"]) # failed never re-claims
|
|
assert len(provider.background_calls) == calls_before
|
|
assert not s.query("SELECT * FROM telling_log")
|
|
|
|
|
|
def test_invalid_judgment_still_fails_closed_without_retry(tmp_path):
|
|
app, provider = h916_app(tmp_path)
|
|
with TestClient(app) as client:
|
|
client.post("/api/companion", json=CREATE)
|
|
eid = add_life(app.state.store)
|
|
selected(provider, eid)
|
|
provider.judgment["narrated"][0]["evidence"] = "这段原话根本不存在于完整回复"
|
|
_, receipt = final_and_receipt(client)
|
|
ack(client, receipt)
|
|
judge(client, app, receipt["message_id"])
|
|
s = app.state.store
|
|
row = s.query_one("SELECT state,judge_attempts FROM sharing_attempt")
|
|
assert row["state"] == "failed" and row["judge_attempts"] == 1
|
|
calls_before = len(provider.background_calls)
|
|
judge(client, app, receipt["message_id"])
|
|
assert len(provider.background_calls) == calls_before
|
|
assert not s.query("SELECT * FROM telling_log")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_chat_hurt_moves_mood_once_and_persists(tmp_path):
|
|
app, provider = h916_app(tmp_path, enabled=False)
|
|
with TestClient(app) as client:
|
|
client.post("/api/companion", json=CREATE)
|
|
provider.affect = {"kind": "hurt", "severity": 0.8}
|
|
turn(client, "我刚才说了很重的话,对不起")
|
|
mood = app.state.mood
|
|
store = app.state.store
|
|
before = mood.state.v
|
|
await app.state.life.tick()
|
|
assert mood.state.v < before # bounded impulse through the audited path
|
|
assert store.last_state()["valence"] == pytest.approx(mood.state.v)
|
|
assert store.query_one("SELECT state FROM chat_affect_job")["state"] == "done"
|
|
# idempotent: the same turn is never classified (or applied) twice
|
|
v_after = mood.state.v
|
|
calls = len(provider.affect_calls)
|
|
await app.state.life.tick()
|
|
assert len(provider.affect_calls) == calls
|
|
assert abs(mood.state.v - v_after) < 0.01 # only heartbeat decay, no re-impulse
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_chat_none_and_failure_never_move_mood(tmp_path):
|
|
app, provider = h916_app(tmp_path, enabled=False)
|
|
with TestClient(app) as client:
|
|
client.post("/api/companion", json=CREATE)
|
|
provider.affect = {"kind": "none", "severity": 0}
|
|
turn(client, "今天过得怎么样")
|
|
mood = app.state.mood
|
|
before = mood.state.v
|
|
await app.state.life.tick()
|
|
# ordinary chat: no impulse (only the pre-existing tanh clamp drift)
|
|
assert abs(mood.state.v - before) < 1e-3
|
|
# a classification failure forges nothing and stays terminal-failed
|
|
provider.affect_error = True
|
|
provider.affect = {"kind": "hurt", "severity": 0.9}
|
|
turn(client, "再说一次重话")
|
|
v_before = mood.state.v
|
|
await app.state.life.tick()
|
|
assert abs(mood.state.v - v_before) < 1e-3
|
|
assert app.state.store.query_one(
|
|
"SELECT state FROM chat_affect_job ORDER BY message_id DESC")["state"] == "failed"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_chat_affect_recovers_expired_lease_as_failed(tmp_path):
|
|
app, provider = h916_app(tmp_path, enabled=False)
|
|
with TestClient(app) as client:
|
|
client.post("/api/companion", json=CREATE)
|
|
turn(client, "普通一句话")
|
|
store = app.state.store
|
|
message_id = store.query_one(
|
|
"SELECT id FROM chat_message WHERE role='companion' AND status='sent'")["id"]
|
|
with store.conn: # simulate a worker that died mid-classification
|
|
store.execute("INSERT INTO chat_affect_job(message_id,state,owner,lease_until,created_at) "
|
|
"VALUES(?,'pending','dead',0,0)", (message_id,))
|
|
app.state.life.recover()
|
|
assert store.query_one("SELECT state FROM chat_affect_job")["state"] == "failed"
|
|
await app.state.life.tick()
|
|
assert not provider.affect_calls # expired lease is never re-run
|
|
|
|
|
|
# ---------------------------------------------------------------- rework (总工 HEL-917 两项)
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("bad", [True, False, float("nan"), float("inf"), float("-inf")])
|
|
async def test_invalid_severity_is_none_like_never_shocks(tmp_path, bad):
|
|
app, provider = h916_app(tmp_path, enabled=False)
|
|
with TestClient(app) as client:
|
|
client.post("/api/companion", json=CREATE)
|
|
provider.affect = {"kind": "hurt", "severity": bad}
|
|
turn(client, "这句话不该产生任何冲击")
|
|
mood, store = app.state.mood, app.state.store
|
|
dyad_before = app.state.dyad.load()
|
|
before = mood.state.v
|
|
await app.state.life.tick()
|
|
# job is done (terminal, never reclassified) but nothing moved
|
|
assert len(provider.affect_calls) == 1
|
|
assert store.query_one("SELECT state FROM chat_affect_job")["state"] == "done"
|
|
assert abs(mood.state.v - before) < 1e-3 # only the pre-existing tanh drift
|
|
after = app.state.dyad.load()
|
|
assert (after.trust, after.intimacy, after.debt, after.security) == \
|
|
(dyad_before.trust, dyad_before.intimacy, dyad_before.debt, dyad_before.security)
|
|
await app.state.life.tick()
|
|
assert len(provider.affect_calls) == 1 # no repeat classification
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_valid_hurt_still_works_after_the_guard(tmp_path):
|
|
app, provider = h916_app(tmp_path, enabled=False)
|
|
with TestClient(app) as client:
|
|
client.post("/api/companion", json=CREATE)
|
|
provider.affect = {"kind": "hurt", "severity": 0.8}
|
|
turn(client, "我刚才说了很重的话")
|
|
before = app.state.mood.state.v
|
|
await app.state.life.tick()
|
|
assert app.state.mood.state.v < before - 0.1 # bounded but real
|
|
|
|
|
|
def seed_old_chat(db_path):
|
|
from cybergril.memory.store import Store
|
|
|
|
store = Store(db_path)
|
|
with store.conn:
|
|
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) "
|
|
"VALUES(1,'user','很久以前的一句重话','old-1','sent')")
|
|
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) "
|
|
"VALUES(2,'companion','很久以前的回复','old-1','sent')")
|
|
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) "
|
|
"VALUES(3,'user','更久以前','old-2','sent')")
|
|
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) "
|
|
"VALUES(4,'companion','更久以前的回复','old-2','sent')")
|
|
store.close()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_migrated_old_chat_never_classified_on_first_startup(tmp_path):
|
|
db = tmp_path / "h916.db"
|
|
seed_old_chat(db) # a populated database from before this wiring existed
|
|
app, provider = h916_app(tmp_path, enabled=False)
|
|
with TestClient(app) as client:
|
|
await app.state.life.tick()
|
|
assert not provider.affect_calls # no call, no job, no retro hurt
|
|
assert not app.state.store.query("SELECT * FROM chat_affect_job")
|
|
cutoff = app.state.store.query_one(
|
|
"SELECT value FROM life_control WHERE key='chat_affect_cutoff'")["value"]
|
|
assert int(cutoff) == 4 # pinned to the max pre-existing message id
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cutoff_persists_across_restart_and_only_new_turns_flow(tmp_path):
|
|
db = tmp_path / "h916.db"
|
|
app, provider = h916_app(tmp_path, enabled=False)
|
|
with TestClient(app) as client:
|
|
client.post("/api/companion", json=CREATE)
|
|
provider.affect = {"kind": "none", "severity": 0}
|
|
turn(client, "新完成的一轮")
|
|
await app.state.life.tick()
|
|
assert len(provider.affect_calls) == 1
|
|
cutoff = app.state.store.query_one(
|
|
"SELECT value FROM life_control WHERE key='chat_affect_cutoff'")["value"]
|
|
# restart on the same database: the cutoff must not move, the classified
|
|
# turn must not be re-run, and a turn completed after the restart flows
|
|
app2, provider2 = h916_app(tmp_path, enabled=False)
|
|
with TestClient(app2) as client2:
|
|
await app2.state.life.tick()
|
|
assert len(provider2.affect_calls) == 0
|
|
assert app2.state.store.query_one(
|
|
"SELECT value FROM life_control WHERE key='chat_affect_cutoff'")["value"] == cutoff
|
|
provider2.affect = {"kind": "repair", "severity": 0.6}
|
|
turn(client2, "和好如初的一轮")
|
|
before = app2.state.mood.state.v
|
|
await app2.state.life.tick()
|
|
assert len(provider2.affect_calls) == 1
|
|
assert app2.state.mood.state.v > before # positive, bounded repair impulse
|