lingshu-skill 4.9.0 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/README.md +1 -1
- package/SKILL.md +1 -1
- package/docs//345/200/237/351/211/264-/346/230/223/347/273/217/344/270/216/345/217/244/345/205/270/347/256/227/346/263/225.md +266 -0
- package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +35 -0
- package/package.json +1 -1
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +8 -6
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +32 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +17 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +4 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +76 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety_net.py +355 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/shape_audit.py +182 -0
- package/scripts/cli.py +17 -0
- package/scripts/core.py +4 -0
- package/scripts/memory.py +76 -0
- package/scripts/safety_net.py +355 -0
- package/scripts/shape_audit.py +182 -0
package/scripts/core.py
CHANGED
|
@@ -333,6 +333,10 @@ DEFAULT_CONFIG = {
|
|
|
333
333
|
"auto_update": False,
|
|
334
334
|
# 安装完成后是否自动在桌面生成「灵枢面板」快捷方式(默认开;已存在不覆盖)
|
|
335
335
|
"desktop_shortcut": True,
|
|
336
|
+
# —— 底层保险(v5.0):写前 O(1) 硬链接快照 + 写后校验 + 失败自动回滚 ——
|
|
337
|
+
"safety_snapshots": True, # 关掉就没有快照/回滚保护(不建议)
|
|
338
|
+
"safety_verify": True, # 写后校验(JSON 可解析 + 层级自洽)
|
|
339
|
+
"safety_keep": 20, # 保留最近多少份快照;更旧的移入 .safety/.pruned/(不删)
|
|
336
340
|
"auto_update_interval_hours": 24,
|
|
337
341
|
"session_state_cache": False,
|
|
338
342
|
"session_state_ttl": 300,
|
package/scripts/memory.py
CHANGED
|
@@ -869,6 +869,20 @@ def archive_run(dry_run: bool = False) -> dict:
|
|
|
869
869
|
|
|
870
870
|
|
|
871
871
|
def save_all(records: list) -> None:
|
|
872
|
+
# 底层保险(safety_net):写前做 O(1) 硬链接快照,写后校验,失败自动回滚。
|
|
873
|
+
# 为什么值得:这是全项目最高危的写入口(17 个公开函数最终都落到这里),
|
|
874
|
+
# 一旦传进来的 records 混层/丢记录,对应层就被整层覆盖。
|
|
875
|
+
# fail-open:快照失败不阻断主写入(宁可少一层保险,也不能让 remember 挂掉)。
|
|
876
|
+
_snap = None
|
|
877
|
+
_sn = None
|
|
878
|
+
try:
|
|
879
|
+
import safety_net as _sn_mod
|
|
880
|
+
_sn = _sn_mod
|
|
881
|
+
if not READONLY:
|
|
882
|
+
_snap = _sn.snapshot("save_all",
|
|
883
|
+
("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl"))
|
|
884
|
+
except Exception:
|
|
885
|
+
_snap = None
|
|
872
886
|
groups = {"hippo": [], "cortex": [], "dust": []}
|
|
873
887
|
for r in records:
|
|
874
888
|
layer = r.get("layer", "hippo")
|
|
@@ -910,6 +924,25 @@ def save_all(records: list) -> None:
|
|
|
910
924
|
for tmp, p in staged:
|
|
911
925
|
_replace_retry(tmp, p)
|
|
912
926
|
|
|
927
|
+
# 写后校验:JSON 可解析 + 末行完整 + 层级自洽。不通过就回滚并抛错
|
|
928
|
+
# (回滚成功时数据是"旧的一致状态",比留着一份写坏的新数据安全)。
|
|
929
|
+
if _snap and _sn is not None:
|
|
930
|
+
try:
|
|
931
|
+
_v = _sn.verify(("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl"))
|
|
932
|
+
if not _v.get("ok"):
|
|
933
|
+
_sn.restore(_snap)
|
|
934
|
+
raise RuntimeError(
|
|
935
|
+
"save_all 写后校验失败,已从快照自动回滚:"
|
|
936
|
+
+ ";".join((_v.get("issues") or [])[:3]))
|
|
937
|
+
except RuntimeError:
|
|
938
|
+
raise
|
|
939
|
+
except Exception as exc: # noqa: BLE001
|
|
940
|
+
try:
|
|
941
|
+
log_event("safety", f"写后校验本身出错(已跳过,数据未动):{exc}",
|
|
942
|
+
level="warn")
|
|
943
|
+
except Exception:
|
|
944
|
+
pass
|
|
945
|
+
|
|
913
946
|
|
|
914
947
|
# ---------------------------------------------------------------- 记忆记录
|
|
915
948
|
|
|
@@ -1905,6 +1938,36 @@ def dereference(memory_id: str) -> list:
|
|
|
1905
1938
|
return out
|
|
1906
1939
|
|
|
1907
1940
|
|
|
1941
|
+
# ---------------------------------------------------------------- 错卦:否定极性
|
|
1942
|
+
# 「错卦」在易经里是六爻全变(按位取反)。借到检索上就是**否定极性**:
|
|
1943
|
+
# "用 X" 和 "不要用 X" 是两个方向,不该拿到同一批无标记的结果。
|
|
1944
|
+
#
|
|
1945
|
+
# 实测问题(2026-11-24,隔离库三条记忆):
|
|
1946
|
+
# recall "用 DiskGenius 恢复分区" → ①不要用…(排第一)②用…可行 ③先做镜像
|
|
1947
|
+
# recall "不要用 DiskGenius 恢复分区" → ①不要用… ③先做镜像 ②用…可行
|
|
1948
|
+
# 结果集 3/3 完全重合,且**肯定查询把「不要用」的禁止记忆排到第一位、无任何标记**。
|
|
1949
|
+
# 模型看到这个很容易读反,所以这里不静默降权(把禁令藏起来更危险),
|
|
1950
|
+
# 而是**把冲突标出来**,交给调用方/模型自己判断。
|
|
1951
|
+
_POLARITY_NEG = re.compile(
|
|
1952
|
+
r"不要|别用|别再|别碰|别动|不要再|勿|切勿|禁止|避免|不能|不可|禁用|放弃|"
|
|
1953
|
+
r"不推荐|不建议|不需要|无需|千万别")
|
|
1954
|
+
|
|
1955
|
+
|
|
1956
|
+
def _polarity_of(text: str) -> str:
|
|
1957
|
+
"""文本的否定极性:'neg'(否定/禁止)或 'pos'(肯定)。空文本返回 ''。"""
|
|
1958
|
+
s = str(text or "").strip()
|
|
1959
|
+
if not s:
|
|
1960
|
+
return ""
|
|
1961
|
+
return "neg" if _POLARITY_NEG.search(s) else "pos"
|
|
1962
|
+
|
|
1963
|
+
|
|
1964
|
+
def _memory_polarity(rec: dict) -> str:
|
|
1965
|
+
"""一条记忆的极性:显式 avoid 标记优先,否则看正文。"""
|
|
1966
|
+
if rec.get("avoid"):
|
|
1967
|
+
return "neg"
|
|
1968
|
+
return _polarity_of(rec.get("text") or "")
|
|
1969
|
+
|
|
1970
|
+
|
|
1908
1971
|
def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
1909
1972
|
strengthen: bool = True, include_dust: bool = False,
|
|
1910
1973
|
include_archive: bool = False,
|
|
@@ -2269,6 +2332,19 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
2269
2332
|
kept_texts.append(txt)
|
|
2270
2333
|
result = kept
|
|
2271
2334
|
|
|
2335
|
+
# 错卦(v5.1):标注"查询方向"与"记忆极性"的冲突。
|
|
2336
|
+
# 只在**方向相反**时打标(查询肯定↔记忆禁止,或反之),一致时不打扰。
|
|
2337
|
+
try:
|
|
2338
|
+
_qp = _polarity_of(query)
|
|
2339
|
+
if _qp:
|
|
2340
|
+
for _m, _s, _p in result:
|
|
2341
|
+
_mp = _memory_polarity(_m)
|
|
2342
|
+
if _mp and _mp != _qp and isinstance(_p, dict):
|
|
2343
|
+
_p["polarity"] = _mp
|
|
2344
|
+
_p["polarity_conflict"] = True
|
|
2345
|
+
except Exception:
|
|
2346
|
+
pass
|
|
2347
|
+
|
|
2272
2348
|
if strengthen and not READONLY:
|
|
2273
2349
|
touched = [m for m, _, _ in result]
|
|
2274
2350
|
for m in touched:
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""底层保险:写前快照 + 写后校验 + 失败自动回滚(灵枢版 ARIES-lite)。
|
|
3
|
+
|
|
4
|
+
## 为什么要做
|
|
5
|
+
|
|
6
|
+
`save_all()` 是全项目最高危的写入口:它按 layer 把整批 records 分写回
|
|
7
|
+
hippocampus/cortex/dust 三个文件,**一旦读写之间丢记录或层名写错,就是整层被
|
|
8
|
+
覆盖**(本会话就踩过一次:用 `write_jsonl(hippocampus, load_all())` 差点把
|
|
9
|
+
cortex/dust 全灌进 hippocampus)。而项目里有 17 个公开函数走 `save_all()`。
|
|
10
|
+
|
|
11
|
+
## 借鉴了什么
|
|
12
|
+
|
|
13
|
+
| 出处 | 借的东西 |
|
|
14
|
+
|---|---|
|
|
15
|
+
| **ARIES / WAL**(Mohan 1992) | "先记 undo 日志再改数据,出错用 undo 回滚" |
|
|
16
|
+
| **rsnapshot / Time Machine 本地快照** | **硬链接即快照**:`os.link()` 是 O(1)、零拷贝,天然 COW |
|
|
17
|
+
| **crash-only software**(Candea & Fox 2003) | 假定随时会崩;恢复逻辑放常路,不靠"优雅关闭" |
|
|
18
|
+
| **SQLite WAL / LMDB COW** | 单写者 + 原子替换(本项目 `_replace_retry` 已是 os.replace) |
|
|
19
|
+
|
|
20
|
+
**为什么硬链接就够**:本项目写盘一律"写临时文件 → `os.replace`"。替换只改目录项,
|
|
21
|
+
老 inode 不动,所以事先 `os.link` 出来的快照**永远保留旧内容**——不需要复制字节。
|
|
22
|
+
|
|
23
|
+
## 边界(重要)
|
|
24
|
+
|
|
25
|
+
- 只保护**记忆层文件**(hippocampus/cortex/dust/archive)+ persona.json。
|
|
26
|
+
- 快照保留 N 份,更旧的**移入 `.pruned/` 而不是删除**(用户 v4.3 规矩:只移不删)。
|
|
27
|
+
- 任何一步失败都不能让主写入失败:`fail-open`,只记 warn 日志。
|
|
28
|
+
"""
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import hashlib
|
|
32
|
+
import json
|
|
33
|
+
import os
|
|
34
|
+
import re
|
|
35
|
+
import shutil
|
|
36
|
+
import time
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
|
|
39
|
+
import core
|
|
40
|
+
|
|
41
|
+
SNAP_DIRNAME = ".safety"
|
|
42
|
+
DEFAULT_KEEP = 20
|
|
43
|
+
PROTECTED = ("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl",
|
|
44
|
+
"archive.jsonl", "persona.json")
|
|
45
|
+
# 文件 → 该文件里记录应有的 layer 值。
|
|
46
|
+
# 用途:抓"整批记录被灌错层"的 bug——那种错 JSON 仍合法、只查语法查不出来。
|
|
47
|
+
_LAYER_OF_FILE = {
|
|
48
|
+
"hippocampus.jsonl": "hippo",
|
|
49
|
+
"cortex.jsonl": "cortex",
|
|
50
|
+
"dust.jsonl": "dust",
|
|
51
|
+
"archive.jsonl": "archive",
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _home() -> Path:
|
|
56
|
+
return Path(core.HOME)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def snap_root() -> Path:
|
|
60
|
+
return _home() / SNAP_DIRNAME
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _enabled() -> bool:
|
|
64
|
+
"""配置开关(默认开);坏配置当开——保险不该因为配置读不出来就失效。"""
|
|
65
|
+
try:
|
|
66
|
+
return bool(core.load_config().get("safety_snapshots", True))
|
|
67
|
+
except Exception:
|
|
68
|
+
return True
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _verify_enabled() -> bool:
|
|
72
|
+
try:
|
|
73
|
+
return bool(core.load_config().get("safety_verify", True))
|
|
74
|
+
except Exception:
|
|
75
|
+
return True
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _keep() -> int:
|
|
79
|
+
try:
|
|
80
|
+
n = int(core.load_config().get("safety_keep") or DEFAULT_KEEP)
|
|
81
|
+
return n if n > 0 else DEFAULT_KEEP
|
|
82
|
+
except Exception:
|
|
83
|
+
return DEFAULT_KEEP
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _slug(reason: str) -> str:
|
|
87
|
+
s = re.sub(r"[^0-9A-Za-z_\u4e00-\u9fff-]+", "_", str(reason or "write"))[:40]
|
|
88
|
+
return s or "write"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _resolve(names) -> list:
|
|
92
|
+
"""只接受受保护的文件名,其它一律忽略(防被当通用备份工具误用)。"""
|
|
93
|
+
out = []
|
|
94
|
+
home = _home()
|
|
95
|
+
for n in names:
|
|
96
|
+
name = Path(str(n)).name
|
|
97
|
+
if name not in PROTECTED:
|
|
98
|
+
continue
|
|
99
|
+
p = home / name
|
|
100
|
+
if p.is_file():
|
|
101
|
+
out.append(p)
|
|
102
|
+
return out
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def snapshot(reason: str = "write", names=None) -> str | None:
|
|
106
|
+
"""给受保护文件做 O(1) 硬链接快照,返回快照 id;失败返回 None(不阻断写入)。"""
|
|
107
|
+
if not _enabled():
|
|
108
|
+
return None
|
|
109
|
+
targets = _resolve(names or PROTECTED)
|
|
110
|
+
if not targets:
|
|
111
|
+
return None
|
|
112
|
+
stamp = time.strftime("%Y%m%d-%H%M%S")
|
|
113
|
+
base = snap_root()
|
|
114
|
+
sid = f"{stamp}_{_slug(reason)}"
|
|
115
|
+
dst = base / sid
|
|
116
|
+
k = 1
|
|
117
|
+
while dst.exists():
|
|
118
|
+
dst = base / f"{sid}_{k}"
|
|
119
|
+
k += 1
|
|
120
|
+
try:
|
|
121
|
+
dst.mkdir(parents=True, exist_ok=True)
|
|
122
|
+
linked = {}
|
|
123
|
+
for p in targets:
|
|
124
|
+
lp = dst / p.name
|
|
125
|
+
try:
|
|
126
|
+
os.link(p, lp) # O(1) 零拷贝:硬链接
|
|
127
|
+
linked[p.name] = "link"
|
|
128
|
+
except OSError:
|
|
129
|
+
# 跨卷/文件系统不支持硬链接 → 退回复制(慢但正确)
|
|
130
|
+
shutil.copy2(p, lp)
|
|
131
|
+
linked[p.name] = "copy"
|
|
132
|
+
counts = {}
|
|
133
|
+
for p in targets:
|
|
134
|
+
try:
|
|
135
|
+
counts[p.name] = sum(1 for ln in p.open(encoding="utf-8", errors="replace")
|
|
136
|
+
if ln.strip())
|
|
137
|
+
except OSError:
|
|
138
|
+
counts[p.name] = -1
|
|
139
|
+
# 给快照内容记指纹。硬链接快照只在"原子替换"写入下成立——万一有代码
|
|
140
|
+
# 路径**就地截断**写(open("w")),共享 inode 会被改,快照当场失效。
|
|
141
|
+
# 记 sha256 就能在回滚前发现"快照已被污染",而不是拿脏快照去覆盖。
|
|
142
|
+
digests = {}
|
|
143
|
+
for p in targets:
|
|
144
|
+
try:
|
|
145
|
+
h = hashlib.sha256()
|
|
146
|
+
with p.open("rb") as f:
|
|
147
|
+
for chunk in iter(lambda: f.read(1 << 20), b""):
|
|
148
|
+
h.update(chunk)
|
|
149
|
+
digests[p.name] = h.hexdigest()
|
|
150
|
+
except OSError:
|
|
151
|
+
digests[p.name] = ""
|
|
152
|
+
(dst / "meta.json").write_text(json.dumps({
|
|
153
|
+
"id": dst.name, "reason": str(reason)[:120], "ts": int(time.time()),
|
|
154
|
+
"mode": linked, "counts": counts, "sha256": digests,
|
|
155
|
+
}, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
156
|
+
_prune()
|
|
157
|
+
return dst.name
|
|
158
|
+
except Exception as exc: # noqa: BLE001
|
|
159
|
+
try:
|
|
160
|
+
core.log_event("safety", f"写前快照失败(不影响写入):{exc}", level="warn")
|
|
161
|
+
except Exception:
|
|
162
|
+
pass
|
|
163
|
+
return None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _counts_of(targets) -> dict:
|
|
167
|
+
out = {}
|
|
168
|
+
for p in targets:
|
|
169
|
+
try:
|
|
170
|
+
out[p.name] = sum(1 for ln in p.open(encoding="utf-8", errors="replace")
|
|
171
|
+
if ln.strip())
|
|
172
|
+
except OSError:
|
|
173
|
+
out[p.name] = -1
|
|
174
|
+
return out
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def verify(names=None, allow_shrink=()) -> dict:
|
|
178
|
+
"""写后校验:文件在、每行可解析、没被截断、哈希链字段齐。
|
|
179
|
+
|
|
180
|
+
返回 {"ok": bool, "issues": [...], "counts": {...}}。
|
|
181
|
+
`allow_shrink` 里列出的文件名允许行数减少(删除类操作显式声明)。
|
|
182
|
+
"""
|
|
183
|
+
targets = _resolve(names or PROTECTED)
|
|
184
|
+
issues = []
|
|
185
|
+
counts = {}
|
|
186
|
+
for p in targets:
|
|
187
|
+
try:
|
|
188
|
+
raw = p.read_text(encoding="utf-8", errors="replace")
|
|
189
|
+
except OSError as exc:
|
|
190
|
+
issues.append(f"{p.name} 读不出来:{exc}")
|
|
191
|
+
continue
|
|
192
|
+
lines = [ln for ln in raw.splitlines() if ln.strip()]
|
|
193
|
+
counts[p.name] = len(lines)
|
|
194
|
+
if raw and not raw.endswith("\n"):
|
|
195
|
+
issues.append(f"{p.name} 末行没有换行——可能被截断")
|
|
196
|
+
if p.name.endswith(".jsonl"):
|
|
197
|
+
parsed = []
|
|
198
|
+
for i, ln in enumerate(lines, 1):
|
|
199
|
+
try:
|
|
200
|
+
parsed.append(json.loads(ln))
|
|
201
|
+
except Exception:
|
|
202
|
+
issues.append(f"{p.name} 第 {i} 行不是合法 JSON(可能写到一半)")
|
|
203
|
+
break
|
|
204
|
+
# 层级一致性:记录自带 layer 必须与"它落在哪个文件"自洽。
|
|
205
|
+
# 这条能抓住"整批记录被灌错层"的 bug(JSON 合法但分层已坏)。
|
|
206
|
+
want = _LAYER_OF_FILE.get(p.name)
|
|
207
|
+
if want and len(parsed) == len(lines):
|
|
208
|
+
bad = [r for r in parsed
|
|
209
|
+
if isinstance(r, dict) and r.get("layer")
|
|
210
|
+
and r.get("layer") != want]
|
|
211
|
+
if bad:
|
|
212
|
+
issues.append(
|
|
213
|
+
f"{p.name} 有 {len(bad)} 条记录的 layer 与文件不匹配"
|
|
214
|
+
f"(该文件应只放 layer={want},实际含 "
|
|
215
|
+
f"{sorted({str(r.get('layer')) for r in bad})[:3]})")
|
|
216
|
+
return {"ok": not issues, "issues": issues, "counts": counts}
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def restore(snap_id: str) -> dict:
|
|
220
|
+
"""从快照回滚(只回写快照里存在的文件),走原子替换。
|
|
221
|
+
|
|
222
|
+
**回滚前先验快照完整性**:硬链接快照与工作文件共享 inode,若期间有人
|
|
223
|
+
就地写(非原子替换),快照会跟着被改。指纹不符就拒绝回滚并报错——
|
|
224
|
+
拿一份被污染的快照去覆盖,比不回滚更糟。
|
|
225
|
+
"""
|
|
226
|
+
src = snap_root() / Path(str(snap_id)).name
|
|
227
|
+
if not src.is_dir():
|
|
228
|
+
raise FileNotFoundError(f"没有这个快照:{snap_id}")
|
|
229
|
+
meta = {}
|
|
230
|
+
try:
|
|
231
|
+
meta = json.loads((src / "meta.json").read_text(encoding="utf-8"))
|
|
232
|
+
except Exception:
|
|
233
|
+
meta = {}
|
|
234
|
+
want = meta.get("sha256") or {}
|
|
235
|
+
restored, corrupt = [], []
|
|
236
|
+
for f in sorted(src.glob("*")):
|
|
237
|
+
if f.name == "meta.json" or f.is_dir():
|
|
238
|
+
continue
|
|
239
|
+
if f.name not in PROTECTED:
|
|
240
|
+
continue
|
|
241
|
+
w = want.get(f.name)
|
|
242
|
+
if w:
|
|
243
|
+
try:
|
|
244
|
+
h = hashlib.sha256()
|
|
245
|
+
with f.open("rb") as fh:
|
|
246
|
+
for chunk in iter(lambda: fh.read(1 << 20), b""):
|
|
247
|
+
h.update(chunk)
|
|
248
|
+
if h.hexdigest() != w:
|
|
249
|
+
corrupt.append(f.name)
|
|
250
|
+
continue
|
|
251
|
+
except OSError:
|
|
252
|
+
corrupt.append(f.name)
|
|
253
|
+
continue
|
|
254
|
+
dst = _home() / f.name
|
|
255
|
+
tmp = dst.with_name(dst.name + ".restore.tmp")
|
|
256
|
+
shutil.copy2(f, tmp)
|
|
257
|
+
core._replace_retry(tmp, dst)
|
|
258
|
+
restored.append(f.name)
|
|
259
|
+
if corrupt:
|
|
260
|
+
raise RuntimeError(
|
|
261
|
+
"快照已被污染(内容与快照时记录的 sha256 不符),拒绝用它回滚:"
|
|
262
|
+
+ ", ".join(corrupt)
|
|
263
|
+
+ "。原因通常是有代码路径就地写文件而不是原子替换。")
|
|
264
|
+
try:
|
|
265
|
+
core.log_event("safety", f"已从快照回滚 {snap_id}:{', '.join(restored)}",
|
|
266
|
+
level="warn")
|
|
267
|
+
except Exception:
|
|
268
|
+
pass
|
|
269
|
+
return {"ok": True, "snapshot": src.name, "restored": restored}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def list_snapshots(limit: int = 20) -> list:
|
|
273
|
+
root = snap_root()
|
|
274
|
+
out = []
|
|
275
|
+
if not root.is_dir():
|
|
276
|
+
return out
|
|
277
|
+
for d in sorted((x for x in root.iterdir() if x.is_dir() and x.name != ".pruned"),
|
|
278
|
+
key=lambda x: x.stat().st_mtime, reverse=True)[:limit]:
|
|
279
|
+
meta = {}
|
|
280
|
+
try:
|
|
281
|
+
meta = json.loads((d / "meta.json").read_text(encoding="utf-8"))
|
|
282
|
+
except Exception:
|
|
283
|
+
pass
|
|
284
|
+
out.append({"id": d.name,
|
|
285
|
+
"time": time.strftime("%Y-%m-%d %H:%M", time.localtime(d.stat().st_mtime)),
|
|
286
|
+
"reason": meta.get("reason", ""), "counts": meta.get("counts", {})})
|
|
287
|
+
return out
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _prune() -> None:
|
|
291
|
+
"""超过保留份数的旧快照**移入 .pruned/**(不删除)。"""
|
|
292
|
+
root = snap_root()
|
|
293
|
+
if not root.is_dir():
|
|
294
|
+
return
|
|
295
|
+
dirs = sorted((x for x in root.iterdir() if x.is_dir() and x.name != ".pruned"),
|
|
296
|
+
key=lambda x: x.stat().st_mtime, reverse=True)
|
|
297
|
+
keep = _keep()
|
|
298
|
+
over = dirs[keep:]
|
|
299
|
+
if not over:
|
|
300
|
+
return
|
|
301
|
+
pruned = root / ".pruned"
|
|
302
|
+
pruned.mkdir(parents=True, exist_ok=True)
|
|
303
|
+
for d in over:
|
|
304
|
+
try:
|
|
305
|
+
dst = pruned / d.name
|
|
306
|
+
k = 1
|
|
307
|
+
while dst.exists():
|
|
308
|
+
dst = pruned / f"{d.name}_{k}"
|
|
309
|
+
k += 1
|
|
310
|
+
shutil.move(str(d), str(dst))
|
|
311
|
+
except Exception:
|
|
312
|
+
pass
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def guarded_write(reason: str, writer, names=None, allow_shrink=()) -> dict:
|
|
316
|
+
"""**保险入口**:快照 → 执行 writer() → 校验 → 失败自动回滚。
|
|
317
|
+
|
|
318
|
+
`writer` 是个无参可调用(真正的写盘动作)。返回
|
|
319
|
+
{"ok", "snapshot", "verified", "restored", "issues"}。
|
|
320
|
+
校验失败会回滚并把 ok=False 返回**而不抛异常**——保住老数据比暴露异常更重要,
|
|
321
|
+
但调用方应当把 ok 当回事(记日志/提示用户)。
|
|
322
|
+
"""
|
|
323
|
+
names = names or PROTECTED
|
|
324
|
+
snap = snapshot(reason, names)
|
|
325
|
+
err = None
|
|
326
|
+
try:
|
|
327
|
+
writer()
|
|
328
|
+
except Exception as exc: # noqa: BLE001
|
|
329
|
+
err = exc
|
|
330
|
+
report = {"ok": True, "snapshot": snap, "verified": None,
|
|
331
|
+
"restored": None, "issues": [], "error": None}
|
|
332
|
+
if err is not None:
|
|
333
|
+
report["ok"] = False
|
|
334
|
+
report["error"] = str(err)
|
|
335
|
+
if snap:
|
|
336
|
+
try:
|
|
337
|
+
report["restored"] = restore(snap).get("restored")
|
|
338
|
+
report["ok"] = True # 回滚成功 = 数据保住了
|
|
339
|
+
report["error"] = f"写入异常已回滚:{err}"
|
|
340
|
+
except Exception as rexc: # noqa: BLE001
|
|
341
|
+
report["error"] = f"写入异常且回滚失败:{err} / {rexc}"
|
|
342
|
+
return report
|
|
343
|
+
if _verify_enabled():
|
|
344
|
+
v = verify(names, allow_shrink=allow_shrink)
|
|
345
|
+
report["verified"] = v["counts"]
|
|
346
|
+
if not v["ok"]:
|
|
347
|
+
report["ok"] = False
|
|
348
|
+
report["issues"] = v["issues"]
|
|
349
|
+
if snap:
|
|
350
|
+
try:
|
|
351
|
+
report["restored"] = restore(snap).get("restored")
|
|
352
|
+
report["ok"] = True # 已回滚,数据一致
|
|
353
|
+
except Exception as rexc: # noqa: BLE001
|
|
354
|
+
report["issues"].append(f"回滚失败:{rexc}")
|
|
355
|
+
return report
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""六爻位体检(shape-audit):把一条记忆的六个二元特征当"六爻",映射到 64 格,
|
|
3
|
+
用「当位 / 得中 / 有应」三组结构谓词判它合不合理。
|
|
4
|
+
|
|
5
|
+
**纯只读**:只扫描、只输出,绝不写任何文件。
|
|
6
|
+
|
|
7
|
+
## 为什么这么映射(不是玄学,是六个真问题)
|
|
8
|
+
|
|
9
|
+
| 爻位 | 特征 | 0 | 1 |
|
|
10
|
+
|---|---|---|---|
|
|
11
|
+
| 初 | 来源 | ai / 派生 | user / 亲历 |
|
|
12
|
+
| 二 | 审核 | pending 等 | confirmed |
|
|
13
|
+
| 三 | 层 | dust / archive | hippo / cortex |
|
|
14
|
+
| 四 | 类型 | 一次性 episode | 稳定 fact/preference/norm |
|
|
15
|
+
| 五 | 置信 | < 0.6 | ≥ 0.6 |
|
|
16
|
+
| 上 | 时效 | 已过 review_by | 未过期 / 无期限 |
|
|
17
|
+
|
|
18
|
+
## 三组谓词(易经里本来就有的约束系统)
|
|
19
|
+
|
|
20
|
+
- **当位**:阳(1)居奇位(初/三/五)、阴(0)居偶位(二/四/上)
|
|
21
|
+
- **得中**:居第二或第五爻
|
|
22
|
+
- **有应**:初↔四、二↔五、三↔上 三对,阴阳相反为有应
|
|
23
|
+
|
|
24
|
+
违反这些谓词,往往正是**真实的坏数据**:
|
|
25
|
+
- 初=1(用户亲历)但 二=0(待审)→ 不当位(v3.80 修过的 bug 就是这个)
|
|
26
|
+
- 五=1(高置信)但 三=0(在 dust)→ 不当位:高置信不该沉在淡忘区
|
|
27
|
+
- 二=1(已确认)但 初=0(AI 派生)且 五=0(低置信)→ 失应:最易沉淀幻觉的组合
|
|
28
|
+
"""
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import json
|
|
32
|
+
from collections import Counter
|
|
33
|
+
|
|
34
|
+
import core
|
|
35
|
+
import memory as mem
|
|
36
|
+
|
|
37
|
+
STABLE_KINDS = {"fact", "preference", "norm", "intent", "relationship", "insight"}
|
|
38
|
+
HOT_LAYERS = {"hippo", "cortex"}
|
|
39
|
+
|
|
40
|
+
POSITION_NAMES = ["初", "二", "三", "四", "五", "上"]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _num(v, d=0.0):
|
|
44
|
+
try:
|
|
45
|
+
return float(v)
|
|
46
|
+
except (TypeError, ValueError):
|
|
47
|
+
return d
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def signature(rec: dict) -> int:
|
|
51
|
+
"""六爻 → 6 位整数(初爻是最低位)。"""
|
|
52
|
+
bits = []
|
|
53
|
+
src = str(rec.get("source") or "")
|
|
54
|
+
bits.append(1 if src in ("user", "checkpoint") else 0) # 初:来源
|
|
55
|
+
bits.append(1 if str(rec.get("review") or "") == "confirmed" else 0) # 二:审核
|
|
56
|
+
bits.append(1 if str(rec.get("layer") or "") in HOT_LAYERS else 0) # 三:层
|
|
57
|
+
bits.append(1 if str(rec.get("kind") or "") in STABLE_KINDS else 0) # 四:类型
|
|
58
|
+
conf = rec.get("confidence")
|
|
59
|
+
conf = _num(conf, _num(rec.get("importance"), 0.5))
|
|
60
|
+
bits.append(1 if conf >= 0.6 else 0) # 五:置信
|
|
61
|
+
rb = rec.get("review_by")
|
|
62
|
+
expired = bool(rb) and _num(rb, 0) > 0 and _num(rb, 0) < core.now_ts()
|
|
63
|
+
bits.append(0 if expired else 1) # 上:时效
|
|
64
|
+
val = 0
|
|
65
|
+
for i, b in enumerate(bits):
|
|
66
|
+
if b:
|
|
67
|
+
val |= (1 << i)
|
|
68
|
+
return val
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def analyse(rec: dict) -> dict:
|
|
72
|
+
"""该记录的结构分析。
|
|
73
|
+
|
|
74
|
+
⚠ **实测结论(2026-11-24,真库 306 条)**:易经里字面的三组谓词——
|
|
75
|
+
「当位」(阳居奇位/阴居偶位)、「得中」、「有应」——在真实记忆数据上
|
|
76
|
+
**几乎不区分**:不当位 100%、失应 74%、未得中 75%。原因是这六位特征
|
|
77
|
+
并不是为"交替排列"设计的,硬套字面规则等于给每条记录都判一次违规,
|
|
78
|
+
也就等于什么都没说(这正是"伪精度",必须诚实标出来)。
|
|
79
|
+
|
|
80
|
+
所以这里保留真正有用的部分——**64 格状态分布**(能看出数据集中在哪、
|
|
81
|
+
有哪些罕见组合)——而把约束换成三条**有领域含义的不变量**。
|
|
82
|
+
"""
|
|
83
|
+
sig = signature(rec)
|
|
84
|
+
bits = [(sig >> i) & 1 for i in range(6)]
|
|
85
|
+
# bits: [初=来源, 二=审核, 三=层, 四=类型, 五=置信, 上=时效]
|
|
86
|
+
src_user, confirmed, hot, stable, conf_hi, fresh = bits
|
|
87
|
+
|
|
88
|
+
issues = []
|
|
89
|
+
# ① 幻觉风险:AI 派生 + 已确认 + 低置信
|
|
90
|
+
if (not src_user) and confirmed and (not conf_hi):
|
|
91
|
+
issues.append("AI 派生却已确认且低置信(最易沉淀幻觉)")
|
|
92
|
+
# ② 高价值沉底:高置信 + 在淡忘/归档层
|
|
93
|
+
if conf_hi and not hot:
|
|
94
|
+
issues.append("高置信却在淡忘/归档层(可能被误淡忘,可 memory boost)")
|
|
95
|
+
# ③ 稳定事实过期:稳定类型 + 已过 review_by
|
|
96
|
+
if stable and not fresh:
|
|
97
|
+
issues.append("稳定事实已过期未复核(应 review-list 处理)")
|
|
98
|
+
|
|
99
|
+
return {"sig": sig, "bits": bits, "issues": issues, "clean": not issues}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def audit(limit: int = 2000) -> dict:
|
|
103
|
+
"""扫描记忆库,输出 64 格分布 + 不变量违规清单。**只读**。"""
|
|
104
|
+
try:
|
|
105
|
+
records = mem.load_all()
|
|
106
|
+
except Exception as exc: # noqa: BLE001
|
|
107
|
+
return {"error": f"读取记忆库失败:{exc}"}
|
|
108
|
+
records = [r for r in records if isinstance(r, dict) and r.get("id")][:limit]
|
|
109
|
+
|
|
110
|
+
cells = Counter()
|
|
111
|
+
buckets = {"hallucination": [], "sunk": [], "stale": []}
|
|
112
|
+
clean = 0
|
|
113
|
+
for r in records:
|
|
114
|
+
a = analyse(r)
|
|
115
|
+
cells[a["sig"]] += 1
|
|
116
|
+
if a["clean"]:
|
|
117
|
+
clean += 1
|
|
118
|
+
continue
|
|
119
|
+
brief = {"id": r.get("id"), "text": str(r.get("text") or "")[:60],
|
|
120
|
+
"layer": r.get("layer"), "source": r.get("source"),
|
|
121
|
+
"kind": r.get("kind"), "review": r.get("review"),
|
|
122
|
+
"importance": r.get("importance"), "sig": a["sig"]}
|
|
123
|
+
for msg in a["issues"]:
|
|
124
|
+
if msg.startswith("AI 派生"):
|
|
125
|
+
buckets["hallucination"].append(brief)
|
|
126
|
+
elif msg.startswith("高置信"):
|
|
127
|
+
buckets["sunk"].append(brief)
|
|
128
|
+
else:
|
|
129
|
+
buckets["stale"].append(brief)
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
"total": len(records),
|
|
133
|
+
"cells": dict(sorted(cells.items())),
|
|
134
|
+
"distinct_cells": len(cells),
|
|
135
|
+
"clean": clean,
|
|
136
|
+
"hallucination": len(buckets["hallucination"]),
|
|
137
|
+
"sunk": len(buckets["sunk"]),
|
|
138
|
+
"stale": len(buckets["stale"]),
|
|
139
|
+
"samples": {k: v[:8] for k, v in buckets.items()},
|
|
140
|
+
"note": ("字面「当位/得中/有应」在本数据上无区分度(实测 100%/75%/74%),"
|
|
141
|
+
"已改用三条领域不变量"),
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def render(rep: dict, top: int = 12) -> str:
|
|
146
|
+
"""人看的文本报告。"""
|
|
147
|
+
if rep.get("error"):
|
|
148
|
+
return f"[错误] {rep['error']}"
|
|
149
|
+
total = rep["total"]
|
|
150
|
+
lines = [f"六爻位体检:共 {total} 条记忆,落在 {rep['distinct_cells']}/64 格"
|
|
151
|
+
f"(结构干净 {rep['clean']} 条)", ""]
|
|
152
|
+
lines.append("领域不变量违规(这些是真问题,不是玄学):")
|
|
153
|
+
for key, label in (("hallucination", "① AI 派生+已确认+低置信(幻觉风险)"),
|
|
154
|
+
("sunk", "② 高置信却在淡忘/归档层(可能被误淡忘)"),
|
|
155
|
+
("stale", "③ 稳定事实已过期未复核")):
|
|
156
|
+
n = rep.get(key) or 0
|
|
157
|
+
pct = (n * 100 / total) if total else 0
|
|
158
|
+
lines.append(f" {label}:{n} 条({pct:.0f}%)")
|
|
159
|
+
|
|
160
|
+
cells = rep.get("cells") or {}
|
|
161
|
+
if cells:
|
|
162
|
+
lines.append("")
|
|
163
|
+
lines.append(f"最密集的 {top} 格(卦号 = 六位二进制,初爻为最低位):")
|
|
164
|
+
for sig, n in sorted(cells.items(), key=lambda kv: -kv[1])[:top]:
|
|
165
|
+
bits = "".join(str((sig >> i) & 1) for i in range(5, -1, -1))
|
|
166
|
+
lines.append(f" 卦 {sig:>2} [{bits}] {n} 条")
|
|
167
|
+
|
|
168
|
+
for key, title in (("hallucination", "幻觉风险样例"),
|
|
169
|
+
("sunk", "高置信沉底样例"),
|
|
170
|
+
("stale", "过期稳定事实样例")):
|
|
171
|
+
rows = (rep.get("samples") or {}).get(key) or []
|
|
172
|
+
if not rows:
|
|
173
|
+
continue
|
|
174
|
+
lines.append("")
|
|
175
|
+
lines.append(f"{title}:")
|
|
176
|
+
for b in rows[:6]:
|
|
177
|
+
lines.append(f" {b['id']} · 层={b['layer']} 源={b['source']} "
|
|
178
|
+
f"类={b['kind']} 审={b['review']} · {b['text']}")
|
|
179
|
+
if rep.get("note"):
|
|
180
|
+
lines.append("")
|
|
181
|
+
lines.append(f"注:{rep['note']}")
|
|
182
|
+
return "\n".join(lines)
|