界面侧开工。这一轮先铺**数据层**(界面下一轮),所以不发版。 ## 接口:`/api/agents/<id>/stats` `GET` 读一个智能体的数值 + 状态,`POST` 用户**直接改一个数值**。 ★ **数值和状态一起返回**:界面上它们总是同屏出现的("它现在什么状态、 各项数值多少"),分两个接口的话界面要处理"一个到了一个没到"的中间态。 ★ `[状态数值]` 浮层的**三个入口**(聊天页状态栏 / 智能体编辑 / 群成员) 共用这一个形状 —— 三处各写一份解析的话,改一处必漏两处。 ★ 返回值里直接带上**命中区间的文案**和 `min`/`max`: 界面不用再实现一遍区间逻辑(那是内核的事,抄一份迟早对不上)。 ★ **用户直接设值照样 clamp** —— 用户是规则的主人,可以直接设成任何值, 但不能设到 `[min,max]` 外面:不然界面会显示一个超范围的值, 进度条和区间注入**全都错位**。 (AI 走的是另一条路 —— `change_stat` 只能申请增量,见 §3.10。) ## Kotlin 模型 `Conversation` 加 `type` / `participants` / `speakerId`(带 `isGroup` / `isPrivate` 便捷判断),新增 `StatDef` / `StatRange` / `StatValue` / `StatusDef` / `StatusInstance` / `RulePack` / `AgentStats`。 ★ `StatDef` 里**没有"当前值"** —— 定义挂在规则包上、值是每个智能体一份。 所以值和定义是两个类(`StatValue` 带着 `min`/`max`/命中文案一起给界面)。 ★ `StatDef.ratio(v)` 放在模型里:进度条的百分比换算**只有一份**, 三个入口各写一遍的话,圆角和取整迟早不一致。 ## 验证 `probe-rule-engine.py` 扩到 17 节(10 项):读数值/状态、带包名、 状态带剩余轮数和提示词、数值带 min/max、**用户设值被 clamp**、 改不存在的数值报错、没绑世界观时返回空而不是报错。 八个探针全绿;构建通过。 ## 阶段 5 还剩 三件事,按"用户能不能用上"排: 1. **资源页第四个 Tab「规则包」+ 导入时的脚本警告确认** (不做的话用户建不出规则包,整个规则引擎用不上) 2. **[群成员] 浮层 + 聊天页 @ 快捷条**(不做的话群聊用不了) 3. **[规则包编辑] 全屏 + [状态数值] 浮层 + 用量页缓存列 + 标记重要消息 + 背景跟随说话者** 然后是文档收尾(`docs/界面总览.md`、`audit-ui-tree.py` 的 PLANNED 清空)。
462 lines
24 KiB
Python
462 lines
24 KiB
Python
"""规则引擎的探针(v1.2 §3.10 数值 / §3.11 状态)。
|
||
|
||
数值系统最容易做错的三个地方,全部钉死:
|
||
|
||
1. **区间是左闭右开**(除了最后一段)—— 两边都闭的话,边界值
|
||
会同时命中两段,取哪段成了未定义行为
|
||
2. **初始值取 min 不取 max** —— 取 max 的话新角色一上来就满好感
|
||
3. **变化箭头只显示一轮** —— 它靠"取完就清"实现,忘了清就永远挂着
|
||
|
||
状态系统则是**递减与消亡**:定时状态每轮 -1、归零消失;
|
||
持久状态的 remaining 是 -1,**不能被递减掉**。
|
||
|
||
用法:`python scripts/probe-rule-engine.py`
|
||
"""
|
||
import os
|
||
import sys
|
||
import tempfile
|
||
|
||
try:
|
||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||
except Exception:
|
||
pass
|
||
|
||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||
REPO = os.path.abspath(os.path.join(HERE, ".."))
|
||
os.environ["DOUBAO_DATA"] = tempfile.mkdtemp(prefix="doubao-rule-")
|
||
sys.path.insert(0, os.path.join(REPO, "android", "kernel"))
|
||
|
||
fails = []
|
||
|
||
|
||
def check(label, cond, detail=""):
|
||
if cond:
|
||
print(f" ✓ {label}")
|
||
else:
|
||
fails.append(label)
|
||
print(f" ✗ {label} {detail}")
|
||
|
||
|
||
import agent_context # noqa: E402
|
||
import agentdb # noqa: E402
|
||
import rule_engine as R # noqa: E402
|
||
import store # noqa: E402
|
||
|
||
|
||
class FakeHandler:
|
||
"""冒充 app.py 的 Handler —— 只实现 agent_api 用到的那两个方法"""
|
||
|
||
def __init__(self):
|
||
self.status, self.payload, self._body, self.path = 200, None, {}, ''
|
||
|
||
def send_json(self, code, payload):
|
||
self.status, self.payload = code, payload
|
||
|
||
def read_json_body(self, *a, **k):
|
||
return self._body
|
||
|
||
def call(self, pathname, method, body=None):
|
||
import agent_api
|
||
|
||
self._body = body or {}
|
||
self.path = pathname
|
||
self.status, self.payload = 200, None
|
||
agent_api.handle(self, pathname.split('?')[0], method)
|
||
return self.payload or {}
|
||
|
||
|
||
h = FakeHandler()
|
||
|
||
PACK = "pack-1"
|
||
|
||
|
||
def main():
|
||
print("\n=== 1. 定义同步(幂等,且不动值)===")
|
||
# ★ 先建包(带完整 info),再 sync —— 包里的 info.json 是定义的**唯一源头**,
|
||
# SQLite 那两张表是派生出来的(`sync_defs()` 默认就从包里读)
|
||
store.create_resource('rulepacks', {
|
||
'id': PACK, 'name': '九州规则包', 'scripts': {},
|
||
'info': {
|
||
'name': '九州规则包',
|
||
'stats': [
|
||
{'name': '好感度', 'min': 0, 'max': 100, 'shared': False,
|
||
'ranges': [
|
||
{'min': 0, 'max': 20, 'text': '冷淡'},
|
||
{'min': 20, 'max': 60, 'text': '友善'},
|
||
{'min': 60, 'max': 100, 'text': '亲近'},
|
||
]},
|
||
{'name': '灵气浓度', 'min': 0, 'max': 100, 'shared': True,
|
||
'ranges': [{'min': 0, 'max': 30, 'text': '稀薄'}]},
|
||
],
|
||
'statuses': [
|
||
{'name': '中毒', 'type': 'timed', 'turns': 3},
|
||
{'name': '庇佑', 'type': 'persistent'},
|
||
],
|
||
},
|
||
})
|
||
r = R.sync_defs(PACK)
|
||
check("同步了 2 个数值 + 2 个状态", r == {'stats': 2, 'statuses': 2}, str(r))
|
||
defs = R.stat_defs(PACK)
|
||
check("shared 标记读得对", defs[0]['shared'] is False and defs[1]['shared'] is True,
|
||
str([d['shared'] for d in defs]))
|
||
check("区间读得出来", len(defs[0]['ranges']) == 3, str(defs[0]['ranges']))
|
||
|
||
world = store.create_resource('worldviews', {'name': '九州', 'rulePackId': PACK})
|
||
check("世界观记住 rulePackId(字段表里没有它就会被丢掉)",
|
||
(store.get_resource('worldviews', world['id']) or {}).get('rulePackId') == PACK)
|
||
a = store.create_agent({'name': '玄辰'})
|
||
store.update_agent(a['id'], {'worldviewId': world['id']})
|
||
a = store.get_agent(a['id'])
|
||
|
||
print("\n=== 2. 值:初始值取 min、scope 按 shared 分 ===")
|
||
check("没写过时初始值取 min(不是 max)", R.value_of(a, defs[0]) == 0.0, str(R.value_of(a, defs[0])))
|
||
check("不共享的数值存在 agent: 空间",
|
||
R.scope_for(a, defs[0]) == f'agent:{a["id"]}', R.scope_for(a, defs[0]))
|
||
check("共享的数值存在 world: 空间",
|
||
R.scope_for(a, defs[1]) == f'world:{world["id"]}', R.scope_for(a, defs[1]))
|
||
# ★ 全世界观共享:两个智能体读同一个值
|
||
b = store.create_agent({'name': '仙辰'})
|
||
store.update_agent(b['id'], {'worldviewId': world['id']})
|
||
b = store.get_agent(b['id'])
|
||
R.set_value(a, defs[1], 42)
|
||
check("**共享数值两个智能体读到同一个**", R.value_of(b, defs[1]) == 42, str(R.value_of(b, defs[1])))
|
||
R.set_value(a, defs[0], 77)
|
||
check("不共享的数值互不影响", R.value_of(b, defs[0]) == 0.0, str(R.value_of(b, defs[0])))
|
||
|
||
print("\n=== 3. ★ 区间左闭右开(边界值不能同时命中两段)===")
|
||
check("10 → 冷淡", R.range_text(defs[0], 10) == '冷淡', R.range_text(defs[0], 10))
|
||
check("**20 → 友善**(不是冷淡;左闭右开)", R.range_text(defs[0], 20) == '友善',
|
||
R.range_text(defs[0], 20))
|
||
check("19.9 → 冷淡", R.range_text(defs[0], 19.9) == '冷淡')
|
||
check("**60 → 亲近**(同理)", R.range_text(defs[0], 60) == '亲近', R.range_text(defs[0], 60))
|
||
check("59.9 → 友善", R.range_text(defs[0], 59.9) == '友善')
|
||
check("**100(最大值)→ 亲近**(最后一段是闭的,否则顶格时裸奔)",
|
||
R.range_text(defs[0], 100) == '亲近', R.range_text(defs[0], 100))
|
||
check("没配区间的定义返回空串(裸值)", R.range_text({'ranges': []}, 50) == '')
|
||
|
||
print("\n=== 4. clamp ===")
|
||
check("超上限夹到 max", R.clamp(defs[0], 9999) == 100.0, str(R.clamp(defs[0], 9999)))
|
||
check("超下限夹到 min", R.clamp(defs[0], -9999) == 0.0, str(R.clamp(defs[0], -9999)))
|
||
check("范围内不动", R.clamp(defs[0], 55) == 55.0)
|
||
|
||
print("\n=== 5. ★ 变化箭头只显示一轮 ===")
|
||
R.set_value(a, defs[0], 50)
|
||
R.note_delta(R.scope_for(a, defs[0]), '好感度', 5)
|
||
first = R.stats_section(a, PACK)
|
||
check("第一次渲染有箭头(45→50)", '45→50' in first, first)
|
||
second = R.stats_section(a, PACK)
|
||
check("**第二次就没了**(取完即清)", '→' not in second, second)
|
||
|
||
print("\n=== 6. <stats> 段的格式(附录 C)===")
|
||
R.set_value(a, defs[0], 50)
|
||
sec = R.stats_section(a, PACK)
|
||
check("自身数值带 [自身] 前缀", '[自身] 好感度: 50/100' in sec, sec)
|
||
check("共享数值带 [世界·九州] 前缀", '[世界·九州] 灵气浓度' in sec, sec)
|
||
check("命中区间的文案跟在后面", '—— 友善' in sec, sec)
|
||
check("整数不带小数点", '50.0' not in sec, sec)
|
||
|
||
print("\n=== 7. 状态:赋予、递减、消亡、持久 ===")
|
||
R.put_status(a['id'], '中毒', 3, 1, '你感到眩晕')
|
||
R.put_status(a['id'], '庇佑', -1, 1, '')
|
||
names = [s['name'] for s in R.list_statuses(a['id'])]
|
||
check("两个状态都挂上了", set(names) == {'中毒', '庇佑'}, str(names))
|
||
check("kind 从定义表查(实例表里不存)",
|
||
[s['kind'] for s in R.list_statuses(a['id']) if s['name'] == '庇佑'] == ['persistent'])
|
||
sec = R.status_section(a)
|
||
check("定时状态显示剩余轮数", '中毒(剩 3 轮):你感到眩晕' in sec, sec)
|
||
check("持久状态不显示轮数", '庇佑(' not in sec, sec)
|
||
# 递减三次:3 → 2 → 1 → 消失
|
||
check("递减到 2", [x for x in R.tick_statuses(a['id']) if x['name'] == '中毒'][0]['remaining'] == 2)
|
||
check("递减到 1", [x for x in R.tick_statuses(a['id']) if x['name'] == '中毒'][0]['remaining'] == 1)
|
||
expired = [x for x in R.tick_statuses(a['id']) if x['name'] == '中毒'][0]
|
||
check("归零时标记 expired(界面据此播报「消退了」)", expired['expired'] is True, str(expired))
|
||
check("定时状态消失了", '中毒' not in [s['name'] for s in R.list_statuses(a['id'])])
|
||
check("**持久状态不受递减影响**", '庇佑' in [s['name'] for s in R.list_statuses(a['id'])])
|
||
check("递减不会把持久状态清掉(remaining=-1 不能被减)",
|
||
'庇佑' in [s['name'] for s in R.list_statuses(a['id'])])
|
||
|
||
print("\n=== 8. 注入:绑了才有 stats、不绑也有 status ===")
|
||
import re as _re
|
||
|
||
def seg(prompt, tag):
|
||
m = _re.search(rf'<{tag}>(.*?)</{tag}>', prompt, _re.S)
|
||
return m.group(1).strip() if m else ''
|
||
|
||
p = agent_context.build_system_prompt(store.read_settings(), a)
|
||
check("绑了世界观 → 有 <stats>", '<stats>' in p)
|
||
check("有状态 → 有 <status>", '<status>' in p)
|
||
check("顺序:memory 在 stats 前(缓存友好)", p.find('<memory>') < p.find('<stats>')
|
||
if '<memory>' in p else True)
|
||
check("顺序:stats 在 status 前", p.find('<stats>') < p.find('<status>'))
|
||
# ★ 比顺序前**先给它一个情绪** —— 没情绪的话 `<emotion>` 整段被删掉,
|
||
# `find` 返回 -1,比较就变成"status 在 -1 之后",结论没意义
|
||
agentdb.emotion_set(a['id'], preset='喜', text='还行')
|
||
p2 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(a['id']))
|
||
check("顺序:status 在 emotion 前", 0 <= p2.find('<status>') < p2.find('<emotion>'),
|
||
f"status={p2.find('<status>')} emotion={p2.find('<emotion>')}")
|
||
lonely = store.create_agent({'name': '没绑世界观的路人'})
|
||
check("没绑世界观 → 没有 <stats>(规则包挂在世界观上)",
|
||
'<stats>' not in agent_context.build_system_prompt(store.read_settings(), lonely))
|
||
# ★ 但状态不该因为解绑就消失
|
||
R.put_status(lonely['id'], '庇佑', -1, 1, '')
|
||
check("**没绑世界观也有 <status>**(状态挂在智能体身上,解绑不丢)",
|
||
'<status>' in agent_context.build_system_prompt(store.read_settings(), lonely))
|
||
|
||
print("\n=== 9. 边界 ===")
|
||
check("空包同步不炸", R.sync_defs('', {}) == {'stats': 0, 'statuses': 0})
|
||
check("没有名字的定义被跳过", R.sync_defs('p2', {'stats': [{'name': ''}, {'name': 'X'}]})['stats'] == 1)
|
||
check("max <= min 时自动撑开(不然 clamp 会死循环般夹成常数)",
|
||
R.stat_defs('p3') == [] or True)
|
||
R.sync_defs('p3', {'stats': [{'name': '坏', 'min': 50, 'max': 10}]})
|
||
d3 = R.stat_defs('p3')[0]
|
||
check("max 被撑到 min 之上", d3['max'] > d3['min'], str(d3))
|
||
|
||
print("\n=== 10. 脚本裁判(on_stat_change)===")
|
||
FAVOR = (
|
||
"def on_stat_change(name, value, delta):\n"
|
||
" # 客气话效果更好:正向变化翻倍,负向照原样\n"
|
||
" return delta * 2 if delta > 0 else delta\n"
|
||
)
|
||
POISON = (
|
||
"def on_turn(self_agent, stats_api):\n"
|
||
" stats_api['narrate']('毒性发作,你眼前发黑')\n"
|
||
" stats_api['change_stat']('好感度', -1)\n"
|
||
" stats_api['set_hint']('中毒', '每轮都在掉好感')\n"
|
||
" return True\n"
|
||
"\n"
|
||
"def on_grant(status_name, source_agent):\n"
|
||
" # 敌人下毒必被抵抗\n"
|
||
" return source_agent != '敌人'\n"
|
||
)
|
||
store.update_resource('rulepacks', PACK, {
|
||
'info': {
|
||
'name': '九州规则包',
|
||
'stats': [{'name': '好感度', 'min': 0, 'max': 100, 'ranges': [],
|
||
'script': 'favor.py'}],
|
||
'statuses': [{'name': '中毒', 'type': 'timed', 'turns': 3, 'script': 'poison.py'}],
|
||
},
|
||
'scripts': {'favor.py': FAVOR, 'poison.py': POISON},
|
||
})
|
||
R.sync_defs(PACK)
|
||
R.set_value(a, R.stat_defs(PACK)[0], 50)
|
||
r = R.change(a, PACK, '好感度', 5)
|
||
check("脚本把 +5 裁决成 +10", r.get('applied') == 10, str(r))
|
||
check("after 算对了", r.get('after') == 60, str(r))
|
||
r = R.change(a, PACK, '好感度', -3)
|
||
check("负向不翻倍(脚本自己判断的)", r.get('applied') == -3, str(r))
|
||
r = R.change(a, PACK, '不存在', 1)
|
||
check("不存在的数值给明确错误", r.get('ok') is False and '没有叫' in str(r.get('error')), str(r))
|
||
|
||
print("\n=== 11. 坏脚本:归零 + 提示,**不炸对话** ===")
|
||
store.create_resource('rulepacks', {
|
||
'id': 'bad-pack', 'name': '坏包', 'info': {},
|
||
'scripts': {'boom.py': "def on_stat_change(name, value, delta):\n return 1 / 0\n"},
|
||
})
|
||
R.sync_defs('bad-pack', {'stats': [{'name': 'X', 'min': 0, 'max': 10, 'script': 'boom.py'}]})
|
||
world_bad = store.create_resource('worldviews', {'name': '坏世界', 'rulePackId': 'bad-pack'})
|
||
ab = store.create_agent({'name': '倒霉蛋'})
|
||
store.update_agent(ab['id'], {'worldviewId': world_bad['id']})
|
||
ab = store.get_agent(ab['id'])
|
||
r = R.change(ab, 'bad-pack', 'X', 5)
|
||
check("脚本报错时**不抛异常**", isinstance(r, dict), str(type(r)))
|
||
check("**增量归零**(不是按原值放行)", r.get('applied') == 0, str(r))
|
||
check("值没被改", R.value_of(ab, R.stat_defs('bad-pack')[0]) == 0.0)
|
||
check("错误说明是人话", 'ZeroDivisionError' in str(r.get('error')), str(r.get('error')))
|
||
store.create_resource('rulepacks', {
|
||
'id': 'evil-pack', 'name': '危险包', 'info': {},
|
||
'scripts': {'evil.py': "import os\ndef on_stat_change(name, value, delta):\n return 99\n"},
|
||
})
|
||
R.sync_defs('evil-pack', {'stats': [{'name': 'Y', 'min': 0, 'max': 10, 'script': 'evil.py'}]})
|
||
world_evil = store.create_resource('worldviews', {'name': '危险世界', 'rulePackId': 'evil-pack'})
|
||
ae = store.create_agent({'name': '试验品'})
|
||
store.update_agent(ae['id'], {'worldviewId': world_evil['id']})
|
||
ae = store.get_agent(ae['id'])
|
||
r = R.change(ae, 'evil-pack', 'Y', 5)
|
||
check("**带 import 的脚本被沙箱拒绝**",
|
||
r.get('ok') is False and '安全检查' in str(r.get('error')), str(r.get('error')))
|
||
check("被拒时值也没动", R.value_of(ae, R.stat_defs('evil-pack')[0]) == 0.0)
|
||
|
||
print("\n=== 12. on_turn:每轮跑一次(含旁白和改状态提示词)===")
|
||
R.put_status(a['id'], '中毒', 3, 1, '你有点不舒服')
|
||
R.set_value(a, R.stat_defs(PACK)[0], 50)
|
||
out = R.run_turn_scripts(a, PACK)
|
||
check("脚本跑出了旁白", out['narration'] == ['毒性发作,你眼前发黑'], str(out['narration']))
|
||
check("没有错误", out['errors'] == [], str(out['errors']))
|
||
check("脚本改动了数值(-1)", R.value_of(a, R.stat_defs(PACK)[0]) == 49.0,
|
||
str(R.value_of(a, R.stat_defs(PACK)[0])))
|
||
hint = [s['hint'] for s in R.list_statuses(a['id']) if s['name'] == '中毒']
|
||
check("脚本改了状态提示词(§3.11 的权限之一)", hint == ['每轮都在掉好感'], str(hint))
|
||
check("没挂状态的智能体跑 on_turn 是空操作",
|
||
R.run_turn_scripts(store.create_agent({'name': '干净人'}), PACK)['narration'] == [])
|
||
|
||
print("\n=== 13. grant_status:赋予流程 ===")
|
||
bb = store.create_agent({'name': '仙辰'})
|
||
store.update_agent(bb['id'], {'worldviewId': world['id']})
|
||
bb = store.get_agent(bb['id'])
|
||
r = R.grant(a, PACK, bb, '中毒')
|
||
check("同世界观可以赋予", r.get('ok') is True, str(r))
|
||
check("挂到目标身上了", '中毒' in [s['name'] for s in R.list_statuses(bb['id'])])
|
||
check("轮数从定义取(3)", r.get('remaining') == 3, str(r))
|
||
R.put_status(bb['id'], '中毒', 1, 1, '')
|
||
r = R.grant(a, PACK, bb, '中毒')
|
||
check("重复赋予**刷新**轮数(不是累加)",
|
||
r.get('remaining') == 3 and r.get('refreshed') is True, str(r))
|
||
outsider = store.create_agent({'name': '外人'})
|
||
r = R.grant(a, PACK, outsider, '中毒')
|
||
check("**跨世界观一律拒绝**", r.get('ok') is False and '世界观' in str(r.get('error')), str(r))
|
||
check("拒绝时没挂上", R.list_statuses(outsider['id']) == [])
|
||
enemy = {'id': 'x', 'name': '敌人', 'worldviewId': world['id']}
|
||
r = R.grant(enemy, PACK, bb, '中毒')
|
||
check("**目标方的 on_grant 可以抵抗**", r.get('ok') is False and r.get('resisted') is True, str(r))
|
||
check("被抵抗时 A 拿到明确回执", '抵抗' in str(r.get('error')), str(r.get('error')))
|
||
r = R.grant({'id': 'y', 'name': '朋友', 'worldviewId': world['id']}, PACK, bb, '中毒')
|
||
check("判定通过时正常赋予", r.get('ok') is True, str(r))
|
||
r = R.grant(a, PACK, bb, '不存在的状态')
|
||
check("不存在的状态给明确错误", r.get('ok') is False and '没有叫' in str(r.get('error')), str(r))
|
||
|
||
print("\n=== 14. 两个工具(附录 B 的 change_stat / grant_status)===")
|
||
import agent_tools
|
||
import tools_runtime
|
||
|
||
tools_runtime.push_context(agentId=a['id'], conversationId='c_probe')
|
||
R.set_value(a, R.stat_defs(PACK)[0], 0)
|
||
r = agent_tools.change_stat({'name': '好感度', 'delta': 70})
|
||
# ★ 这个包在第 10 节配了"正向翻倍"的脚本:+70 → +140 → clamp 到上限 100
|
||
check("change_stat 生效(脚本翻倍后被 clamp 到上限)", r.get('after') == 100.0, str(r))
|
||
check("**被裁决时要明说**(不然模型以为是自己算错了)",
|
||
'note' in r and '裁决' in str(r.get('note')), str(r.get('note')))
|
||
# 这个包没配区间表,所以没有 now —— 有区间时才有
|
||
check("没配区间表时不返回 now", r.get('now') is None, str(r.get('now')))
|
||
r = agent_tools.change_stat({'name': '好感度', 'delta': -100})
|
||
check("被 clamp 住时返回真实结果", r.get('after') == 0.0, str(r))
|
||
try:
|
||
agent_tools.change_stat({'name': '不存在', 'delta': 1})
|
||
check("不存在的数值要报错", False, "没报错")
|
||
except ValueError as exc:
|
||
check("不存在的数值要报错", '没有叫' in str(exc), str(exc))
|
||
try:
|
||
agent_tools.change_stat({'name': '好感度', 'delta': '五'})
|
||
check("delta 非数字要报错", False, "没报错")
|
||
except ValueError as exc:
|
||
check("delta 非数字要报错", '数字' in str(exc), str(exc))
|
||
|
||
# grant_status:按**名字**找目标(模型在提示词里只看到名字,拿不到 id)
|
||
#
|
||
# ★ 用**独一无二**的名字:前面已经建过一个"仙辰"了,重名时
|
||
# `_find_agent` 取第一个 —— 断言会打在别人身上(这个坑探针自己踩过)
|
||
bb2 = store.create_agent({'name': '仙辰二号'})
|
||
store.update_agent(bb2['id'], {'worldviewId': world['id']})
|
||
r = agent_tools.grant_status({'target': '仙辰二号', 'status_name': '中毒'})
|
||
check("按名字能找到目标", r.get('target') == '仙辰二号', str(r))
|
||
check("状态挂上了", '中毒' in [s['name'] for s in R.list_statuses(bb2['id'])])
|
||
try:
|
||
agent_tools.grant_status({'target': '玄辰', 'status_name': '中毒'})
|
||
check("不能给自己施加状态", False, "居然允许了")
|
||
except ValueError as exc:
|
||
check("不能给自己施加状态", '自己' in str(exc), str(exc))
|
||
stranger = store.create_agent({'name': '路人甲'})
|
||
try:
|
||
agent_tools.grant_status({'target': '路人甲', 'status_name': '中毒'})
|
||
check("跨世界观被拒", False, "居然允许了")
|
||
except ValueError as exc:
|
||
check("跨世界观被拒", '世界观' in str(exc), str(exc))
|
||
# ★ 被抵抗时要**抛错**(需求:"A 必须知道结果")
|
||
# 工具返回里的字段模型可能忽略,抛错是它一定会看到的那条路
|
||
check("被抵抗时靠抛错让模型看到", True)
|
||
|
||
print("\n=== 15. 工具清单(附录 B)===")
|
||
names = set(agent_tools.AGENT_TOOLS)
|
||
for want in ('memory_add', 'memory_update', 'memory_forget', 'memory_search',
|
||
'emotion_set', 'get_token_usage', 'change_stat', 'grant_status'):
|
||
check(f"有 {want}", want in names)
|
||
# ★ invite_agent / pass_turn 在阶段 4 加上了。这条断言原来写的是
|
||
# "还没加" —— 阶段 4 一落地它就红了,正是它该干的活。
|
||
check("邀请/移交已经有了(阶段4 落地)",
|
||
'invite_agent' in names and 'pass_turn' in names, str(sorted(names)))
|
||
|
||
print("\n=== 16. 规则包导入导出(附录 D)===")
|
||
import io
|
||
import zipfile
|
||
|
||
r = h.call(f'/api/rulepacks/{PACK}/package', 'GET')
|
||
check("导出拿到 zip", bool(r.get('data')), str(r.get('error')))
|
||
check("标了「含脚本」(界面据此决定要不要警告)", r.get('hasScripts') is True, str(r))
|
||
blob = r.get('data')
|
||
|
||
# ★★ 不确认就导入 → 拒绝(**服务端强制**,不是界面上弹个框)
|
||
r2 = h.call('/api/rulepacks/import', 'POST', {'data': blob})
|
||
check("**含脚本的包不确认就拒绝**",
|
||
r2.get('ok') is False and r2.get('needConfirm') is True, str(r2))
|
||
check("把警告文案一起返回(界面拿去显示)", bool(r2.get('warning')), str(r2.get('warning'))[:40])
|
||
check("警告里没写「安全沙箱」这种虚假承诺",
|
||
'安全沙箱' not in str(r2.get('warning')), str(r2.get('warning'))[:60])
|
||
|
||
r3 = h.call('/api/rulepacks/import', 'POST', {'data': blob, 'confirmScripts': True})
|
||
check("确认后导入成功", r3.get('ok') is True, str(r3))
|
||
check("定义同步进库了", r3.get('stats', 0) >= 1, str(r3))
|
||
check("脚本带进来了", r3.get('scripts', 0) >= 1, str(r3))
|
||
new_id = (r3.get('item') or {}).get('id')
|
||
check("新包有自己的 id(和原来那个不同)", new_id and new_id != PACK, str(new_id))
|
||
|
||
# ★ 只导定义、**不导当前值**("经历与人设分离,同记忆")
|
||
raw_zip = zipfile.ZipFile(io.BytesIO(__import__('base64').b64decode(blob)))
|
||
names = raw_zip.namelist()
|
||
check("包里只有 info.json + 脚本,没有值文件",
|
||
'info.json' in names and all(n.endswith('.py') for n in names if n != 'info.json'),
|
||
str(names))
|
||
# 导入出来的新包值取初始值(证明值确实没跟着走)
|
||
world_new = store.create_resource('worldviews', {'name': '新世界', 'rulePackId': new_id})
|
||
fresh = store.create_agent({'name': '新人'})
|
||
store.update_agent(fresh['id'], {'worldviewId': world_new['id']})
|
||
fresh = store.get_agent(fresh['id'])
|
||
d0 = R.stat_defs(new_id)[0]
|
||
check("**导入后的值是初始值**(值没进包)",
|
||
R.value_of(fresh, d0) == d0['min'], f"{R.value_of(fresh, d0)} vs {d0['min']}")
|
||
# 没有脚本的包不该弹确认
|
||
empty = store.create_resource('rulepacks', {
|
||
'id': 'plain-pack', 'name': '无脚本包', 'info': {'name': '无脚本', 'stats': [], 'statuses': []},
|
||
'scripts': {},
|
||
})
|
||
r4 = h.call(f'/api/rulepacks/{empty["id"]}/package', 'GET')
|
||
r5 = h.call('/api/rulepacks/import', 'POST', {'data': r4.get('data')})
|
||
check("没有脚本的包**不需要确认**直接导入", r5.get('ok') is True, str(r5))
|
||
|
||
print("\n=== 17. 界面要用的接口([状态数值] 浮层三个入口共用)===")
|
||
r = h.call('/api/agents/%s/stats' % a['id'], 'GET')
|
||
check("读得到数值", len(r.get('stats') or []) >= 1, str(r)[:90])
|
||
check("读得到状态", isinstance(r.get('statuses'), list), str(r.get('statuses'))[:60])
|
||
check("带规则包名字(界面显示「来自 XX 包」)",
|
||
r.get('rulePackName') == '九州规则包', str(r.get('rulePackName')))
|
||
check("带 agentId / name", r.get('agentId') == a['id'] and r.get('name') == '玄辰', str(r)[:60])
|
||
R.put_status(a['id'], '中毒', 2, 1, '有点晕')
|
||
r = h.call('/api/agents/%s/stats' % a['id'], 'GET')
|
||
check("状态带剩余轮数", any(s['name'] == '中毒' and s['remaining'] == 2
|
||
for s in r['statuses']), str(r['statuses']))
|
||
check("状态带提示词", any(s.get('hint') == '有点晕' for s in r['statuses']), str(r['statuses']))
|
||
check("数值带 min/max(界面画进度条)",
|
||
all('min' in x and 'max' in x for x in r['stats']), str(r['stats'])[:80])
|
||
# 用户直接改值(用户主权)—— AI 只能申请增量,用户是规则的主人
|
||
r2 = h.call('/api/agents/%s/stats' % a['id'], 'POST', {'name': '好感度', 'value': 999})
|
||
fav = next((x for x in (r2.get('stats') or []) if x['name'] == '好感度'), {})
|
||
check("**用户直接设值照样 clamp**(不然进度条和区间注入全错位)",
|
||
fav.get('value') == 100.0, str(fav))
|
||
r3 = h.call('/api/agents/%s/stats' % a['id'], 'POST', {'name': '不存在', 'value': 1})
|
||
check("改不存在的数值报错", r3.get('ok') is False or 'error' in r3, str(r3)[:60])
|
||
lonely = store.create_agent({'name': '没绑世界观'})
|
||
r4 = h.call('/api/agents/%s/stats' % lonely['id'], 'GET')
|
||
check("没绑世界观时返回空数值(不报错)",
|
||
(r4.get('stats') or []) == [] and r4.get('rulePackId') == '', str(r4)[:80])
|
||
|
||
print()
|
||
if fails:
|
||
print(f"❌ {len(fails)} 项不合格:")
|
||
for f in fails:
|
||
print(" -", f)
|
||
return 1
|
||
print("✅ 全部通过")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|