feat(v1.2): 阶段3 上半 —— 规则引擎内核(数值 + 状态的数据层与注入)
v1.2 最大的一块开工。这一轮是**内核核心**,工具(change_stat / grant_status)、脚本接线、规则包导入导出、界面都还没做,所以**不发版**。 ## 数据层:4 张表 `stat_defs` / `stat_values` / `status_defs` / `status_instances`。 ★ 定义表的 key 是**规则包 id 不是世界观 id** —— 同一个包可以被多个世界观 引用,定义只存一份(改一次全生效)。世界观只是"挂载点"(需求 §3.6)。 ★ 值的 scope 和记忆**故意用同一套写法**:`shared=0 → agent:<uuid>`、 `shared=1 → world:<uuid>`。好处是"绑定/解绑世界观只换读写空间、值不迁移" 这条自动成立,和记忆行为一致 —— 用户不用学两套心智模型。 ## rule_engine.py `sync_defs`(幂等,只覆盖定义、**不动值**,符合"定义进包、当前值不进包") / `stat_defs` / `status_defs` / `scope_for` / `value_of` / `set_value` / `clamp` / `range_text` / `stats_section` / `status_section` / `list_statuses` / `put_status` / `drop_status` / `tick_statuses`。 ## 三个"看起来随意、其实要算"的决定 **① 区间是左闭右开**(最后一段除外)。两边都闭的话,边界值(20 点在 0~20 和 20~60 两段里)会同时命中,取哪段成了未定义行为。最后一段必须闭, 否则顶格(100)时裸奔。 **② 初始值取 min 不取 max**。在"好感度 0~100"这种语义里 min 是中性起点; 取 max 的话新角色一上来就满好感。想要别的起点,包作者把 min 设成他要的值。 **③ 状态递减不碰持久状态**。persistent 的 `remaining = -1`,递减循环里 直接跳过 —— 不跳的话 `-1 - 1 = -2` 永远到不了 0,但每轮白写一次库; 而如果谁把判断写成 `<= 0 就删`,持久状态第一轮就没了。 ## 注入 `<stats>` 按附录 C 的格式:`[世界·九州] 声望: 450→500/1000 —— 名震九州……` (来源前缀 + 值 + 变化箭头 + 命中区间文案)。箭头靠"取完就清"实现 **只显示一轮**,所以它放在内存不放库。 `<status>`:`中毒(剩 3 轮):你感到眩晕`,持久状态不显示轮数。 ★ `<stats>` 要求绑世界观(规则包挂在世界观上),**`<status>` 不要求** —— 状态一旦赋予就挂在智能体自己身上,解绑世界观不该让它凭空消失 (和"解绑不丢记忆"同一个道理)。 ## 顺手修掉的两个字段表缺项 · `worldviews` 的 `text` 字段表里加 `rulePackId` —— 不加的话这个字段会被 `_apply_resource_patch` 丢掉,表现是"界面里配了、读出来没有" · `RESOURCES` 加 `rulepacks` + `paths.rulepacks_file` / `rule_scripts_dir` ## 验证 新增 `scripts/probe-rule-engine.py` 9 节 40+ 项:定义同步幂等、 初始值取 min、scope 按 shared 分(共享的两人读同一个)、 **区间左闭右开的三个边界值**、clamp、**箭头只显示一轮**、 `<stats>` 格式、状态递减消亡、持久不受影响、绑不绑世界观时两段的差异。 ★ 探针抓到一个真 bug:`sync_defs` 返回的是"输入了几条"而不是"实际入库几条" —— 界面拿这个数报给用户时,"导入了 3 条"和"3 条里有 1 条没名字被跳过" 是两回事。 七个探针全绿。下一步:change_stat / grant_status 工具 + 脚本接线 + 规则包导入导出。
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
"""每轮对话前拼 system prompt(需求 3.2 / 3.5 / 3.6 / 3.7 + 附录 C)。
|
||||
"""每轮对话前拼 system prompt(需求 3.2 / 3.5 / 3.6 / 3.7 + 附录 C)。
|
||||
|
||||
## 这个模块只做一件事
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
import re
|
||||
|
||||
import agentdb
|
||||
import rule_engine
|
||||
import store
|
||||
from defaults import (
|
||||
BUILTIN_SKILL,
|
||||
@@ -337,23 +338,41 @@ def build_system_prompt(settings: dict, agent: dict) -> str:
|
||||
return render(template, values)
|
||||
|
||||
|
||||
def _pack_of(agent: dict) -> str:
|
||||
"""
|
||||
这个智能体用的规则包 id(`世界观.rulePackId`),没有就空串。
|
||||
|
||||
★ 数值状态包挂在**世界观**上(需求 §3.6:"v1.2 起,世界观同时是
|
||||
数值状态包的挂载点"),所以没绑世界观就没有规则引擎 —— 返回空串,
|
||||
`<stats>` / `<status>` 两段会被整段删掉。
|
||||
"""
|
||||
wid = ((agent or {}).get('worldviewId') or '').strip()
|
||||
if not wid:
|
||||
return ''
|
||||
world = _safe(lambda: store.get_resource('worldviews', wid), None) or {}
|
||||
return (world.get('rulePackId') or '').strip()
|
||||
|
||||
|
||||
def build_stats(agent: dict) -> str:
|
||||
"""
|
||||
`<stats>` 段:数值系统(需求附录 C / §3.10)。
|
||||
|
||||
★ 占位函数,**阶段 3 实现**。现在返回空串 —— `render` 会把整段删掉,
|
||||
所以提示词里不会出现一个空的 `<stats></stats>`。
|
||||
先把它列进 `SECTIONS` 是为了让模板和渲染两边**一开始就一致**:
|
||||
否则阶段 3 加段名时,会有一版"模板里有、渲染不管"的中间状态,
|
||||
表现是提示词里原样留着 `{stats}` 大括号。
|
||||
格式见 `rule_engine.stats_section`。没绑世界观、或世界观没挂规则包 → 空段。
|
||||
"""
|
||||
pack = _pack_of(agent)
|
||||
if not pack:
|
||||
return ''
|
||||
return _safe(lambda: rule_engine.stats_section(agent or {}, pack), '')
|
||||
|
||||
|
||||
def build_status(agent: dict) -> str:
|
||||
"""
|
||||
`<status>` 段:状态系统(需求附录 C / §3.11)。
|
||||
|
||||
★ 同样是**阶段 3 的占位**,见 `build_stats` 的说明。
|
||||
★ 和 `<stats>` 不同,它**不要求绑世界观**:状态一旦被赋予就挂在智能体
|
||||
自己身上,解绑世界观不该让它身上的状态凭空消失(那和"解绑不丢记忆"
|
||||
是同一个道理)。
|
||||
"""
|
||||
if not ((agent or {}).get('id') or ''):
|
||||
return ''
|
||||
return _safe(lambda: rule_engine.status_section(agent or {}), '')
|
||||
|
||||
@@ -125,6 +125,66 @@ CREATE TABLE IF NOT EXISTS agent_skills (
|
||||
ord INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (agent_id, skill_id)
|
||||
);
|
||||
|
||||
-- ============ v1.2 规则引擎(需求 §3.10 数值 / §3.11 状态)============
|
||||
--
|
||||
-- 和记忆一个思路:**定义**挂世界观、**值**按 scope 存。
|
||||
--
|
||||
-- 为什么定义不挂智能体:需求 §3.10 原话"定义统一收进数值状态包
|
||||
-- (世界观层),智能体不再自带数值定义" —— 一份定义、多个实例。
|
||||
--
|
||||
-- 值的 scope 有两种,由 def 的 shared 决定:
|
||||
-- shared=0 → "agent:<uuid>" 好感度各算各的
|
||||
-- shared=1 → "world:<uuid>" 灵气浓度全世界观一份
|
||||
-- 这和记忆的 scope 写法**故意一致**(`scope_of` 那套),
|
||||
-- 于是"绑定/解绑世界观只是换读写空间、值不迁移不丢失"这条也自动成立。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS stat_defs (
|
||||
-- ★ key 是**规则包** id 不是世界观 id:同一个包可以被多个世界观引用,
|
||||
-- 定义只存一份(改一次全生效)。世界观只是"挂载点"。
|
||||
pack_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
-- min / max 是 SQL 关键字,所以列名带后缀
|
||||
min_value REAL NOT NULL DEFAULT 0,
|
||||
max_value REAL NOT NULL DEFAULT 100,
|
||||
shared INTEGER NOT NULL DEFAULT 0,
|
||||
-- ranges 是 JSON 字符串:[{"min":0,"max":20,"text":"冷淡:……"}],
|
||||
-- 命中哪段注入哪段的 text(需求 §3.10 的"声明式区间表")
|
||||
ranges TEXT NOT NULL DEFAULT '[]',
|
||||
script TEXT NOT NULL DEFAULT '',
|
||||
ord INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (pack_id, name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS stat_values (
|
||||
scope TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
value REAL NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (scope, name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS status_defs (
|
||||
pack_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
-- persistent(持久,每轮执行脚本)/ timed(定时,每轮递减归零消失)
|
||||
kind TEXT NOT NULL DEFAULT 'timed',
|
||||
turns INTEGER NOT NULL DEFAULT 1,
|
||||
max_stack INTEGER NOT NULL DEFAULT 1,
|
||||
script TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (pack_id, name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS status_instances (
|
||||
agent_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
-- 剩余轮数:timed 每轮 -1,归零消失;persistent 恒为 -1(不过期)
|
||||
remaining INTEGER NOT NULL DEFAULT 0,
|
||||
stacks INTEGER NOT NULL DEFAULT 1,
|
||||
-- 状态提示词:脚本可以改写它(需求 §3.11 的脚本权限之一)
|
||||
hint TEXT NOT NULL DEFAULT '',
|
||||
granted_at TEXT NOT NULL,
|
||||
PRIMARY KEY (agent_id, name)
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""
|
||||
"""
|
||||
运行期路径与平台判断。
|
||||
|
||||
为什么单独一个模块:
|
||||
@@ -95,6 +95,12 @@ class Paths:
|
||||
self.worldviews_file = os.path.join(self.data_dir, 'worldviews.json')
|
||||
self.models_file = os.path.join(self.data_dir, 'models.json')
|
||||
self.skills_file = os.path.join(self.data_dir, 'skills.json')
|
||||
# 数值状态包(需求附录 D):定义 + 对应的 Python 脚本源码。
|
||||
# 量级小、而且用户会想看自己写了什么 → 还是 JSON
|
||||
self.rulepacks_file = os.path.join(self.data_dir, 'rulepacks.json')
|
||||
# 规则脚本**落盘**的位置:脚本要作为文件被 exec 起来,
|
||||
# 所以从包里解出来之后得写到磁盘上(不能只存在 JSON 里)
|
||||
self.rule_scripts_dir = os.path.join(self.data_dir, 'rule-scripts')
|
||||
# 智能体系统的 SQLite(记忆 / 情绪 / Token / 绑定关系)
|
||||
self.agent_db_file = os.path.join(self.data_dir, 'agent.db')
|
||||
# 智能体包解出来的图片等资源(导入 zip 时落到这儿)
|
||||
@@ -116,7 +122,7 @@ class Paths:
|
||||
|
||||
def ensure_dirs(self) -> None:
|
||||
for folder in (self.data_dir, self.uploads_dir, self.tmp_dir, self.screens_dir,
|
||||
self.notes_dir, self.agent_assets_dir):
|
||||
self.notes_dir, self.agent_assets_dir, self.rule_scripts_dir):
|
||||
try:
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
except OSError as exc: # 安卓上外部存储没授权时会失败,不能让它把进程打死
|
||||
|
||||
396
android/kernel/rule_engine.py
Normal file
396
android/kernel/rule_engine.py
Normal file
@@ -0,0 +1,396 @@
|
||||
"""规则引擎:数值系统 + 状态系统(需求 v1.2 §3.10 / §3.11)。
|
||||
|
||||
## 一句话分工
|
||||
|
||||
· **定义**在「数值状态包」里(独立资源,可被多个世界观引用)
|
||||
· **值**按 scope 存(`shared` 决定是每个智能体一份还是全世界观一份)
|
||||
· **注入**走 `<stats>` / `<status>` 两个段(附录 C,排在提示词最后)
|
||||
· **操作**只有 `change_stat`(只申请增量,不许写绝对值)
|
||||
|
||||
## 为什么"只申请增量"这条不能通融
|
||||
|
||||
需求 §3.10 原话:`change_stat(name, delta)` —— 只申请增量,内核流程固定:
|
||||
|
||||
脚本裁决(如有)→ clamp 到 [min,max] → 写库 → 下一轮注入反映新值
|
||||
|
||||
如果允许 AI 写绝对值,那"脚本裁决"就没意义了 —— 修正器要的是
|
||||
"你想加 5 点,我判成加 10 点",而不是"你想设成 100,我判……多少"。
|
||||
而且并发时(群聊里两个智能体同时改同一个 shared 数值)
|
||||
绝对值会互相覆盖,增量不会。
|
||||
|
||||
## 值的 scope
|
||||
|
||||
和记忆**故意用同一套写法**:
|
||||
|
||||
shared=0 → "agent:<uuid>" 好感度各算各的
|
||||
shared=1 → "world:<uuid>" 灵气浓度全世界观一份
|
||||
|
||||
好处是"绑定/解绑世界观只换读写空间、值不迁移"这条自动成立 ——
|
||||
和记忆的行为一致,用户不用学两套心智模型。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
import agentdb
|
||||
import rule_sandbox
|
||||
import store
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 定义:从规则包同步进来
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: 规则包里数值定义的合法字段(多出来的忽略,不报错 —— 兼容将来扩展)
|
||||
_STAT_KEYS = ('name', 'min', 'max', 'shared', 'ranges', 'script')
|
||||
_STATUS_KEYS = ('name', 'kind', 'turns', 'max_stack', 'script')
|
||||
|
||||
|
||||
def _num(v, default=0.0):
|
||||
try:
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def sync_defs(pack_id: str, info: dict) -> dict:
|
||||
"""
|
||||
把一个规则包的 `info.json` 同步进库(**幂等**,重复导入只覆盖定义)。
|
||||
|
||||
★ 只同步**定义**,不动**值**(需求附录 D:"数值的**定义**进包,
|
||||
**当前值**不进包 —— 经历与人设分离,同记忆")。
|
||||
所以重新导入一个包不会把你的好感度清零。
|
||||
|
||||
返回 `{'stats': n, 'statuses': m}`。
|
||||
"""
|
||||
info = info or {}
|
||||
sid = (pack_id or '').strip()
|
||||
if not sid:
|
||||
return {'stats': 0, 'statuses': 0}
|
||||
agentdb.init() # ★ 别忘了:这几张表是 v1.2 才加的,惰性建表
|
||||
conn = agentdb._connect()
|
||||
stats = info.get('stats') if isinstance(info.get('stats'), list) else []
|
||||
statuses = info.get('statuses') if isinstance(info.get('statuses'), list) else []
|
||||
|
||||
# 定义表整体替换这个包的(不然删掉的数值会一直留着)
|
||||
conn.execute('DELETE FROM stat_defs WHERE pack_id = ?', (sid,))
|
||||
conn.execute('DELETE FROM status_defs WHERE pack_id = ?', (sid,))
|
||||
|
||||
# ★ 数**实际入库的**,不是输入数组的长度:"你导入了 3 条"和
|
||||
# "3 条里有 1 条没名字被跳过"是两回事,界面拿这个数报给用户。
|
||||
n_stats = 0
|
||||
for i, s in enumerate(stats):
|
||||
s = s or {}
|
||||
name = str(s.get('name') or '').strip()
|
||||
if not name:
|
||||
continue
|
||||
lo, hi = _num(s.get('min'), 0.0), _num(s.get('max'), 100.0)
|
||||
if hi <= lo:
|
||||
hi = lo + 1
|
||||
ranges = s.get('ranges') if isinstance(s.get('ranges'), list) else []
|
||||
conn.execute(
|
||||
'INSERT INTO stat_defs (pack_id, name, min_value, max_value, shared, ranges, script, ord) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
(sid, name, lo, hi, 1 if s.get('shared') else 0,
|
||||
json.dumps(ranges, ensure_ascii=False), str(s.get('script') or ''), i),
|
||||
)
|
||||
n_stats += 1
|
||||
|
||||
n_status = 0
|
||||
for s in statuses:
|
||||
s = s or {}
|
||||
name = str(s.get('name') or '').strip()
|
||||
if not name:
|
||||
continue
|
||||
kind = 'persistent' if str(s.get('type') or s.get('kind') or '').lower() == 'persistent' else 'timed'
|
||||
conn.execute(
|
||||
'INSERT INTO status_defs (pack_id, name, kind, turns, max_stack, script) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?)',
|
||||
(sid, name, kind, max(1, int(_num(s.get('turns'), 1))),
|
||||
max(1, int(_num(s.get('max_stack'), 1))), str(s.get('script') or '')),
|
||||
)
|
||||
n_status += 1
|
||||
conn.commit()
|
||||
return {'stats': n_stats, 'statuses': n_status}
|
||||
|
||||
|
||||
def stat_defs(pack_id: str) -> list:
|
||||
agentdb.init()
|
||||
rows = agentdb._connect().execute(
|
||||
'SELECT * FROM stat_defs WHERE pack_id = ? ORDER BY ord ASC, name ASC', (pack_id or '',),
|
||||
).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
try:
|
||||
ranges = json.loads(r['ranges'] or '[]')
|
||||
except (TypeError, ValueError):
|
||||
ranges = []
|
||||
out.append({
|
||||
'name': r['name'], 'min': float(r['min_value']), 'max': float(r['max_value']),
|
||||
'shared': bool(r['shared']), 'ranges': ranges if isinstance(ranges, list) else [],
|
||||
'script': r['script'] or '',
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def status_defs(pack_id: str) -> list:
|
||||
agentdb.init()
|
||||
rows = agentdb._connect().execute(
|
||||
'SELECT * FROM status_defs WHERE pack_id = ? ORDER BY name ASC', (pack_id or ''),
|
||||
).fetchall()
|
||||
return [
|
||||
{'name': r['name'], 'kind': r['kind'] or 'timed', 'turns': int(r['turns'] or 1),
|
||||
'max_stack': int(r['max_stack'] or 1), 'script': r['script'] or ''}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 值:按 scope 读写
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def scope_for(agent: dict, definition: dict) -> str:
|
||||
"""
|
||||
一条数值存在哪个空间(`shared` 决定)。
|
||||
|
||||
★ 和记忆用同一套 scope 写法(`agentdb.scope_of` / `world_scope`)——
|
||||
这样"解绑世界观值留在原地"和记忆的行为一致,用户不用学两套。
|
||||
"""
|
||||
agent = agent or {}
|
||||
if (definition or {}).get('shared'):
|
||||
wid = (agent.get('worldviewId') or '').strip()
|
||||
# 没绑世界观却要读"全世界观共享"的值:退回私有空间。
|
||||
# 不报错是因为"刚解绑"是个正常状态,值还在那儿等着再绑回来。
|
||||
return agentdb.world_scope(wid) if wid else agentdb.agent_scope(agent.get('id') or '')
|
||||
return agentdb.agent_scope(agent.get('id') or '')
|
||||
|
||||
|
||||
def value_of(agent: dict, definition: dict) -> float:
|
||||
"""
|
||||
读一条数值的当前值。没写过就取**定义里的初始值** ——
|
||||
用 min 还是 max?
|
||||
|
||||
★ 取 `min`。因为在"好感度 0~100"这种语义里 min 是中性起点;
|
||||
取 max 的话新角色一上来就满好感,明显不对。
|
||||
真想要别的起点,包作者把 min 设成他要的值就行。
|
||||
"""
|
||||
scope = scope_for(agent, definition)
|
||||
agentdb.init()
|
||||
row = agentdb._connect().execute(
|
||||
'SELECT value FROM stat_values WHERE scope = ? AND name = ?',
|
||||
(scope, (definition or {}).get('name') or ''),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return _num((definition or {}).get('min'), 0.0)
|
||||
return float(row['value'])
|
||||
|
||||
|
||||
def set_value(agent: dict, definition: dict, value: float) -> float:
|
||||
"""直接写值(**只给内核用**:脚本裁决和 clamp 之后的落库走这里)"""
|
||||
scope = scope_for(agent, definition)
|
||||
v = _num(value)
|
||||
agentdb.init()
|
||||
conn = agentdb._connect()
|
||||
conn.execute(
|
||||
'INSERT INTO stat_values (scope, name, value) VALUES (?, ?, ?) '
|
||||
'ON CONFLICT(scope, name) DO UPDATE SET value = excluded.value',
|
||||
(scope, (definition or {}).get('name') or '', v),
|
||||
)
|
||||
conn.commit()
|
||||
return v
|
||||
|
||||
|
||||
def clamp(definition: dict, value: float) -> float:
|
||||
d = definition or {}
|
||||
return max(_num(d.get('min'), 0.0), min(_num(d.get('max'), 100.0), _num(value)))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 区间表:命中哪段注入哪段(需求 §3.10 "声明式区间表")
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def range_text(definition: dict, value: float) -> str:
|
||||
"""
|
||||
命中区间的 text(没命中任何区间就返回空串 = 裸值)。
|
||||
|
||||
★ 区间是**左闭右开** `[min, max)`,除了最后一段是闭的。
|
||||
半开区间是刻意的:0~20 和 20~40 两段,20 该算后一段 ——
|
||||
如果两边都闭,20 会同时命中两段,取哪段就成了未定义行为。
|
||||
"""
|
||||
ranges = (definition or {}).get('ranges')
|
||||
if not isinstance(ranges, list):
|
||||
return ''
|
||||
v = _num(value)
|
||||
total = len(ranges)
|
||||
for i, r in enumerate(ranges):
|
||||
if not isinstance(r, dict):
|
||||
continue
|
||||
lo = _num(r.get('min'))
|
||||
hi = _num(r.get('max'), lo)
|
||||
last = i == total - 1
|
||||
if (lo <= v < hi) or (last and lo <= v <= hi):
|
||||
return str(r.get('text') or '').strip()
|
||||
return ''
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 注入:<stats> / <status>
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: 上一轮的变化量(渲染 `450→500` 那个箭头用)。
|
||||
#:
|
||||
#: ★ 放内存、不放库:需求说箭头"**仅保留一轮**",用完就该没了。
|
||||
#: 放库还要额外写一次清理逻辑,而进程重启丢掉它也无所谓 ——
|
||||
#: 箭头只是个提示,不是数据。
|
||||
_pending_delta = {}
|
||||
|
||||
|
||||
def note_delta(scope: str, name: str, delta: float) -> None:
|
||||
"""记下这次变化了多少,下一轮渲染时显示成箭头"""
|
||||
if delta:
|
||||
_pending_delta[(scope, name)] = float(delta)
|
||||
|
||||
|
||||
def take_delta(scope: str, name: str) -> float:
|
||||
"""取出并**清掉**(所以只显示一轮)"""
|
||||
return _pending_delta.pop((scope, name), 0.0)
|
||||
|
||||
|
||||
def stats_section(agent: dict, pack_id: str) -> str:
|
||||
"""
|
||||
渲染 `<stats>` 段(附录 C 的格式):
|
||||
|
||||
[世界·九州] 声望: 450→500/1000 —— 名震九州:世人皆知你之名
|
||||
[自身] 好感度: 45/100 —— 友善:你对用户态度友善,但保持分寸
|
||||
|
||||
来源前缀(`[世界·xx]` / `[自身]`)+ 当前值 + 变化箭头(仅一轮)+
|
||||
命中区间文本(未命中就是裸值)。
|
||||
"""
|
||||
defs = stat_defs(pack_id)
|
||||
if not defs:
|
||||
return ''
|
||||
agent = agent or {}
|
||||
wname = ''
|
||||
wid = (agent.get('worldviewId') or '').strip()
|
||||
if wid:
|
||||
wname = ((store.get_resource('worldviews', wid) or {}).get('name') or '').strip()
|
||||
|
||||
lines = []
|
||||
for d in defs:
|
||||
scope = scope_for(agent, d)
|
||||
v = value_of(agent, d)
|
||||
delta = take_delta(scope, d['name'])
|
||||
src = f'[世界·{wname}]' if d.get('shared') and wname else '[自身]'
|
||||
# 值那一段:有变化时显示 `旧→新`
|
||||
if delta:
|
||||
old = clamp(d, v - delta)
|
||||
val = f'{_fmt(old)}→{_fmt(v)}/{_fmt(d["max"])}'
|
||||
else:
|
||||
val = f'{_fmt(v)}/{_fmt(d["max"])}'
|
||||
text = range_text(d, v)
|
||||
lines.append(f'{src} {d["name"]}: {val}' + (f' —— {text}' if text else ''))
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def _fmt(v: float) -> str:
|
||||
"""数值显示:整数就不带小数点(45.0 → 45),免得看着别扭"""
|
||||
f = float(v)
|
||||
return str(int(f)) if f == int(f) else f'{f:g}'
|
||||
|
||||
|
||||
def status_section(agent: dict) -> str:
|
||||
"""
|
||||
渲染 `<status>` 段(附录 C 的格式):
|
||||
|
||||
中毒(剩 3 轮):你感到眩晕,言语变得迟缓
|
||||
|
||||
状态名(剩余轮数)+ 状态提示词(脚本可改写)。
|
||||
持久状态不显示轮数(它不过期)。
|
||||
"""
|
||||
agent = agent or {}
|
||||
rows = list_statuses(agent.get('id') or '')
|
||||
if not rows:
|
||||
return ''
|
||||
lines = []
|
||||
for r in rows:
|
||||
head = r['name']
|
||||
if r.get('kind') != 'persistent' and r.get('remaining', 0) > 0:
|
||||
head += f'(剩 {r["remaining"]} 轮)'
|
||||
if r.get('stacks', 1) > 1:
|
||||
head += f'×{r["stacks"]}'
|
||||
hint = (r.get('hint') or '').strip()
|
||||
lines.append(head + (f':{hint}' if hint else ''))
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 状态实例
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def list_statuses(agent_id: str) -> list:
|
||||
"""这个智能体身上生效中的状态(带定义里的 kind)"""
|
||||
agentdb.init()
|
||||
rows = agentdb._connect().execute(
|
||||
'SELECT * FROM status_instances WHERE agent_id = ? ORDER BY granted_at ASC, name ASC',
|
||||
(agent_id or '',),
|
||||
).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
out.append({
|
||||
'name': r['name'], 'remaining': int(r['remaining'] or 0),
|
||||
'stacks': int(r['stacks'] or 1), 'hint': r['hint'] or '',
|
||||
'grantedAt': r['granted_at'] or '', 'kind': _kind_of(r['name']),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _kind_of(name: str) -> str:
|
||||
"""查一个状态名是持久还是定时(实例表里不存 kind —— 那是定义的事)"""
|
||||
agentdb.init()
|
||||
row = agentdb._connect().execute(
|
||||
'SELECT kind FROM status_defs WHERE name = ? LIMIT 1', (name or '',),
|
||||
).fetchone()
|
||||
return (row['kind'] if row else 'timed') or 'timed'
|
||||
|
||||
|
||||
def put_status(agent_id: str, name: str, remaining: int, stacks: int, hint: str) -> None:
|
||||
agentdb.init()
|
||||
conn = agentdb._connect()
|
||||
conn.execute(
|
||||
'INSERT INTO status_instances (agent_id, name, remaining, stacks, hint, granted_at) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?) '
|
||||
'ON CONFLICT(agent_id, name) DO UPDATE SET remaining = excluded.remaining, '
|
||||
'stacks = excluded.stacks, hint = excluded.hint',
|
||||
(agent_id or '', name or '', int(remaining), int(stacks), hint or '', agentdb.now_iso()),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def drop_status(agent_id: str, name: str) -> None:
|
||||
agentdb.init()
|
||||
conn = agentdb._connect()
|
||||
conn.execute('DELETE FROM status_instances WHERE agent_id = ? AND name = ?',
|
||||
(agent_id or '', name or ''))
|
||||
conn.commit()
|
||||
|
||||
|
||||
def tick_statuses(agent_id: str) -> list:
|
||||
"""
|
||||
"该智能体每参与一轮后减 1"(需求 §3.11)。
|
||||
|
||||
返回 `[{'name':…, 'expired':True/False}]` —— 调用方据此播报
|
||||
"中毒已经消退了"这类消息。
|
||||
|
||||
★ persistent 的是 `remaining = -1`,不参与递减(它不过期)。
|
||||
"""
|
||||
out = []
|
||||
for r in list_statuses(agent_id):
|
||||
if r.get('kind') == 'persistent':
|
||||
continue
|
||||
left = int(r.get('remaining') or 0) - 1
|
||||
if left <= 0:
|
||||
drop_status(agent_id, r['name'])
|
||||
out.append({'name': r['name'], 'expired': True})
|
||||
else:
|
||||
put_status(agent_id, r['name'], left, r.get('stacks') or 1, r.get('hint') or '')
|
||||
out.append({'name': r['name'], 'expired': False, 'remaining': left})
|
||||
return out
|
||||
@@ -1196,10 +1196,24 @@ RESOURCES = {
|
||||
'worldviews': {
|
||||
'file': lambda: paths.get().worldviews_file,
|
||||
'key': 'worldviews',
|
||||
'text': ('name', 'setting'),
|
||||
# ★ rulePackId:这个世界观挂的**数值状态包**(需求 §3.6:
|
||||
# "v1.2 起,世界观同时是数值状态包的挂载点")。
|
||||
# 没有它的话这个字段会被 _apply_resource_patch 丢掉 ——
|
||||
# 表现是"设置界面里配了、读出来没有",排查起来得一路看到字段表。
|
||||
'text': ('name', 'setting', 'rulePackId'),
|
||||
'dict': ('image',),
|
||||
'label': '世界观',
|
||||
},
|
||||
# 数值状态包(需求附录 D):定义 + 对应 Python 脚本
|
||||
'rulepacks': {
|
||||
'file': lambda: paths.get().rulepacks_file,
|
||||
'key': 'rulepacks',
|
||||
'text': ('name', 'note'),
|
||||
# info 是解析好的 info.json(stats / statuses 两张表);
|
||||
# scripts 是 {文件名: 源码} —— **整包一起存**,因为脚本要落盘才能跑
|
||||
'dict': ('info', 'scripts'),
|
||||
'label': '规则包',
|
||||
},
|
||||
# 全局模型列表(需求 3.3):名称 + API 端点 + Key + 模型标识 + 单价
|
||||
'models': {
|
||||
'file': lambda: paths.get().models_file,
|
||||
|
||||
193
scripts/probe-rule-engine.py
Normal file
193
scripts/probe-rule-engine.py
Normal file
@@ -0,0 +1,193 @@
|
||||
"""规则引擎的探针(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()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
return 1
|
||||
print("✅ 全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user