feat(v1.2): 阶段3 下 —— 规则包导入导出 + 一个静默失效的真 bug
规则包的 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「规则包」+ [规则包编辑] 全屏(脚本编辑复用节点代码组件)
+ [状态数值] 浮层 + 导入时的脚本警告确认弹窗。
This commit is contained in:
@@ -39,14 +39,16 @@
|
||||
|
||||
import base64
|
||||
import io
|
||||
import zipfile
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
import agentdb
|
||||
import paths
|
||||
import rule_engine
|
||||
import rule_sandbox
|
||||
import store
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -738,9 +740,108 @@ _RES_PATH = {
|
||||
'worldviews': 'worldviews',
|
||||
'model-entries': 'models',
|
||||
'skills': 'skills',
|
||||
# v1.2 数值状态包(需求附录 D)。★ 它是**唯一允许夹带可执行脚本**的包类型 ——
|
||||
# 智能体包/世界观包发现脚本一律拒绝导入(见 _resource_import)
|
||||
'rulepacks': 'rulepacks',
|
||||
}
|
||||
|
||||
|
||||
def _export_rulepack(handler, pid: str, err) -> bool:
|
||||
"""
|
||||
导出数值状态包(zip:`info.json` + 各脚本)。
|
||||
|
||||
★ **只导定义、不导当前值**(需求附录 D 原话:"数值的**定义**进包,
|
||||
**当前值**不进包 —— 经历与人设分离,同记忆")。
|
||||
所以把包发给别人,对方拿到的是规则,不是你的好感度。
|
||||
"""
|
||||
pack = store.get_resource('rulepacks', pid)
|
||||
if not pack:
|
||||
err(404, '没有这个规则包')
|
||||
return True
|
||||
info = dict(pack.get('info') or {})
|
||||
info['name'] = pack.get('name') or info.get('name') or '规则包'
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.writestr('info.json', json.dumps(info, ensure_ascii=False, indent=2))
|
||||
for fname, src in (pack.get('scripts') or {}).items():
|
||||
zf.writestr(str(fname), str(src))
|
||||
return _send_json_ok(handler, {
|
||||
'ok': True,
|
||||
'name': pack.get('name') or '',
|
||||
'data': base64.b64encode(buf.getvalue()).decode('ascii'),
|
||||
'hasScripts': bool(pack.get('scripts')),
|
||||
})
|
||||
|
||||
|
||||
def _import_rulepack(handler, body: dict, err) -> bool:
|
||||
"""
|
||||
导入数值状态包。
|
||||
|
||||
★★ 这是**唯一允许夹带可执行脚本**的包类型(需求附录 D)。
|
||||
所以它比别的包多一道**服务端强制**的确认:
|
||||
|
||||
包里真有 `.py` 而请求没带 `confirmScripts: true` → **拒绝导入**,
|
||||
并把警告文案一起返回,界面拿去显示。
|
||||
|
||||
为什么不做成"界面弹个框就行":那只是界面上的礼貌,绕过界面直接
|
||||
调接口就没了。而这条是**安全底线**(脚本每轮在用户设备上跑)。
|
||||
|
||||
★ 智能体包 / 世界观包**仍然禁止夹带脚本** —— 那条在各自的导入里拦。
|
||||
"""
|
||||
raw = body.get('data') or ''
|
||||
if not raw:
|
||||
err(400, '缺少包内容')
|
||||
return True
|
||||
try:
|
||||
blob = base64.b64decode(raw)
|
||||
files = _read_zip(blob)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
err(400, f'包读不出来:{exc}')
|
||||
return True
|
||||
|
||||
# 先找出脚本 —— 在**解析 info.json 之前**就要决定要不要拦,
|
||||
# 因为"有没有脚本"是用户要先知道的事
|
||||
scripts = {
|
||||
os.path.basename(name): data.decode('utf-8', errors='replace')
|
||||
for name, data in files.items()
|
||||
if name.lower().endswith('.py')
|
||||
}
|
||||
if scripts and not body.get('confirmScripts'):
|
||||
return _send_json_ok(handler, {
|
||||
'ok': False,
|
||||
'needConfirm': True,
|
||||
'scriptCount': len(scripts),
|
||||
'warning': rule_sandbox.IMPORT_WARNING,
|
||||
})
|
||||
|
||||
info = None
|
||||
for name in files:
|
||||
if os.path.basename(name).lower() == 'info.json':
|
||||
try:
|
||||
info = json.loads(files[name].decode('utf-8'))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
err(400, f'info.json 解析失败:{exc}')
|
||||
return True
|
||||
break
|
||||
if not isinstance(info, dict):
|
||||
err(400, '包里没有 info.json —— 这不是一个数值状态包')
|
||||
return True
|
||||
|
||||
name = str(info.get('name') or body.get('name') or '规则包')[:40]
|
||||
item = store.create_resource('rulepacks', {
|
||||
'name': name,
|
||||
'note': str(body.get('note') or ''),
|
||||
'info': info,
|
||||
'scripts': scripts,
|
||||
})
|
||||
# 定义同步进库(值不动 —— 那是"定义进包、值不进包"的另一半)
|
||||
counts = rule_engine.sync_defs(item['id'], info)
|
||||
return _send_json_ok(handler, {
|
||||
'ok': True, 'item': item, 'stats': counts.get('stats', 0),
|
||||
'statuses': counts.get('statuses', 0), 'scripts': len(scripts),
|
||||
})
|
||||
|
||||
|
||||
def _tag_world_agents(items: list) -> list:
|
||||
"""
|
||||
给每个世界观补一个 `agents: [{id, name}]` —— "谁绑了它"。
|
||||
@@ -775,6 +876,14 @@ def _resource_route(handler, seg: list, method: str, body, err):
|
||||
name = _RES_PATH[seg[1]]
|
||||
|
||||
# 包 / JSON 的导入导出(世界观包、Skill 文件)
|
||||
#
|
||||
# ★ 规则包要**抢在通用分支前面**:它的格式不一样(zip 里除了 info.json
|
||||
# 还有一堆 .py),而且多一道"含脚本要确认"的关卡。
|
||||
if name == 'rulepacks':
|
||||
if len(seg) == 4 and seg[3] in ('package', 'export') and method == 'GET':
|
||||
return _export_rulepack(handler, seg[2], err)
|
||||
if len(seg) == 3 and seg[2] == 'import' and method == 'POST':
|
||||
return _import_rulepack(handler, body(), err)
|
||||
if len(seg) == 3 and seg[2] == 'import' and method == 'POST':
|
||||
return _resource_import(handler, name, body(), err)
|
||||
if len(seg) == 4 and seg[3] == 'asset' and method == 'POST':
|
||||
|
||||
@@ -52,7 +52,7 @@ def _num(v, default=0.0):
|
||||
return default
|
||||
|
||||
|
||||
def sync_defs(pack_id: str, info: dict) -> dict:
|
||||
def sync_defs(pack_id: str, info: dict = None) -> dict:
|
||||
"""
|
||||
把一个规则包的 `info.json` 同步进库(**幂等**,重复导入只覆盖定义)。
|
||||
|
||||
@@ -60,12 +60,28 @@ def sync_defs(pack_id: str, info: dict) -> dict:
|
||||
**当前值**不进包 —— 经历与人设分离,同记忆")。
|
||||
所以重新导入一个包不会把你的好感度清零。
|
||||
|
||||
★ [info] 不传时**从 store 里那个包读**。这是默认路径 ——
|
||||
定义只应该有一处源头(包里的 `info.json`),SQLite 里那两张表是
|
||||
**派生**出来的。两处都能写的话,迟早会出现
|
||||
"包里改了、库里还是旧的",而那种不一致极难查。
|
||||
|
||||
返回 `{'stats': n, 'statuses': m}`。
|
||||
"""
|
||||
if info is None:
|
||||
pack = store.get_resource('rulepacks', pack_id or '') or {}
|
||||
info = pack.get('info') if isinstance(pack.get('info'), dict) else {}
|
||||
info = info or {}
|
||||
sid = (pack_id or '').strip()
|
||||
if not sid:
|
||||
return {'stats': 0, 'statuses': 0}
|
||||
# ★★ 空定义**不动库**。
|
||||
#
|
||||
# "读不到这个包"(id 不对、包刚被删)和"用户真要把定义清空"在这一层
|
||||
# 分不清,而**清空定义是不可逆的**:值还在 `stat_values` 里,
|
||||
# 定义没了它们就成了永远读不到的孤儿。
|
||||
# 真要清空,把那个包删掉就行 —— 那是个明确得多的动作。
|
||||
if not info.get('stats') and not info.get('statuses'):
|
||||
return {'stats': 0, 'statuses': 0}
|
||||
agentdb.init() # ★ 别忘了:这几张表是 v1.2 才加的,惰性建表
|
||||
conn = agentdb._connect()
|
||||
stats = info.get('stats') if isinstance(info.get('stats'), list) else []
|
||||
|
||||
@@ -1284,13 +1284,34 @@ def _apply_resource_patch(name: str, item: dict, patch: dict) -> dict:
|
||||
for key in cfg.get('dict', ()):
|
||||
if patch.get(key) is not None:
|
||||
raw = patch[key]
|
||||
item[key] = (
|
||||
{str(k): _as_text(v) for k, v in raw.items()}
|
||||
if isinstance(raw, dict) else {}
|
||||
)
|
||||
# ★★ **不要对每个值调 `_as_text`**。
|
||||
#
|
||||
# 原来那么写是因为 `image` 的值全是字符串(路径),转一下无妨。
|
||||
# 但 v1.2 的规则包里 `info` 的值是**嵌套结构**
|
||||
# (`stats: [{name, min, max, ranges: [...]}]`)——
|
||||
# 转成字符串之后 `sync_defs` 读到的就是 `"[{'name': 'A'}]"`,
|
||||
# 于是**整个规则引擎静默失效**(解析不出来 → 当成没定义 → 不报错)。
|
||||
# 这种"看起来存进去了、实际全废"的坑最难查。
|
||||
item[key] = _json_safe(raw) if isinstance(raw, dict) else {}
|
||||
return item
|
||||
|
||||
|
||||
def _json_safe(v):
|
||||
"""
|
||||
只留下 JSON 存得下的东西(dict / list / 字符串 / 数字 / 布尔 / None)。
|
||||
|
||||
别的(set、datetime、自定义对象)转成字符串 —— 不让它们把写盘搞炸,
|
||||
同时**保留嵌套结构**(这是 `_as_text` 做不到的)。
|
||||
"""
|
||||
if isinstance(v, dict):
|
||||
return {str(k): _json_safe(x) for k, x in v.items()}
|
||||
if isinstance(v, (list, tuple)):
|
||||
return [_json_safe(x) for x in v]
|
||||
if v is None or isinstance(v, (str, int, float, bool)):
|
||||
return v
|
||||
return str(v)
|
||||
|
||||
|
||||
def create_resource(name: str, payload: dict) -> dict:
|
||||
"""
|
||||
新建一种资源。
|
||||
|
||||
@@ -42,27 +42,59 @@ 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. 定义同步(幂等,且不动值)===")
|
||||
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'},
|
||||
],
|
||||
# ★ 先建包(带完整 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,
|
||||
@@ -196,15 +228,16 @@ def main():
|
||||
" # 敌人下毒必被抵抗\n"
|
||||
" return source_agent != '敌人'\n"
|
||||
)
|
||||
store.create_resource('rulepacks', {
|
||||
'id': PACK, 'name': '九州规则包', 'info': {},
|
||||
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, {
|
||||
'stats': [{'name': '好感度', 'min': 0, 'max': 100, 'ranges': [],
|
||||
'script': 'favor.py'}],
|
||||
'statuses': [{'name': '中毒', 'type': 'timed', 'turns': 3, 'script': 'poison.py'}],
|
||||
})
|
||||
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))
|
||||
@@ -340,6 +373,53 @@ def main():
|
||||
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)} 项不合格:")
|
||||
|
||||
Reference in New Issue
Block a user