HEL-916 rework: finite non-bool severity only; one-time chat-affect historical cutoff
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -26,13 +26,14 @@
|
||||
"GOV-003",
|
||||
"GOV-005"
|
||||
],
|
||||
"deliverable": "从真实基线 ffbc8c2/e74531c 起的集中工程修正,全部离线替身验证、零真实调用:1) api/app.py 对话 system 输入重构为可审的分段结构(【事实:她是谁】/【事实:她此刻的状态】/【指令:怎么说话】),出生事实、既有 persona 诠释原文保留不动,事实与行为指令边界清晰;2) 世界边界改为自然承接表述:保留信息可跨世界、实物不可的真实约束,去掉被扩写成隔屏拒绝的生硬原句,明确亲近表达自然接住、不反复解释规则、追问按本人理解回答、未开收音不声称听见;3) 生活活动状态接线进主对话(life_activity current 作为'此刻'唯一权威),分享候选逐条携带发生时间并被明确标为过去经历,杜绝旧候选冒充此刻;4) sharing.py 判定失败区分:模型答复无效(含证据不符/pydantic 校验失败)保持终态 fail-closed,瞬态失败(超时/上游/预算停)经新增 judge_attempts 计数恰好重排一次(新增列含旧库 guarded ALTER 迁移),成功分享仍需确实叙述+有效回执缺一不可;5) 普通聊天接入情绪:复用既有 PATTERN_DETECT 分类与 dyad 事件接线(原 detect_and_apply 从未被调用),改造为账本化 chat_affect(新表 chat_affect_job,幂等/租约/重启恢复终态),仅 hurt/repair 带 severity 才经既有 make_impulse 产生有界冲击(salience 减半常数,复用既有敏感度方程),none 不动情绪、失败不伪造;6) tests/test_hel916.py 新增 8 个针对性测试(输入结构/边界措辞/失败重试历史拼接/瞬态与无效判定分流/聊天情绪来源-幂等-失败-恢复),并按新接线调整 test_r2 背景调用计数断言;conftest 增加 Python 3.10 测试环境 asyncio.timeout 兼容 shim(仅测试环境,产品仍按 3.11)。",
|
||||
"deliverable": "两轮交付。第一轮(adf4d5c,总工已核过输入结构/活动接线/分享失败分流/情绪接线框架):api/app.py 对话输入重构为可审分段(事实/此刻状态/指令),出生事实与既有 persona 诠释原文保留;世界边界改自然承接表述;生活活动状态接线为'此刻'唯一权威、分享候选带发生时间标为过去;sharing.py 判定失败分流(无效终态 fail-closed、瞬态经 judge_attempts 恰好重排一次);普通聊天经既有 PATTERN_DETECT+dyad 接线接入情绪(账本化 chat_affect,幂等/租约/恢复终态,salience 0.5 减半,复用既有敏感度与衰减方程)。第二轮(本轮返工,总工 HEL-917 两项阻塞):1) dyad/runtime.py 情绪分类 severity 只接受有限非 bool 数值——True/False(bool 是 int 子类会被当 1.0/0.0)、NaN/正负 Infinity(json.loads 可产出、原 min/max 钳制会放行 NaN 或放大 Infinity)一律按 none 处理:job 终态 done、不写情绪/关系冲击、不重复分类;正常有限 hurt/repair 原有有界算法不变。2) life/runtime.py 聊天情绪补一次性历史切断点(life_control 键 chat_affect_cutoff=初始化时 MAX(message_id)):app lifespan 在开始接收任何聊天前调用 init_chat_affect_cutoff 固化切断点,INSERT…ON CONFLICT/NOT EXISTS 幂等,任何 tick/重启/并发都不会重置;分类只处理切断点之后新完成轮次,旧聊天(迁移库)永不补算为当下伤害;历史回溯未获授权不做。",
|
||||
"acceptance": [
|
||||
"pytest tests/ 全量:482 passed / 11 skipped / 3 failed —— 3 个失败(test_r2 lifespan_cancels、server_loop、voice_asr seam_recv_death)在未改动基线 ffbc8c2 上以同环境同样失败,属本机 Python 3.10 与产品目标 3.11 的环境差异,非本次改动引入;test_reach_out 在 3.10 无法收集(datetime.UTC,基线同样)",
|
||||
"新增 8 个 HEL-916 测试全部通过:修前复现=旧生硬边界原句与无活动接线输入(以基线代码结构对照),修后对照=分段可审输入、候选带发生时间、判定瞬态一次重排、聊天 hurt 冲击有界且幂等持久",
|
||||
"python3 -m ruff check src 通过;tests 仅剩基线既有的 2 处 test_sdk_livekit_hel908 错误;ruff format 全仓本不强制(基线 73 文件即不一致),未引入新格式问题",
|
||||
"python3 scripts/check_requirements.py --base-ref origin/main 通过(60项),含本 handoff 再跑一次通过",
|
||||
"出生底色/人格不重算:persona.prompt() 内容未改一字,测试断言既有 INTERP 原文逐字出现在新输入中"
|
||||
"返工专项测试(tests/test_hel916.py,本机 Python 3.10+测试 shim,隔离临时库+替身 LLM)16/16 通过:含 True/False/NaN/+Inf/-Inf 五参数均无冲击无重复分类且 dyad 账本不变、正常 hurt 仍走通;迁移旧库首次启动零分类零调用且切断点=MAX(message_id)、新轮只处理一次、重启切断点不变新轮不丢、repair 正向有界冲击走通",
|
||||
"受影响既有测试通过:tests/test_r2.py -k 'old_profile or disclosure or judgment or receipt or expired' 25 passed;tests/test_r4_api.py + tests/test_mood_runtime.py 11 passed",
|
||||
"python3 -m ruff check src 通过(0 错误)",
|
||||
"双基线需求检查通过:--base-ref origin/main 与 --base-ref e74531c 各含本 handoff",
|
||||
"全量口径如实分开:原施工本机 pytest 全量 482 passed/11 skipped/3 failed(3 项在未改动基线 ffbc8c2 同环境同败,属本机 3.10 与产品 3.11 环境差异);总工全套记录 483 过/11 跳/3 败(总工环境口径),本轮未全库复测、未将总工数字冒充新实测",
|
||||
"出生底色/人格不重算:persona.prompt() 内容未改一字(测试断言既有 INTERP 原文逐字出现)"
|
||||
],
|
||||
"deferred": [
|
||||
"真实模型下的语气自然度、边界承接与情绪体验:本卡零真实调用,无法以离线替身证明语言自然;建议下一轮最低必要验证:由总管在隔离副本放行小额度(建议 ≤30 次对话/1 次分享判定闭环),操作人总管,约 1 小时,重点观察亲近表达承接、追问'为什么'、隔屏说明是否消失、聊天后情绪词变化与恢复",
|
||||
@@ -42,9 +43,9 @@
|
||||
],
|
||||
"requirement_changes": [],
|
||||
"verification": [
|
||||
"离线测试证据:tests/test_hel916.py 8/8 通过(隔离临时库+替身 LLM+受控断言),全仓 pytest 记录如上",
|
||||
"修前/修后对照:test_dialogue_input_is_labeled_facts_instructions_and_past_life 断言旧原句'只有信息能穿过两个世界,不能触碰或给予实物'已不在输入、活动状态与候选发生时间在输入中;历史拼接测试复现失败→重试→上下文完整",
|
||||
"每项证据的边界:以上仅证明服务器输入结构与状态接线正确;不证明真实模型语气自然、不证明用户满意,真实验收保留",
|
||||
"离线测试证据:tests/test_hel916.py 16/16 通过(隔离临时库+替身 LLM+受控断言);受影响既有子集 25+11 通过;命令与口径见 acceptance,未全库复测",
|
||||
"返工修前/修后对照:修前(adf4d5c)severity=True/NaN/Infinity 会进入 min/max 钳制(True→1.0 最大冲击、NaN 经 max/min 原样穿透),且首次启动会把库中所有旧聊天逐条分类;修后五类无效值均无冲击无重复分类、迁移旧库首次启动零调用、切断点重启不变",
|
||||
"每项证据的边界:以上仅证明服务器输入结构、状态接线与数值防护正确;不证明真实模型语气自然、不证明用户满意,真实验收保留;真实体验方案仅备稿,待两项复核通过后由总管集中请用户批准",
|
||||
"未测到:真实 LLM/ASR/TTS 行为、多日连续运行、浏览器端到端、Safari/手机;均如实未验证"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -261,6 +261,10 @@ def create_app(
|
||||
app.state.semantic.recover()
|
||||
if app.state.life.reach_out:
|
||||
app.state.life.reach_out.recover()
|
||||
# HEL-916 rework: fix the chat-affect historical cutoff NOW, before
|
||||
# the server accepts its first chat turn — everything that already
|
||||
# exists (migration) stays unclassified, everything after it flows.
|
||||
app.state.life.init_chat_affect_cutoff()
|
||||
# HEL-879: bounded restart compensation for this instance's own
|
||||
# voice rooms (persisted cleanup ledger; own rooms only).
|
||||
if getattr(app.state, "voice_service", None):
|
||||
|
||||
@@ -8,6 +8,7 @@ never as lines to recite.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
import secrets
|
||||
import time
|
||||
from datetime import datetime
|
||||
@@ -111,7 +112,15 @@ class DyadRuntime:
|
||||
"message_id": message_id}, max_tokens=200,
|
||||
)
|
||||
kind, severity = raw.get("kind"), raw.get("severity")
|
||||
if kind in ("hurt", "repair") and isinstance(severity, (int, float)):
|
||||
# HEL-916 rework: accept ONLY finite numbers — bool is an int
|
||||
# subclass (True would land as 1.0) and json.loads happily yields
|
||||
# NaN/Infinity, which the min/max clamp would pass through as the
|
||||
# maximum shock. Anything else is treated like "none": the job is
|
||||
# done, the mood and the ledger stay untouched.
|
||||
if (kind in ("hurt", "repair")
|
||||
and isinstance(severity, (int, float))
|
||||
and not isinstance(severity, bool)
|
||||
and math.isfinite(severity)):
|
||||
severity = max(-1.0, min(1.0, float(severity)))
|
||||
dyad = self.load()
|
||||
dyad.apply(DyadEvent(kind=kind, summary=f"对话事件 message_id={message_id}",
|
||||
|
||||
@@ -99,6 +99,33 @@ class LifeRuntime:
|
||||
yield day.isoformat(), slot, stamp
|
||||
day += timedelta(days=1)
|
||||
|
||||
def _chat_affect_cutoff(self) -> int:
|
||||
"""HEL-916 rework: one-time historical cutoff for chat-affect.
|
||||
|
||||
On the very first initialization (or on a database migrated from a
|
||||
build without this wiring) the cutoff persists the current max
|
||||
message id ONCE — every chat that predates the wiring stays
|
||||
unclassified forever. ``ON CONFLICT DO NOTHING`` makes the write
|
||||
idempotent: no tick, restart or concurrent worker can ever reset the
|
||||
cutoff and swallow turns that complete after it. The app lifespan
|
||||
calls :meth:`init_chat_affect_cutoff` before the server accepts any
|
||||
chat request; this lazy read is the fallback for other assemblies.
|
||||
"""
|
||||
row = self.store.query_one("SELECT value FROM life_control WHERE key='chat_affect_cutoff'")
|
||||
if not row:
|
||||
with self.store.conn:
|
||||
self.store.execute(
|
||||
"INSERT INTO life_control "
|
||||
"SELECT 'chat_affect_cutoff', COALESCE(MAX(id),0) FROM chat_message "
|
||||
"WHERE NOT EXISTS(SELECT 1 FROM life_control WHERE key='chat_affect_cutoff')"
|
||||
)
|
||||
row = self.store.query_one("SELECT value FROM life_control WHERE key='chat_affect_cutoff'")
|
||||
return int(row["value"])
|
||||
|
||||
def init_chat_affect_cutoff(self) -> None:
|
||||
"""Lifespan hook: establish the cutoff before any turn can arrive."""
|
||||
self._chat_affect_cutoff()
|
||||
|
||||
async def tick(self):
|
||||
if self.memories:
|
||||
await self.memories.tick()
|
||||
@@ -110,16 +137,18 @@ class LifeRuntime:
|
||||
if self.dyad:
|
||||
self.dyad.daily_regression(self.clock())
|
||||
# HEL-916: ordinary chat finally feeds the mood — one bounded
|
||||
# classification per completed public turn, before the R2 gate so
|
||||
# text-only configurations keep the wiring too. Ledger-enforced
|
||||
# classification per NEWLY completed public turn (id above the
|
||||
# one-time cutoff), before the R2 gate so text-only
|
||||
# configurations keep the wiring too. Ledger-enforced
|
||||
# idempotency; no candidates or private life data in the payload.
|
||||
cutoff = self._chat_affect_cutoff()
|
||||
row = self.store.query_one(
|
||||
"SELECT m.id AS message_id, u.text AS user_text, m.text AS reply_text "
|
||||
"FROM chat_message m JOIN chat_message u "
|
||||
"ON u.turn_id=m.turn_id AND u.role='user' AND u.status='sent' "
|
||||
"WHERE m.role='companion' AND m.status='sent' AND m.proactive=0 "
|
||||
"WHERE m.role='companion' AND m.status='sent' AND m.proactive=0 AND m.id>? "
|
||||
"AND NOT EXISTS(SELECT 1 FROM chat_affect_job j WHERE j.message_id=m.id) "
|
||||
"ORDER BY m.id LIMIT 1")
|
||||
"ORDER BY m.id LIMIT 1", (cutoff,))
|
||||
if row:
|
||||
await self.dyad.chat_affect(message_id=row["message_id"],
|
||||
user_text=row["user_text"],
|
||||
|
||||
@@ -224,3 +224,98 @@ async def test_chat_affect_recovers_expired_lease_as_failed(tmp_path):
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user