HEL-916: auditable dialogue input, natural two-world boundary, live-activity wiring, bounded judgment retry, chat-driven mood
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -2,6 +2,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -9,6 +12,34 @@ import pytest
|
||||
from cybergril.config import CharacterConfig, ModelsConfig, Settings
|
||||
from cybergril.memory import Store
|
||||
|
||||
# Test-env compatibility only (product targets Python 3.11, deploy/hel874 uses
|
||||
# uv --python 3.11): this workspace runs 3.10, where asyncio.timeout does not
|
||||
# exist. The shim mirrors the only shape the product uses —
|
||||
# ``async with asyncio.timeout(delay)`` raising TimeoutError on expiry.
|
||||
if sys.version_info < (3, 11) and not hasattr(asyncio, "timeout"):
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def _timeout_compat(delay: float):
|
||||
loop = asyncio.get_running_loop()
|
||||
deadline = loop.time() + max(0.0, delay)
|
||||
current = asyncio.current_task()
|
||||
|
||||
def _expire():
|
||||
if current is not None:
|
||||
current.cancel()
|
||||
|
||||
handle = loop.call_at(deadline, _expire)
|
||||
try:
|
||||
yield
|
||||
except asyncio.CancelledError:
|
||||
if loop.time() < deadline:
|
||||
raise
|
||||
raise TimeoutError from None
|
||||
finally:
|
||||
handle.cancel()
|
||||
|
||||
asyncio.timeout = _timeout_compat # type: ignore[attr-defined]
|
||||
|
||||
try:
|
||||
from cybergril.think.budget import CATEGORIES, BudgetConfig
|
||||
except ImportError: # r3 baseline probe runs these tests against older src trees
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
"""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
|
||||
+5
-2
@@ -192,8 +192,11 @@ def test_old_profile_never_auto_backfilled_and_explicit_backfill_is_honest(tmp_p
|
||||
assert not app2.state.store.query("SELECT * FROM persona_interp")
|
||||
assert not app2.state.store.query("SELECT * FROM persona_job")
|
||||
assert len(app2.state.store.query("SELECT * FROM life_event")) == life_count
|
||||
assert len(p.background_calls) == life_count
|
||||
assert all("本人生活自述" in prompt for prompt in p.background_calls)
|
||||
# HEL-916 adds one chat-affect classification per completed turn;
|
||||
# the no-backfill honesty claim is about life/persona calls only.
|
||||
assert len([p for p in p.background_calls if "伤害或修复" not in p]) == life_count
|
||||
assert all("本人生活自述" in prompt for prompt in p.background_calls
|
||||
if "伤害或修复" not in prompt)
|
||||
persona = app2.state.persona
|
||||
c.portal.call(lambda: persona.ensure(backfill=True))
|
||||
view = c.get("/api/persona").json()
|
||||
|
||||
Reference in New Issue
Block a user