规则引擎的**执行层**。工具(让 AI 能调)和界面还没接,仍不发版。
## 三个脚本入口(需求附录 E 的签名)
on_stat_change(name, value, delta) -> 生效增量
on_turn(self_agent, stats_api) 每轮执行
on_grant(status_name, source_agent) -> bool
全部走 `rule_sandbox`(上一轮写的受限沙箱)+ 硬超时(`timeouts.customNode`)。
## ★ 异常 = 归零 + 提示,不炸对话
需求附录 E 原话。所以 `run_script` 把**所有**异常接在内部转成人话:
脚本被沙箱拒绝、没有入口函数、语法错误、运行时报错、超时 —— 五种。
**抛出去的话,一次脚本报错会顺着调用栈炸到对话主循环**,
而规则脚本是用户自己写的,写错是常态。
★ 特别注意"归零"的语义:脚本坏了时增量归**零**,**不是按原值放行**。
宁可这一次不生效,也不能让一个失控的脚本改数值。
## change_stat:流程固定,不许写绝对值
脚本裁决(如有)→ clamp → 写库 → 下一轮注入反映新值
**为什么"只申请增量"不能通融**(需求 §3.10):
允许写绝对值的话"脚本裁决"就没意义了 —— 修正器要的是"你想加 5 点,
我判成加 10 点",而不是"你想设成 100,我判……多少"。
而且群聊里两个智能体同时改同一个 shared 数值时,**绝对值会互相覆盖,
增量不会**。
裁决脚本的返回值三种都认:数字(生效增量)、`(增量, 旁白)`、`None`(否决)。
## grant_status:赋予流程
1. **同世界观**才能赋(也包含"自己没绑世界观"→ 拒绝)
2. 调**目标方**的 `on_grant(status_name, source_agent)` → bool
3. 拒绝时给 A 一个明确的「被抵抗」回执(需求原话"A 必须知道结果")
4. 同名重复赋予默认**刷新轮数**;定义配了 max_stack 才叠层
## 脚本 API(需求 §3.11 的三项权限 + 旁白)
通过**参数**注入而不是模块级函数:那样脚本能摸到别的东西,
两个脚本也会互相污染。
★ 这里的 `emotion_set` **没有死亡检查** —— 需求 §3.11 明说状态脚本是
"唯一能让 AI 侧解除死亡的通道"(定时复活 / 解药剧情)。禁止自愈那条
只约束 AI 直接调工具。
## 接线:状态脚本在重拼 prompt **之前**跑
需求附录 E 的顺序是固定的:`状态脚本执行 → 重拼 prompt → 生成`。
顺序反了的话脚本这一轮的改动要等下一轮才生效 —— 表现是
"中毒了但 AI 这轮还生龙活虎"。
脚本返回的旁白拼在提示词末尾("作为系统消息注入下一轮"),
比单开一条 user 消息干净 —— 不会污染对话记录。
## 验证
`probe-rule-engine.py` 从 9 节扩到 13 节:脚本裁判(+5 裁决成 +10、
负向不翻倍)、坏脚本(除零 → 归零 + 人话)、危险脚本(带 import → 沙箱拒绝)、
`on_turn`(旁白 + 改数值 + 改状态提示词)、`grant_status`(同世界观 / 跨世界观拒 /
目标方抵抗 / 重复刷新轮数)。
★ 探针又抓到两个真 bug:
· `status_defs` 的 SQL 参数少个逗号 —— 字符串被当元组展开成 6 个绑定值
· `create_resource` 忽略传入的 `id` —— 规则包的 id 要和 `sync_defs` 写库用的
一致,否则定义和值分别挂在两个 id 上。现在允许带 id(校验过、撞了就换新的)
七个探针全绿。
296 lines
15 KiB
Python
296 lines
15 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
|
||
|
||
PACK = "pack-1"
|
||
|
||
|
||
def main():
|
||
print("\n=== 1. 定义同步(幂等,且不动值)===")
|
||
r = R.sync_defs(PACK, {
|
||
'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'},
|
||
],
|
||
})
|
||
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.create_resource('rulepacks', {
|
||
'id': PACK, 'name': '九州规则包', 'info': {},
|
||
'scripts': {'favor.py': FAVOR, 'poison.py': POISON},
|
||
})
|
||
R.sync_defs(PACK, {
|
||
'stats': [{'name': '好感度', 'min': 0, 'max': 100, 'ranges': [],
|
||
'script': 'favor.py'}],
|
||
'statuses': [{'name': '中毒', 'type': 'timed', 'turns': 3, 'script': 'poison.py'}],
|
||
})
|
||
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()
|
||
if fails:
|
||
print(f"❌ {len(fails)} 项不合格:")
|
||
for f in fails:
|
||
print(" -", f)
|
||
return 1
|
||
print("✅ 全部通过")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|