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 工具 + 脚本接线 + 规则包导入导出。
397 lines
15 KiB
Python
397 lines
15 KiB
Python
"""规则引擎:数值系统 + 状态系统(需求 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
|