规则包的 zip 导入导出接完了。仍不发版 —— 界面还没有,
用户建不出规则包(只能靠接口)。
## 导入导出
`GET /api/rulepacks/<id>/package` → zip(`info.json` + 各 `.py`)→ base64
`POST /api/rulepacks/import` → 解包 → 建资源 → `sync_defs`
★ **只导定义、不导当前值**(需求附录 D:"数值的**定义**进包,
**当前值**不进包 —— 经历与人设分离,同记忆")。
所以把包发给别人,对方拿到的是规则,不是你的好感度。
探针里钉了这一条:导入后新包的值取初始值。
★ **含脚本的包必须显式确认**:包里真有 `.py` 而请求没带
`confirmScripts: true` → **服务端直接拒绝**,并把警告文案一起返回
(界面拿去显示)。
为什么不做成"界面弹个框就行":那只是界面上的礼貌,**绕过界面直接调
接口就没了**。而这条是安全底线(脚本每轮在用户设备上跑)。
## ★★ 抓到一个"会静默失效"的真 bug
`_apply_resource_patch` 处理 `dict` 字段时对**每个值**都调了 `_as_text`:
item[key] = {str(k): _as_text(v) for k, v in raw.items()}
原来这么写没问题 —— `image` 的值全是字符串(路径)。但 v1.2 的规则包里
`info` 的值是**嵌套结构**(`stats: [{name, min, max, ranges: [...]}]`)。
结果:`info` 被存成 `{'stats': "[{'name': 'A'}]"}`(**列表变成了字符串**),
于是 `sync_defs` 解析不出任何定义 → 当成"这个包没有数值" → **不报错**。
**这个 bug 如果漏到线上**:用户导入规则包 → 界面显示导入成功 →
但数值系统完全不工作,而且**没有任何错误信息**。查起来要从
"界面 → 接口 → store → SQLite"一路挖到底。
修法:新增 `_json_safe()` —— 保留嵌套结构,只把 JSON 存不下的东西
(set / datetime)转成字符串。`image` 的行为**完全不变**(它的值本来就是字符串)。
## 顺手加的保护
`sync_defs` 收到**空定义**时不再动库。
"读不到这个包"(id 不对、刚被删)和"用户真要把定义清空"在这一层分不清,
而**清空定义是不可逆的**:值还在 `stat_values` 里,定义没了它们就成了
永远读不到的孤儿。真要清空,把那个包删掉就行 —— 那是个明确得多的动作。
## 验证
`probe-rule-engine.py` 扩到 16 节:导入导出 12 项(含"不确认就拒绝"、
"警告里没有虚假承诺"、"包里没有值文件"、"导入后值是初始值"、
"没脚本的包不用确认")。
★ 这一节又把探针自己的三个坑挖出来了:
· 第 10 节给这个包配了"正向翻倍"脚本,所以 +70 实际是 +100(被 clamp)
· 这个包没配区间表,所以不该期待 `now`
· 前面已经建过一个"仙辰",重名时 `_find_agent` 取第一个
三次都是**代码对、断言错**。但暴露了真问题:**探针的断言必须自足**,
不能依赖"前面某节留下的状态" —— 那正是让测试变脆的原因。
已把那三处改成不依赖前文。
七个探针全绿。
## 阶段 3 只剩界面
资源页第四个 Tab「规则包」+ [规则包编辑] 全屏(脚本编辑复用节点代码组件)
+ [状态数值] 浮层 + 导入时的脚本警告确认弹窗。
435 lines
22 KiB
Python
435 lines
22 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(多智能体对话)的
|
||
check("邀请/移交还没加(阶段4)",
|
||
'invite_agent' not in names and 'pass_turn' not 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()
|
||
if fails:
|
||
print(f"❌ {len(fails)} 项不合格:")
|
||
for f in fails:
|
||
print(" -", f)
|
||
return 1
|
||
print("✅ 全部通过")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|