chore: project foundation
Contracts (the shared language): - percept / state / context / utterance / render / audio / capabilities - Capability model instead of vendor schemas (see below) Providers (capability-based abstraction): - LLM + Embedding: OpenAI-compatible shape IS the standard, adopted directly - ASR: internal contract is an event stream (partial -> final), because /v1/audio/transcriptions has no partial and dialogue needs it for endpointing. OpenAI adapter degrades to supports_partial=False. - TTS: internal contract carries tags/emotion/style, because /v1/audio/speech has no paralinguistics and [laughter]/[breath] are the core of feeling alive. Unsupported providers are stripped AND reported via Degradation -- silent degradation is forbidden. - Avatar: no de-facto standard, custom RenderCmd protocol driven by State. Core: - mood: dynamical system, slow variables, negativity bias (grudge), numbing after prolonged negativity - bazi: four pillars -> numeric vector; 'ming' is data, not prose - projection: phi, system event -> in-world statement; uncovered events are counted as projection gaps Storage: - SQLite schema, three memory layers, dyad ledger - accessibility floor 0.03 (not 0): forgettable but still there Config split: - models.yaml is the ONLY place model versions live - character.yaml holds world rules / emotion params, no version numbers 58 tests pass; ruff clean.
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
"""共享 fixture。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from cybergril.config import CharacterConfig, ModelsConfig, Settings
|
||||
from cybergril.memory import Store
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo_root() -> Path:
|
||||
return Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def settings(repo_root: Path) -> Settings:
|
||||
return Settings(
|
||||
models=ModelsConfig(),
|
||||
character=CharacterConfig(identity={"y": 2000, "m": 1, "d": 1, "h": 12}),
|
||||
db_path=repo_root / "test.db",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def store(tmp_path: Path) -> Store:
|
||||
s = Store(tmp_path / "test.db")
|
||||
yield s
|
||||
s.close()
|
||||
@@ -0,0 +1,94 @@
|
||||
"""八字编译测试。
|
||||
|
||||
守的是:**命是数值,不是散文。**
|
||||
编译结果必须稳定(同一个四柱永远得到同一个向量),
|
||||
而且强弱必须真的影响敏感度。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from cybergril.core.bazi import (
|
||||
ELEMENTS,
|
||||
Pillars,
|
||||
compile_pillars,
|
||||
day_master_strength,
|
||||
element_scores,
|
||||
ten_god,
|
||||
ten_god_distribution,
|
||||
)
|
||||
|
||||
PILLARS = Pillars(year="甲子", month="丙寅", day="戊午", time="壬子")
|
||||
|
||||
|
||||
def test_pillars_day_master() -> None:
|
||||
assert PILLARS.day_master == "戊"
|
||||
|
||||
|
||||
def test_element_scores_sum_positive() -> None:
|
||||
scores = element_scores(PILLARS)
|
||||
assert set(scores) == set(ELEMENTS)
|
||||
assert sum(scores.values()) > 0
|
||||
assert all(v >= 0 for v in scores.values())
|
||||
|
||||
|
||||
def test_element_scores_rejects_bad_format() -> None:
|
||||
with pytest.raises(ValueError, match="格式错误"):
|
||||
element_scores(Pillars(year="甲", month="丙寅", day="戊午", time="壬子"))
|
||||
|
||||
|
||||
def test_day_master_strength_in_range() -> None:
|
||||
scores = element_scores(PILLARS)
|
||||
s = day_master_strength(PILLARS, scores)
|
||||
assert 0.0 <= s <= 1.0
|
||||
|
||||
|
||||
def test_ten_god_known_relations() -> None:
|
||||
# 木克土(克我),同阳 → 七杀
|
||||
assert ten_god("戊", "甲") == "七杀"
|
||||
# 火生土(生我),同阳 → 偏印
|
||||
assert ten_god("戊", "丙") == "偏印"
|
||||
# 土克水(我克),同阳 → 偏财
|
||||
assert ten_god("戊", "壬") == "偏财"
|
||||
# 土同土,同阳 → 比肩
|
||||
assert ten_god("戊", "戊") == "比肩"
|
||||
|
||||
|
||||
def test_ten_god_distribution_normalized() -> None:
|
||||
dist = ten_god_distribution(PILLARS)
|
||||
assert dist
|
||||
assert abs(sum(dist.values()) - 1.0) < 1e-6
|
||||
assert all(0 <= v <= 1 for v in dist.values())
|
||||
|
||||
|
||||
def test_compile_is_deterministic() -> None:
|
||||
a = compile_pillars(PILLARS)
|
||||
b = compile_pillars(PILLARS)
|
||||
assert a.as_dict() == b.as_dict()
|
||||
|
||||
|
||||
def test_compile_produces_bounded_params() -> None:
|
||||
d = compile_pillars(PILLARS)
|
||||
for key in (
|
||||
"autonomy", "compliance", "expressiveness", "warmth",
|
||||
"anxiety", "aggression", "discipline", "correcting",
|
||||
"solitude_need", "impulsivity", "sharing", "realism",
|
||||
):
|
||||
val = getattr(d, key)
|
||||
assert 0.0 <= val <= 1.0, f"{key} 越界: {val}"
|
||||
|
||||
|
||||
def test_strength_drives_sensitivity() -> None:
|
||||
"""身弱必须更敏感、恢复更慢。这是强弱进入动力学的唯一入口。"""
|
||||
weak = compile_pillars(Pillars(year="甲子", month="乙丑", day="丙子", time="丁亥"))
|
||||
# 用编译结果自身的 strength 反推关系
|
||||
for d in (weak, compile_pillars(PILLARS)):
|
||||
expected_sens = 1.35 - 0.70 * d.strength
|
||||
assert abs(d.sensitivity - expected_sens) < 1e-9
|
||||
expected_rec = 1.60 - 1.20 * d.strength
|
||||
assert abs(d.recovery_scale - expected_rec) < 1e-9
|
||||
|
||||
|
||||
def test_traits_text_non_empty() -> None:
|
||||
assert compile_pillars(PILLARS).traits_text()
|
||||
@@ -0,0 +1,117 @@
|
||||
"""契约层测试。
|
||||
|
||||
这些测试守的是"接口形状",不是实现细节。
|
||||
接口一变,它们就该红——因为所有层都依赖这些形状。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from cybergril.contracts import (
|
||||
Capabilities,
|
||||
Degradation,
|
||||
Expression,
|
||||
Modality,
|
||||
ParaEmotion,
|
||||
ParaEvent,
|
||||
Paralinguistics,
|
||||
Percept,
|
||||
SpeechTag,
|
||||
State,
|
||||
Streaming,
|
||||
Utterance,
|
||||
)
|
||||
|
||||
|
||||
def test_state_clamp_bounds() -> None:
|
||||
s = State(v=5.0, a=3.0, d=-1.0, e=2.0)
|
||||
s.clamp()
|
||||
assert -1.0 <= s.v <= 1.0
|
||||
assert 0.0 <= s.a <= 1.0
|
||||
assert 0.0 <= s.d <= 1.0
|
||||
assert 0.0 <= s.e <= 1.0
|
||||
|
||||
|
||||
def test_state_energy_band() -> None:
|
||||
assert State(e=0.1).energy_band() == "exhausted"
|
||||
assert State(e=0.3).energy_band() == "tired"
|
||||
assert State(e=0.5).energy_band() == "normal"
|
||||
assert State(e=0.9).energy_band() == "energized"
|
||||
|
||||
|
||||
def test_utterance_strip_tags_removes_inline() -> None:
|
||||
u = Utterance(
|
||||
text="真的吗[laughter]……我、我先想想[breath]",
|
||||
speech_tags=(SpeechTag.LAUGHTER, SpeechTag.BREATH),
|
||||
)
|
||||
stripped = u.strip_tags()
|
||||
assert "[laughter]" not in stripped.text
|
||||
assert "[breath]" not in stripped.text
|
||||
assert stripped.speech_tags == ()
|
||||
# 原文不变(frozen)
|
||||
assert "[laughter]" in u.text
|
||||
|
||||
|
||||
def test_utterance_tag_density() -> None:
|
||||
u = Utterance(text="好" * 100, speech_tags=(SpeechTag.LAUGHTER,))
|
||||
assert abs(u.tag_density() - 0.01) < 1e-9
|
||||
|
||||
|
||||
def test_capabilities_tag_support() -> None:
|
||||
caps = Capabilities(
|
||||
modality=Modality.AUDIO,
|
||||
streaming=Streaming.CHUNKED,
|
||||
speech_tags=frozenset({"laughter", "breath"}),
|
||||
)
|
||||
assert caps.tags_supported({"laughter"})
|
||||
assert not caps.tags_supported({"laughter", "sigh"})
|
||||
|
||||
|
||||
def test_capabilities_can() -> None:
|
||||
caps = Capabilities(modality=Modality.TEXT, emotion_control=True)
|
||||
assert caps.can("emotion_control")
|
||||
assert not caps.can("voice_clone")
|
||||
|
||||
|
||||
def test_degradation_readable() -> None:
|
||||
d = Degradation(
|
||||
capability="speech_tags",
|
||||
requested=("sigh",),
|
||||
reason="provider 不支持",
|
||||
suggestion="换 provider",
|
||||
)
|
||||
text = str(d)
|
||||
assert "degraded" in text
|
||||
assert "speech_tags" in text
|
||||
assert "换 provider" in text
|
||||
|
||||
|
||||
def test_paralinguistics_distress() -> None:
|
||||
calm = Paralinguistics(emotion=ParaEmotion.HAPPY)
|
||||
assert not calm.is_distressed()
|
||||
|
||||
crying = Paralinguistics(
|
||||
emotion=ParaEmotion.SAD, events=frozenset({ParaEvent.CRY})
|
||||
)
|
||||
assert crying.is_distressed()
|
||||
assert crying.is_negative()
|
||||
|
||||
|
||||
def test_percept_factories() -> None:
|
||||
p = Percept.asr_final(ts=1000, text="你好", confidence=0.9)
|
||||
assert p.kind.value == "asr_final"
|
||||
assert p.text() == "你好"
|
||||
assert p.confidence == 0.9
|
||||
|
||||
sys_p = Percept.system(ts=0, event="net.error")
|
||||
assert sys_p.system_event() == "net.error"
|
||||
|
||||
|
||||
def test_expression_from_state() -> None:
|
||||
e = Expression.from_state(v=0.8, a=0.9, d=0.2, e=0.1)
|
||||
assert e.happy > 0
|
||||
assert e.tired > 0.8
|
||||
assert e.surprise > 0
|
||||
|
||||
e2 = Expression.from_state(v=0.0, a=0.3, d=0.8, e=0.9)
|
||||
assert e2.happy == 0.0
|
||||
assert e2.sad == 0.0
|
||||
@@ -0,0 +1,133 @@
|
||||
"""情绪动力学测试。
|
||||
|
||||
守两件事:
|
||||
1. 情绪是慢变量(有惯性),不是每轮重置
|
||||
2. 负向偏置真实存在(难过比开心久)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
from cybergril.contracts import State
|
||||
from cybergril.core.mood import (
|
||||
Baseline,
|
||||
Impulse,
|
||||
MoodParams,
|
||||
NumbingTracker,
|
||||
decay,
|
||||
make_impulse,
|
||||
mood_word,
|
||||
step,
|
||||
)
|
||||
|
||||
P = MoodParams.default()
|
||||
B = Baseline()
|
||||
|
||||
|
||||
def test_decay_moves_toward_baseline() -> None:
|
||||
s = State(ts=0, v=-0.8, a=0.9, d=0.9, e=0.1)
|
||||
out = decay(s, B, dt_seconds=3600, params=P)
|
||||
# 一小时后应该更接近基线
|
||||
assert out.v > s.v
|
||||
assert out.a < s.a
|
||||
assert out.e > s.e
|
||||
|
||||
|
||||
def test_negative_bias_slower_recovery() -> None:
|
||||
"""负向恢复必须慢于正向。这是"记仇"的技术来源。
|
||||
|
||||
检验方式:比较"剩余距离占初始距离的比例",再解出时间常数之比。
|
||||
纯正向时 tau_v = 3h;负向时 tau_v ×2 = 6h。
|
||||
"""
|
||||
start_v = 0.5
|
||||
pos = State(ts=0, v=start_v)
|
||||
neg = State(ts=0, v=-start_v)
|
||||
|
||||
gap0_pos = abs(start_v - B.v)
|
||||
gap0_neg = abs(-start_v - B.v)
|
||||
|
||||
after_pos = decay(pos, B, 3600, P)
|
||||
after_neg = decay(neg, B, 3600, P)
|
||||
|
||||
pos_gap = abs(after_pos.v - B.v)
|
||||
neg_gap = abs(after_neg.v - B.v)
|
||||
|
||||
# 同样的时间,负向剩得更多
|
||||
assert neg_gap > pos_gap
|
||||
|
||||
# 剩余比例:exp(-dt/tau)。两比例取对数后相除 = tau_neg / tau_pos
|
||||
pos_frac = pos_gap / gap0_pos
|
||||
neg_frac = neg_gap / gap0_neg
|
||||
assert neg_frac > pos_frac
|
||||
|
||||
tau_ratio = math.log(pos_frac) / math.log(neg_frac)
|
||||
# 配置里 neg_bias["v"] = 2.0
|
||||
assert 1.95 <= tau_ratio <= 2.05
|
||||
|
||||
|
||||
def test_decay_is_monotonic_toward_baseline() -> None:
|
||||
s = State(ts=0, v=-0.9)
|
||||
prev = s.v
|
||||
for _ in range(10):
|
||||
s = decay(s, B, 1800, P)
|
||||
assert s.v > prev
|
||||
prev = s.v
|
||||
|
||||
|
||||
def test_impulse_scales_with_sensitivity() -> None:
|
||||
strong = make_impulse(valence=-0.8, salience=0.9, sensitivity=0.65)
|
||||
weak = make_impulse(valence=-0.8, salience=0.9, sensitivity=1.35)
|
||||
assert abs(weak.v) > abs(strong.v)
|
||||
|
||||
|
||||
def test_impulse_direction() -> None:
|
||||
bad = make_impulse(valence=-0.7, salience=0.8, sensitivity=1.0)
|
||||
good = make_impulse(valence=0.7, salience=0.8, sensitivity=1.0)
|
||||
assert bad.v < 0 < good.v
|
||||
# 好事也会消耗精力
|
||||
assert bad.e <= 0 and good.e <= 0
|
||||
|
||||
|
||||
def test_step_clamps_and_advances_time() -> None:
|
||||
s = State(ts=1000, v=0.0)
|
||||
huge = Impulse(v=99.0, a=99.0)
|
||||
out = step(s, B, dt_seconds=60, params=P, impulses=(huge,))
|
||||
assert -1.0 <= out.v <= 1.0
|
||||
assert 0.0 <= out.a <= 1.0
|
||||
assert out.ts == 1000 + 60_000
|
||||
|
||||
|
||||
def test_step_no_impulse_returns_valid_state() -> None:
|
||||
s = State(ts=0, v=0.2, a=0.4, d=0.5, e=0.6)
|
||||
out = step(s, B, 60, P)
|
||||
assert isinstance(out, State)
|
||||
out.clamp()
|
||||
|
||||
|
||||
def test_mood_word_bands() -> None:
|
||||
assert mood_word(v=0.6, a=0.7, e=0.8) == "雀跃"
|
||||
assert mood_word(v=-0.8, a=0.4, e=0.6) == "低落"
|
||||
assert mood_word(v=0.0, a=0.3, e=0.5) == "平静"
|
||||
assert mood_word(v=0.0, a=0.3, e=0.1) == "疲惫"
|
||||
|
||||
|
||||
def test_numbing_kicks_in_after_threshold() -> None:
|
||||
tracker = NumbingTracker(after_hours=6.0, drop=0.15)
|
||||
s = State(ts=0, v=-0.5)
|
||||
|
||||
# 刚开始:无影响
|
||||
assert tracker.update(s) == 0.0
|
||||
|
||||
# 推进 8 小时
|
||||
s2 = State(ts=8 * 3600 * 1000, v=-0.5)
|
||||
offset = tracker.update(s2)
|
||||
assert offset < 0
|
||||
|
||||
|
||||
def test_numbing_resets_on_positive() -> None:
|
||||
tracker = NumbingTracker(after_hours=1.0, drop=0.15)
|
||||
tracker.update(State(ts=0, v=-0.5))
|
||||
tracker.update(State(ts=3 * 3600 * 1000, v=-0.5)) # 已经麻木
|
||||
tracker.update(State(ts=4 * 3600 * 1000, v=0.5)) # 转正
|
||||
assert tracker.update(State(ts=5 * 3600 * 1000, v=0.5)) == 0.0
|
||||
@@ -0,0 +1,67 @@
|
||||
"""投影层测试。
|
||||
|
||||
守的是本体 C-膜 的落地机制:
|
||||
未覆盖的事件必须落到 fallback,并**计数**。
|
||||
projection_gap 的行数就是"现实感泄漏"的度量。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from cybergril.core.projection import (
|
||||
FALLBACK,
|
||||
Projector,
|
||||
violates_absence_rule,
|
||||
)
|
||||
|
||||
|
||||
def test_known_event_projects() -> None:
|
||||
p = Projector()
|
||||
assert p("process.wake") == "刚醒。"
|
||||
assert p.gap_count == 0
|
||||
|
||||
|
||||
def test_unknown_event_falls_back_and_counts() -> None:
|
||||
gaps = []
|
||||
p = Projector(on_gap=gaps.append)
|
||||
out = p("totally.unknown.event", {"x": 1})
|
||||
assert out == FALLBACK
|
||||
assert p.gap_count == 1
|
||||
assert gaps[0].event_key == "totally.unknown.event"
|
||||
|
||||
|
||||
def test_register_fills_gap() -> None:
|
||||
p = Projector()
|
||||
p("new.event")
|
||||
assert p.gap_count == 1
|
||||
|
||||
p.register("new.event", "这个我说得上来了。")
|
||||
assert p("new.event") == "这个我说得上来了。"
|
||||
# 计数不因补表而回退
|
||||
assert p.gap_count == 1
|
||||
|
||||
|
||||
def test_custom_table_overrides() -> None:
|
||||
p = Projector({"process.wake": "醒了。"})
|
||||
assert p("process.wake") == "醒了。"
|
||||
|
||||
|
||||
def test_no_secrets_leak_into_projection() -> None:
|
||||
"""投影只输出世界内陈述,不输出技术细节。"""
|
||||
p = Projector()
|
||||
forbidden = ["进程", "服务", "错误码", "API", "超时", "token"]
|
||||
for key in p.known_keys():
|
||||
text = p(key)
|
||||
for f in forbidden:
|
||||
assert f not in text, f"{key} 的投影泄漏了技术词 {f!r}"
|
||||
|
||||
|
||||
def test_absence_rule_detects_forbidden_patterns() -> None:
|
||||
assert violates_absence_rule("我一直在等你,等了好久")
|
||||
assert violates_absence_rule("你会把我删掉吗")
|
||||
assert not violates_absence_rule("这几天我这边发生了点事")
|
||||
|
||||
|
||||
def test_all_default_projections_are_nonempty() -> None:
|
||||
p = Projector()
|
||||
for key in p.known_keys():
|
||||
assert p(key).strip(), f"{key} 的投影为空"
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Provider 层测试。
|
||||
|
||||
核心守的是这条设计判断:
|
||||
OpenAI 兼容是 adapter,不是标准。
|
||||
适配器用不了某项能力时,必须**显式降级**,不能静默丢弃。
|
||||
|
||||
如果哪天有人把 TTS 的 plan() 改成"静默删掉不支持的标签",
|
||||
test_plan_reports_missing_paralinguistics 会红。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from cybergril.contracts import AudioChunk, LLMMessage
|
||||
from cybergril.providers import (
|
||||
EchoLLM,
|
||||
HeuristicTurn,
|
||||
Provider,
|
||||
ProviderError,
|
||||
Registry,
|
||||
ScriptedASR,
|
||||
SilenceTTS,
|
||||
SpeechRequest,
|
||||
TurnDecision,
|
||||
bootstrap_registry,
|
||||
registry,
|
||||
)
|
||||
from cybergril.providers.asr import ASREventType
|
||||
|
||||
# ---------------------------------------------------------------- 注册表
|
||||
|
||||
|
||||
def test_registry_unknown_provider_raises() -> None:
|
||||
reg = Registry()
|
||||
with pytest.raises(ProviderError, match="未知的 llm provider"):
|
||||
reg.create("llm", "nope")
|
||||
|
||||
|
||||
def test_bootstrap_registers_builtins() -> None:
|
||||
bootstrap_registry()
|
||||
assert "echo" in registry.available("llm")
|
||||
assert "scripted" in registry.available("asr")
|
||||
assert "silence" in registry.available("tts")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- TTS 规划
|
||||
|
||||
|
||||
def test_plan_keeps_tags_when_supported() -> None:
|
||||
tts = SilenceTTS(with_tags=True)
|
||||
req = SpeechRequest(text="真的吗", tags=("laughter", "breath"), emotion="happy")
|
||||
planned = tts.plan(req)
|
||||
assert planned.request.tags == ("laughter", "breath")
|
||||
assert planned.request.emotion == "happy"
|
||||
assert planned.degradations == ()
|
||||
assert not planned.lost_paralinguistics
|
||||
|
||||
|
||||
def test_plan_reports_missing_paralinguistics() -> None:
|
||||
"""关键测试:不支持副语言的 provider 必须上报,不能装没事。"""
|
||||
tts = SilenceTTS(with_tags=False)
|
||||
req = SpeechRequest(text="真的吗", tags=("laughter", "breath"), emotion="sad")
|
||||
planned = tts.plan(req)
|
||||
|
||||
# 标签被剥掉
|
||||
assert planned.request.tags == ()
|
||||
# 但**必须**有降级记录
|
||||
assert planned.lost_paralinguistics
|
||||
caps = {d.capability for d in planned.degradations}
|
||||
assert "speech_tags" in caps
|
||||
assert "emotion_control" in caps
|
||||
|
||||
|
||||
def test_plan_partial_tag_support() -> None:
|
||||
"""只支持一部分标签时,只剥掉不支持的,并上报。"""
|
||||
tts = SilenceTTS(with_tags=True) # 支持 laughter/breath/sigh/pause
|
||||
req = SpeechRequest(text="唉", tags=("laughter", "cry")) # cry 不支持
|
||||
planned = tts.plan(req)
|
||||
assert planned.request.tags == ("laughter",)
|
||||
assert any(d.capability == "speech_tags" for d in planned.degradations)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- LLM
|
||||
|
||||
|
||||
async def test_echo_llm_streams_and_closes() -> None:
|
||||
llm = EchoLLM(prefix="echo: ")
|
||||
parts: list[str] = []
|
||||
done = False
|
||||
async for d in llm.stream([LLMMessage(role="user", content="你好")]):
|
||||
if d.done:
|
||||
done = True
|
||||
parts.append(d.text)
|
||||
assert "".join(parts) == "echo: 你好"
|
||||
assert done
|
||||
|
||||
|
||||
async def test_echo_llm_complete() -> None:
|
||||
llm = EchoLLM()
|
||||
resp = await llm.complete([LLMMessage(role="user", content="abc")])
|
||||
assert resp.text == "abc"
|
||||
assert resp.finish_reason == "stop"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- ASR
|
||||
|
||||
|
||||
async def test_scripted_asr_emits_partial_then_final() -> None:
|
||||
asr = ScriptedASR(["你好呀。"])
|
||||
events = []
|
||||
|
||||
async def _audio():
|
||||
yield AudioChunk(data=b"\x00" * 320, ts=0)
|
||||
|
||||
async for ev in asr.stream(_audio()):
|
||||
events.append(ev)
|
||||
|
||||
assert events[-1].type is ASREventType.FINAL
|
||||
assert events[-1].text == "你好呀。"
|
||||
assert any(e.type is ASREventType.PARTIAL for e in events)
|
||||
|
||||
|
||||
async def test_asr_capabilities_claim_partial() -> None:
|
||||
asr = ScriptedASR()
|
||||
assert asr.capabilities.supports_partial is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Turn
|
||||
|
||||
|
||||
async def test_turn_waits_on_hesitation() -> None:
|
||||
turn = HeuristicTurn(min_ms=100, hard_end_ms=800)
|
||||
|
||||
sig = await turn.predict("我想想……那个", silence_ms=300)
|
||||
assert sig.decision is TurnDecision.CONTINUE
|
||||
|
||||
sig2 = await turn.predict("我想想……那个", silence_ms=900)
|
||||
assert sig2.decision is TurnDecision.END # 兜底阈值
|
||||
|
||||
|
||||
async def test_turn_ends_on_sentence_punctuation() -> None:
|
||||
turn = HeuristicTurn(min_ms=100, hard_end_ms=800)
|
||||
sig = await turn.predict("今天天气不错。", silence_ms=300)
|
||||
assert sig.decision is TurnDecision.END
|
||||
|
||||
|
||||
async def test_turn_waits_when_too_short_silence() -> None:
|
||||
turn = HeuristicTurn(min_ms=150, hard_end_ms=800)
|
||||
sig = await turn.predict("说完了。", silence_ms=50)
|
||||
assert sig.decision is TurnDecision.CONTINUE
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 基类
|
||||
|
||||
|
||||
def test_provider_repr_contains_caps() -> None:
|
||||
p = EchoLLM()
|
||||
assert isinstance(p, Provider)
|
||||
assert "native" in repr(p)
|
||||
@@ -0,0 +1,110 @@
|
||||
"""存储层测试。
|
||||
|
||||
守的是遗忘的**下限**:accessibility 会衰减,但永不归零。
|
||||
这是 availability / accessibility 双阈值的实现——
|
||||
想不起来,但还在,情绪线索能唤起。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from cybergril.memory import Store
|
||||
|
||||
|
||||
def test_schema_initialises(store: Store) -> None:
|
||||
rows = store.query(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"
|
||||
)
|
||||
names = {r["name"] for r in rows}
|
||||
for expected in (
|
||||
"bazi_core",
|
||||
"identity_change_log",
|
||||
"state_snapshot",
|
||||
"life_event",
|
||||
"mem_episodic",
|
||||
"mem_semantic",
|
||||
"mem_relational",
|
||||
"dyad_state",
|
||||
"dyad_event",
|
||||
"projection_gap",
|
||||
):
|
||||
assert expected in names, f"缺表 {expected}"
|
||||
|
||||
|
||||
def test_save_and_read_state(store: Store) -> None:
|
||||
store.save_state(v=-0.4, a=0.6, d=0.3, e=0.5, mood_word="闷闷的")
|
||||
row = store.last_state()
|
||||
assert row is not None
|
||||
assert abs(row["valence"] - (-0.4)) < 1e-9
|
||||
assert row["mood_word"] == "闷闷的"
|
||||
|
||||
|
||||
def test_add_episodic_and_fts(store: Store) -> None:
|
||||
eid = store.add_episodic(
|
||||
role="user",
|
||||
raw="我今天很难过",
|
||||
salience=0.85,
|
||||
affect={"v": -0.7, "a": 0.6, "d": 0.3},
|
||||
)
|
||||
assert eid > 0
|
||||
|
||||
row = store.query_one("SELECT * FROM mem_episodic WHERE id=?", (eid,))
|
||||
assert row is not None
|
||||
assert row["salience"] == 0.85
|
||||
assert row["accessibility"] == 1.0
|
||||
|
||||
|
||||
def test_decay_never_reaches_zero(store: Store) -> None:
|
||||
"""最关键的一条:遗忘有下限。"""
|
||||
store.add_episodic(role="user", raw="一件小事", salience=0.1)
|
||||
store.decay_accessibility(dt_hours=24 * 365, floor=0.03)
|
||||
|
||||
row = store.query_one("SELECT accessibility FROM mem_episodic LIMIT 1")
|
||||
assert row is not None
|
||||
assert row["accessibility"] >= 0.03
|
||||
assert row["accessibility"] < 0.1 # 确实衰减了
|
||||
|
||||
|
||||
def test_high_salience_decays_slower(store: Store) -> None:
|
||||
store.add_episodic(role="user", raw="重要的事", salience=1.0)
|
||||
store.add_episodic(role="user", raw="不重要的事", salience=0.0)
|
||||
store.decay_accessibility(dt_hours=48, floor=0.03)
|
||||
|
||||
rows = store.query(
|
||||
"SELECT salience, accessibility FROM mem_episodic ORDER BY salience DESC"
|
||||
)
|
||||
high, low = rows[0], rows[1]
|
||||
assert high["accessibility"] > low["accessibility"]
|
||||
|
||||
|
||||
def test_reinforce_raises_accessibility(store: Store) -> None:
|
||||
eid = store.add_episodic(role="user", raw="会被想起的事", salience=0.5)
|
||||
store.decay_accessibility(dt_hours=100, floor=0.03)
|
||||
before = store.query_one(
|
||||
"SELECT accessibility, recall_count FROM mem_episodic WHERE id=?", (eid,)
|
||||
)
|
||||
|
||||
store.reinforce(eid, boost=0.25)
|
||||
after = store.query_one(
|
||||
"SELECT accessibility, recall_count FROM mem_episodic WHERE id=?", (eid,)
|
||||
)
|
||||
|
||||
assert after["accessibility"] > before["accessibility"]
|
||||
assert after["recall_count"] == before["recall_count"] + 1
|
||||
|
||||
|
||||
def test_dyad_persistence(store: Store) -> None:
|
||||
eid = store.add_dyad_event(kind="hurt", summary="他忘了约定", severity=-0.6)
|
||||
store.save_dyad(trust=0.4, intimacy=0.5, debt=-0.6, security=0.4, unresolved=[eid])
|
||||
|
||||
row = store.last_dyad()
|
||||
assert row is not None
|
||||
assert abs(row["debt"] - (-0.6)) < 1e-9
|
||||
|
||||
ev = store.query_one("SELECT * FROM dyad_event WHERE id=?", (eid,))
|
||||
assert ev is not None
|
||||
assert ev["severity"] < 0
|
||||
|
||||
|
||||
def test_projection_gap_recorded(store: Store) -> None:
|
||||
store.record_projection_gap("mystery.event", {"detail": "x"})
|
||||
assert store.projection_gap_count() == 1
|
||||
Reference in New Issue
Block a user