lingshu-skill 5.28.0 → 5.30.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 +141 -0
- package/README.md +1 -1
- package/SKILL-lite.md +1 -1
- package/SKILL-tiny.md +1 -1
- package/SKILL.md +1 -1
- package/assets/panel.html +47 -6
- package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +328 -0
- package/package.json +1 -1
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +12 -12
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +141 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +47 -6
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +11 -2
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +29 -7
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +189 -57
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +60 -31
- package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +13 -7
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety_net.py +16 -6
- package/scripts/cli.py +11 -2
- package/scripts/dream.py +29 -7
- package/scripts/memory.py +189 -57
- package/scripts/panel_server.py +60 -31
- package/scripts/persona.py +13 -7
- package/scripts/safety_net.py +16 -6
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
<!doctype html>
|
|
2
2
|
<html lang="zh-CN"><head>
|
|
3
3
|
<meta charset="utf-8">
|
|
4
4
|
<meta name="lingshu-panel" content="1" />
|
|
@@ -785,6 +785,10 @@
|
|
|
785
785
|
<option value="300" selected>300 节点</option>
|
|
786
786
|
<option value="600">600 节点</option>
|
|
787
787
|
</select>
|
|
788
|
+
<label class="sub" style="display:flex;align-items:center;gap:5px;cursor:pointer;user-select:none"
|
|
789
|
+
title="只画有真实联想关系的记忆。孤立记忆不贡献结构,还会用斥力把可见部分挤成一坨——这是「点开就是个球」的主因之一。取消勾选可看全部">
|
|
790
|
+
<input type="checkbox" id="graph-hide-isolated" checked>只看有联想的
|
|
791
|
+
</label>
|
|
788
792
|
<button class="ghost" id="btn-graph-reset">重置视角</button>
|
|
789
793
|
<button class="ghost" id="btn-graph-refresh">刷新</button>
|
|
790
794
|
<button class="ghost" id="btn-graph-auto">自动联想</button>
|
|
@@ -1754,9 +1758,12 @@ function renderDailyCards(){
|
|
|
1754
1758
|
}
|
|
1755
1759
|
|
|
1756
1760
|
// ---------------- 记忆联想 · 3D 空间(零依赖力导向) ----------------
|
|
1761
|
+
// hideIsolated:默认只看"真有联想关系"的记忆。孤立记忆不是被丢了,是被收起——
|
|
1762
|
+
// 它们在图里既不贡献结构、又用斥力把可见部分挤成一坨(毛球的主要成因之一)。
|
|
1757
1763
|
const GRAPH = { data: null, pos: [], yaw: 0.6, pitch: -0.35, dist: 360,
|
|
1758
1764
|
focus: {x: 0, y: 0, z: 0}, target: {x: 0, y: 0, z: 0}, targetDist: 360,
|
|
1759
|
-
selected: null, hover: null, loaded: false, nbrs: null, anim: null,
|
|
1765
|
+
selected: null, hover: null, loaded: false, nbrs: null, anim: null,
|
|
1766
|
+
pathEdges: null, hideIsolated: true, stats: null, deg: null };
|
|
1760
1767
|
const LAYER_COLOR = { cortex: "#d9a441", hippo: "#5fa8a0", dust: "#5d646e", archive: "#8f92b8" };
|
|
1761
1768
|
// 颜色 = 重要程度(与图例一致):红=很重要 / 金=较重要 / 青=一般 / 灰=不重要;人格星核专属暖金
|
|
1762
1769
|
// 主题跟随:取 --node-* RGB 三元组(浅色主题在 enhance.css 里覆盖为深色版本)
|
|
@@ -1812,6 +1819,9 @@ function startPhysics(){
|
|
|
1812
1819
|
if (!nodes || !pos || !vel || !GRAPH.loaded){ GRAPH.phys = null; return; }
|
|
1813
1820
|
const n = Math.min(nodes.length, 260);
|
|
1814
1821
|
const kk = 24, rep = 5200;
|
|
1822
|
+
// 初始半径随节点数放大:节点多时还按 24 的"理想边长"铺,力不够撑开,
|
|
1823
|
+
// 一堆节点只能互相重叠着挤在中心——那是"一个球"的另一半原因。
|
|
1824
|
+
const ideal = kk * Math.max(1, Math.sqrt(nodes.length / 12));
|
|
1815
1825
|
// 防重叠:硬斥力只对"贴在一起"的节点生效,避免大图里互相穿透成一坨;>250 个节点跳过保性能
|
|
1816
1826
|
const overlap = nodes.length <= 250;
|
|
1817
1827
|
let energy = 0;
|
|
@@ -1834,7 +1844,13 @@ function startPhysics(){
|
|
|
1834
1844
|
(GRAPH.springs[i] || []).forEach(([j, w]) => {
|
|
1835
1845
|
const dx = pos[j].x - pos[i].x, dy = pos[j].y - pos[i].y, dz = pos[j].z - pos[i].z;
|
|
1836
1846
|
const d = Math.sqrt(dx*dx + dy*dy + dz*dz) + 1e-6;
|
|
1837
|
-
|
|
1847
|
+
// 弹簧力按两端度数归一(除以 sqrt(deg)):枢纽节点连了十几条边时,
|
|
1848
|
+
// 每条边都按原样拉会让整个子图被拽进一点、坍缩成球。
|
|
1849
|
+
// 归一后"每个连接的权重"相近,结构才铺得开——这是力导向做密度补偿的常规做法。
|
|
1850
|
+
const di = Math.max(1, (GRAPH.deg && GRAPH.deg[i]) || 1);
|
|
1851
|
+
const dj = Math.max(1, (GRAPH.deg && GRAPH.deg[j]) || 1);
|
|
1852
|
+
const norm = 1 / Math.sqrt(di * dj);
|
|
1853
|
+
const f = (d - ideal) * 0.03 * (0.5 + w * 0.5) * norm;
|
|
1838
1854
|
fx += dx / d * f; fy += dy / d * f; fz += dz / d * f;
|
|
1839
1855
|
});
|
|
1840
1856
|
vel[i].x = (vel[i].x + fx * 0.06) * 0.86;
|
|
@@ -1861,7 +1877,7 @@ function startPhysics(){
|
|
|
1861
1877
|
for (let i = n; i < nodes.length; i++){
|
|
1862
1878
|
const p = pos[i];
|
|
1863
1879
|
const d = Math.sqrt(p.x*p.x + p.y*p.y + p.z*p.z) + 1e-6;
|
|
1864
|
-
const f = (d -
|
|
1880
|
+
const f = (d - ideal) / d * -0.006; // 远的往回收、近的往外推,缓慢归位到 ideal 半径
|
|
1865
1881
|
vel[i].x = (vel[i].x + p.x * f) * 0.9;
|
|
1866
1882
|
vel[i].y = (vel[i].y + p.y * f) * 0.9;
|
|
1867
1883
|
vel[i].z = (vel[i].z + p.z * f) * 0.9;
|
|
@@ -1919,7 +1935,9 @@ async function loadGraph(limit){
|
|
|
1919
1935
|
GRAPH.focus = {x: 0, y: 0, z: 0}; GRAPH.target = {x: 0, y: 0, z: 0};
|
|
1920
1936
|
GRAPH.targetDist = 360;
|
|
1921
1937
|
try {
|
|
1922
|
-
GRAPH.data = await api("/api/graph?limit=" + (limit || 300)
|
|
1938
|
+
GRAPH.data = await api("/api/graph?limit=" + (limit || 300)
|
|
1939
|
+
+ (GRAPH.hideIsolated ? "&hide_isolated=1" : "&hide_isolated=0"));
|
|
1940
|
+
GRAPH.stats = GRAPH.data.stats || null;
|
|
1923
1941
|
// 节点从中心附近"绽放"散开(借鉴 Obsidian graph view 的加载动效)
|
|
1924
1942
|
GRAPH.vel = GRAPH.data.nodes.map(() => ({ x: 0, y: 0, z: 0 }));
|
|
1925
1943
|
GRAPH.pos = GRAPH.data.nodes.map(n => {
|
|
@@ -1938,6 +1956,14 @@ async function loadGraph(limit){
|
|
|
1938
1956
|
nodes.forEach((_, i) => GRAPH.nbrs.set(i, new Set()));
|
|
1939
1957
|
edges.forEach(e => { const a = idx.get(e.src), b = idx.get(e.dst);
|
|
1940
1958
|
if (a != null && b != null){ GRAPH.nbrs.get(a).add(b); GRAPH.nbrs.get(b).add(a); } });
|
|
1959
|
+
// 真实关联度数(不含人格星核):孤立节点判定、LOD 都用它
|
|
1960
|
+
GRAPH.deg = nodes.map(() => 0);
|
|
1961
|
+
edges.forEach(e => {
|
|
1962
|
+
if (e.src === "__persona__" || e.dst === "__persona__") return;
|
|
1963
|
+
const a = idx.get(e.src), b = idx.get(e.dst);
|
|
1964
|
+
if (a != null) GRAPH.deg[a]++;
|
|
1965
|
+
if (b != null) GRAPH.deg[b]++;
|
|
1966
|
+
});
|
|
1941
1967
|
GRAPH.loaded = true;
|
|
1942
1968
|
startPhysics(); // 持续物理模拟:节点像活物一样漂浮舒展
|
|
1943
1969
|
renderGraph();
|
|
@@ -1950,7 +1976,16 @@ async function loadGraph(limit){
|
|
|
1950
1976
|
} else {
|
|
1951
1977
|
if (loadTip) loadTip.classList.add("hidden");
|
|
1952
1978
|
const nAuto = edges.filter(e => e.auto).length;
|
|
1953
|
-
|
|
1979
|
+
const s = GRAPH.stats || {};
|
|
1980
|
+
// 把"为什么边这么少"讲明白:拦下了哪几个泛标签、收起了多少孤立记忆。
|
|
1981
|
+
// 不解释的话,用户会以为记忆丢了——这是比"球"更难查的误解。
|
|
1982
|
+
const gb = (s.generic_buckets || []).slice(0, 3)
|
|
1983
|
+
.map(b => `${b.name}(${b.count})`).join("、");
|
|
1984
|
+
const bits = [`${nodes.length} 条记忆`, `${edges.length} 条关联`];
|
|
1985
|
+
if (s.auto_candidates != null) bits.push(`候选 ${s.auto_candidates} → 保留 ${s.auto_kept}`);
|
|
1986
|
+
if (gb) bits.push(`泛标签已忽略:${gb}${s.generic_bucket_count > 3 ? " 等" + s.generic_bucket_count + "个" : ""}`);
|
|
1987
|
+
if (s.isolated_hidden) bits.push(`收起 ${s.isolated_hidden} 条无联想的记忆(可勾选显示)`);
|
|
1988
|
+
$("graph-hint").textContent = bits.join(" · ") + " · 点节点:以它为中心 + 激活相邻记忆";
|
|
1954
1989
|
$("graph-stat").textContent = `${nodes.length} 节点 · ${edges.length} 关联边 · 手动 ${edges.length - nAuto} / 自动 ${nAuto}`;
|
|
1955
1990
|
}
|
|
1956
1991
|
} catch (e) {
|
|
@@ -3843,6 +3878,12 @@ if (btnGa) btnGa.addEventListener("click", async () => {
|
|
|
3843
3878
|
} catch (e) { console.error("自动联想:", e); toast(e.message, true); }
|
|
3844
3879
|
});
|
|
3845
3880
|
$("graph-limit").addEventListener("change", () => loadGraph(Number($("graph-limit").value || 300)));
|
|
3881
|
+
// 「只看有联想的」:切换要重新拉图——孤立记忆必须整批退出力学,只在前端隐藏没用,
|
|
3882
|
+
// 它们看不见的斥力照样会把可见部分挤成一坨。
|
|
3883
|
+
$("graph-hide-isolated") && $("graph-hide-isolated").addEventListener("change", e => {
|
|
3884
|
+
GRAPH.hideIsolated = !!e.target.checked;
|
|
3885
|
+
loadGraph(Number($("graph-limit").value || 300));
|
|
3886
|
+
});
|
|
3846
3887
|
// 图内搜索:输入即定位(300ms 防抖),回车看下一个命中
|
|
3847
3888
|
let _gsTimer = null;
|
|
3848
3889
|
$("graph-search").addEventListener("input", e => {
|
|
@@ -697,14 +697,23 @@ def cmd_relink(limit: int = 0, min_score: float = 1.0, max_links: int = 5) -> in
|
|
|
697
697
|
"""全库联想建链:给历史记忆按词面相似度补挂 links(双向)。
|
|
698
698
|
|
|
699
699
|
与 cold/archive 分层无关——建链是给"还在热查询集里的记忆"补关联网。
|
|
700
|
-
|
|
701
|
-
|
|
700
|
+
|
|
701
|
+
**必须持写锁**:load_all → 改 links → save_all 是整库快照回写,锁外做会被
|
|
702
|
+
remember / dream / 面板的并发写整片覆盖。本函数早期版本漏了锁,docstring 却
|
|
703
|
+
写着"整体一把写锁"——注释骗过了历次审计(实测 61 行里 0 处 `_locked`)。
|
|
702
704
|
"""
|
|
703
705
|
import memory as _mem
|
|
704
706
|
if READONLY:
|
|
705
707
|
print("[只读] 记忆库当前不可写,relink 需要写盘。", file=sys.stderr)
|
|
706
708
|
return 1
|
|
707
709
|
ensure_home()
|
|
710
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
711
|
+
return _relink_locked(limit, min_score, max_links)
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
def _relink_locked(limit: int, min_score: float, max_links: int) -> int:
|
|
715
|
+
"""真正的遍历。**调用方必须已持有 hippocampus 写锁。**"""
|
|
716
|
+
import memory as _mem
|
|
708
717
|
# 记忆上万后全库 jaccard 两两比对是 O(n²),但与 recall/dream 现有全量扫描
|
|
709
718
|
# 同量级;先按创建时间倒序截 limit,保证"最近的最先补到"。
|
|
710
719
|
rows = _mem.load_all()
|
|
@@ -237,9 +237,14 @@ def cluster_memories(records: list, max_clusters: int = 6, include_ids: set | No
|
|
|
237
237
|
def _dream_snapshot() -> str:
|
|
238
238
|
"""做梦改库前的自动快照(借鉴 sage-mem:整理前强制建回滚点)。
|
|
239
239
|
|
|
240
|
-
|
|
241
|
-
轻量得多;存在 ~/.brain-memory/dream-snapshots/ 下,保留最近 10 份。
|
|
240
|
+
存 ~/.brain-memory/dream-snapshots/ 下,保留最近 10 份。
|
|
242
241
|
失败返回 "" 并记事件日志;调用方(dream)fail-closed:拿不到快照就拒绝整理。
|
|
242
|
+
|
|
243
|
+
**core_files 必须覆盖 `save_all` 真正会写的全部文件**。`save_all` 写的是
|
|
244
|
+
("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl"),而 dream 恰好会 promote 到
|
|
245
|
+
cortex、淡忘到 dust——早期版本只备份 hippocampus 一层,于是 restore 之后
|
|
246
|
+
cortex/dust 保持新状态、hippocampus 回到旧状态,同一条记忆同时出现在两处,
|
|
247
|
+
库处于半新半旧状态,而报告却写着"可用 restore 还原"(审计 dream.py:253)。
|
|
243
248
|
"""
|
|
244
249
|
snap_dir = HOME / "dream-snapshots"
|
|
245
250
|
try:
|
|
@@ -250,19 +255,23 @@ def _dream_snapshot() -> str:
|
|
|
250
255
|
while path.exists():
|
|
251
256
|
k += 1
|
|
252
257
|
path = snap_dir / f"dream-snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{k}.zip"
|
|
253
|
-
|
|
258
|
+
# 三层记忆全都要(hippo/cortex/dust 是 save_all 的写入目标,缺一层回滚点就是残的)
|
|
259
|
+
core_files = ["hippocampus.jsonl", "cortex.jsonl", "dust.jsonl",
|
|
260
|
+
"archive.jsonl", "assoc.jsonl",
|
|
254
261
|
"knowledge.jsonl", "persona.json", "dream_state.json"]
|
|
255
262
|
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as zf:
|
|
256
263
|
for name in core_files:
|
|
257
264
|
f = HOME / name
|
|
258
265
|
if f.is_file():
|
|
259
266
|
zf.write(f, name)
|
|
260
|
-
# 保留最近 10
|
|
267
|
+
# 保留最近 10 份;旧的移入 .pruned/ 而不是删除(用户规矩:要删的进垃圾桶/归档)
|
|
268
|
+
pruned = snap_dir / ".pruned"
|
|
261
269
|
snaps = sorted(snap_dir.glob("dream-snap_*.zip"))
|
|
262
270
|
for p in snaps[:-10]:
|
|
263
271
|
try:
|
|
264
|
-
|
|
265
|
-
|
|
272
|
+
pruned.mkdir(parents=True, exist_ok=True)
|
|
273
|
+
shutil.move(str(p), str(pruned / p.name))
|
|
274
|
+
except (OSError, shutil.Error):
|
|
266
275
|
pass
|
|
267
276
|
return str(path)
|
|
268
277
|
except Exception as exc:
|
|
@@ -732,6 +741,7 @@ def dream(trigger: str = "manual", dry_run: bool = False) -> dict:
|
|
|
732
741
|
# 新任务也可能被晾着(借鉴 Mnemosyne 幂等键防重复情节、租约验证)。
|
|
733
742
|
# 未超时 → 沿用旧任务;超时太久(孤儿)→ 归档后接新任务。
|
|
734
743
|
old = load_dream_pending()
|
|
744
|
+
keep_old = False
|
|
735
745
|
if old and old.get("task_id"):
|
|
736
746
|
age = now - _num(old.get("created"), now)
|
|
737
747
|
if age < _DREAM_ORPHAN_TTL:
|
|
@@ -739,6 +749,7 @@ def dream(trigger: str = "manual", dry_run: bool = False) -> dict:
|
|
|
739
749
|
task_id = old["task_id"]
|
|
740
750
|
report["task_id"] = task_id
|
|
741
751
|
report["pending_kept"] = True
|
|
752
|
+
keep_old = True
|
|
742
753
|
log_event("dream", f"已有未整理的梦(task_id={old['task_id']},"
|
|
743
754
|
f"{age / 3600:.1f}h 前触发),本次不重复生成新任务", level="warn")
|
|
744
755
|
else:
|
|
@@ -751,7 +762,18 @@ def dream(trigger: str = "manual", dry_run: bool = False) -> dict:
|
|
|
751
762
|
f"悬置 {age / 3600:.1f}h > {_DREAM_ORPHAN_TTL / 3600:.0f}h),"
|
|
752
763
|
"生成新任务", level="warn")
|
|
753
764
|
report["orphaned_task_id"] = old["task_id"]
|
|
754
|
-
|
|
765
|
+
# ⚠ 两处必须一起改(原先只改了一半,实测导致自动做梦必然失败):
|
|
766
|
+
# ① 沿用旧任务时**绝不能写盘**——new_pending 装的是本次的新簇,
|
|
767
|
+
# 写下去等于用新簇顶掉旧 task_id 的任务,旧簇静默丢失;
|
|
768
|
+
# ② 真写盘时,pending 里的 task_id 必须是**最终** task_id。
|
|
769
|
+
# new_pending 在 L709 用新 id 构造,若期间 task_id 被改写(孤儿归档
|
|
770
|
+
# 分支不会改,但任何未来的改写都会),两者就会错位——
|
|
771
|
+
# 而 `dream --auto` 拿 report["task_id"] 去 apply,盘上却是另一个 id
|
|
772
|
+
# → 稳定报"任务对不上"。这里显式同步,不依赖构造顺序。
|
|
773
|
+
if not keep_old:
|
|
774
|
+
new_pending["task_id"] = task_id
|
|
775
|
+
new_pending["apply_schema"]["task_id"] = task_id
|
|
776
|
+
atomic_json(HOME / "dreams" / "pending.json", new_pending)
|
|
755
777
|
# 没有可整理的碎片就不写 pending.json,免得让 AI 对着一份空任务空转
|
|
756
778
|
write_dream_report(report)
|
|
757
779
|
st = load_dream_state()
|
|
@@ -678,17 +678,38 @@ def verify_integrity() -> dict:
|
|
|
678
678
|
|
|
679
679
|
|
|
680
680
|
def load_all() -> list:
|
|
681
|
-
"""三层热层合并;缺 id
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
681
|
+
"""三层热层合并;缺 id 的 dict 记录**补一个稳定 id**,而不是丢弃。
|
|
682
|
+
|
|
683
|
+
为什么不丢:`_locked_save_all` 专门保留 `no_id`、`dream.py:182` 也明确承诺
|
|
684
|
+
"这些记录会原样保留在库,不会被 save_all 丢掉"。但早期版本在这里直接略过
|
|
685
|
+
它们 → 任何一次 `save_all(load_all())` 就把它们永远抹掉
|
|
686
|
+
(审计 memory.py:686,承诺与实际相反)。
|
|
687
|
+
|
|
688
|
+
现在按内容哈希补 id:同一条记录重复 load 得到同一个 id(幂等),于是它能
|
|
689
|
+
安全穿过 read-modify-write 而不蒸发,也不会每次 load 都长出重复副本。
|
|
690
|
+
仍然跳过非 dict 的记录(无法附加字段,也读不出 id)。
|
|
691
|
+
"""
|
|
692
|
+
raw = (read_jsonl(HOME / "hippocampus.jsonl")
|
|
693
|
+
+ read_jsonl(HOME / "cortex.jsonl")
|
|
694
|
+
+ read_jsonl(HOME / "dust.jsonl"))
|
|
695
|
+
good, fixed, bad = [], 0, 0
|
|
685
696
|
for r in raw:
|
|
686
|
-
if isinstance(r, dict)
|
|
687
|
-
good.append(r)
|
|
688
|
-
else:
|
|
697
|
+
if not isinstance(r, dict):
|
|
689
698
|
bad += 1
|
|
699
|
+
continue
|
|
700
|
+
if not r.get("id"):
|
|
701
|
+
r = dict(r)
|
|
702
|
+
seed = json.dumps({k: r.get(k) for k in
|
|
703
|
+
("text", "kind", "created", "layer", "gist")},
|
|
704
|
+
ensure_ascii=False, sort_keys=True, default=str)
|
|
705
|
+
r["id"] = "m_" + hashlib.sha1(seed.encode("utf-8")).hexdigest()[:12]
|
|
706
|
+
fixed += 1
|
|
707
|
+
good.append(r)
|
|
708
|
+
if fixed:
|
|
709
|
+
log_event("load", f"load_all 给 {fixed} 条缺 id 的记录补了内容哈希 id"
|
|
710
|
+
"(不再丢弃,避免 save_all 抹掉它们)", level="warning")
|
|
690
711
|
if bad:
|
|
691
|
-
log_event("load", f"load_all 跳过 {bad}
|
|
712
|
+
log_event("load", f"load_all 跳过 {bad} 条非 dict 畸形记录", level="warning")
|
|
692
713
|
return good
|
|
693
714
|
|
|
694
715
|
|
|
@@ -917,44 +938,54 @@ def save_all(records: list) -> None:
|
|
|
917
938
|
targets = [("hippocampus.jsonl", groups["hippo"]),
|
|
918
939
|
("cortex.jsonl", groups["cortex"]),
|
|
919
940
|
("dust.jsonl", groups["dust"])]
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
for tmp, _ in staged:
|
|
932
|
-
try:
|
|
933
|
-
os.unlink(tmp)
|
|
934
|
-
except OSError:
|
|
935
|
-
pass
|
|
936
|
-
raise
|
|
937
|
-
for tmp, p in staged:
|
|
938
|
-
_replace_retry(tmp, p)
|
|
939
|
-
|
|
940
|
-
# 写后校验:JSON 可解析 + 末行完整 + 层级自洽。不通过就回滚并抛错
|
|
941
|
-
# (回滚成功时数据是"旧的一致状态",比留着一份写坏的新数据安全)。
|
|
942
|
-
if _snap and _sn is not None:
|
|
941
|
+
# ★ 三层锁必须**一起持**(审计 core.py:2044):`_patch_memory_fields` 是按
|
|
942
|
+
# 「该层文件」加锁的(改 cortex 记录就持 cortex.jsonl.lock),而 save_all 写的是
|
|
943
|
+
# 三层全量——如果这里只持 hippocampus 锁,它随时能穿过 patch 正在进行的 cortex
|
|
944
|
+
# 写回,两边各自 read-modify-write,后写者把对方的 `review_by_confirmed` 等字段
|
|
945
|
+
# 抹掉。同一文件存在两套互斥口径,等于没有互斥。
|
|
946
|
+
# `_locked` 可重入(同线程已持锁直接 yield),所以调用方已经 `with _locked(...)`
|
|
947
|
+
# 时也不会死锁;固定 hippocampus→cortex→dust 的顺序避免跨线程循环等待。
|
|
948
|
+
with _locked(HOME / "hippocampus.jsonl"), \
|
|
949
|
+
_locked(HOME / "cortex.jsonl"), \
|
|
950
|
+
_locked(HOME / "dust.jsonl"):
|
|
951
|
+
staged = []
|
|
943
952
|
try:
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
953
|
+
for fname, rows in targets:
|
|
954
|
+
p = HOME / fname
|
|
955
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
956
|
+
tmp = _tmp_path(p)
|
|
957
|
+
with open(tmp, "w", encoding="utf-8", newline="\n") as f:
|
|
958
|
+
for r in rows:
|
|
959
|
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
|
960
|
+
staged.append((tmp, p))
|
|
961
|
+
except Exception:
|
|
962
|
+
for tmp, _ in staged:
|
|
963
|
+
try:
|
|
964
|
+
os.unlink(tmp)
|
|
965
|
+
except OSError:
|
|
966
|
+
pass
|
|
951
967
|
raise
|
|
952
|
-
|
|
968
|
+
for tmp, p in staged:
|
|
969
|
+
_replace_retry(tmp, p)
|
|
970
|
+
|
|
971
|
+
# 写后校验:JSON 可解析 + 末行完整 + 层级自洽。不通过就回滚并抛错
|
|
972
|
+
# (回滚成功时数据是"旧的一致状态",比留着一份写坏的新数据安全)。
|
|
973
|
+
if _snap and _sn is not None:
|
|
953
974
|
try:
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
975
|
+
_v = _sn.verify(("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl"))
|
|
976
|
+
if not _v.get("ok"):
|
|
977
|
+
_sn.restore(_snap)
|
|
978
|
+
raise RuntimeError(
|
|
979
|
+
"save_all 写后校验失败,已从快照自动回滚:"
|
|
980
|
+
+ ";".join((_v.get("issues") or [])[:3]))
|
|
981
|
+
except RuntimeError:
|
|
982
|
+
raise
|
|
983
|
+
except Exception as exc: # noqa: BLE001
|
|
984
|
+
try:
|
|
985
|
+
log_event("safety", f"写后校验本身出错(已跳过,数据未动):{exc}",
|
|
986
|
+
level="warn")
|
|
987
|
+
except Exception:
|
|
988
|
+
pass
|
|
958
989
|
|
|
959
990
|
|
|
960
991
|
# ---------------------------------------------------------------- 记忆记录
|
|
@@ -4161,17 +4192,43 @@ def assoc_auto(weight: float = 0.8, dry_run: bool = False) -> dict:
|
|
|
4161
4192
|
"pairs": added[:20]}
|
|
4162
4193
|
|
|
4163
4194
|
|
|
4164
|
-
|
|
4195
|
+
# 联想图的边密度闸门。为什么需要(实测 2026-11-27):本机 165 条记忆、
|
|
4196
|
+
# 自动联想产生 **9278 条边**(密度 65%,完全图才 13530),前端力导向必然坍缩成一个毛球
|
|
4197
|
+
# 并且卡死。根因不是"记忆多",而是 **两个存档流程标签**:
|
|
4198
|
+
# 「封存」挂在 135 条记忆上(80.4%)→ 单这一个桶就是 135×134/2 = 9045 对
|
|
4199
|
+
# 「即记」挂在 103 条(61.3%) → 再 5253 对
|
|
4200
|
+
# 这类标签描述的是**存储动作**,不是内容关联,不该被当成"相关"。
|
|
4201
|
+
#
|
|
4202
|
+
# 处理分两道(都是数据驱动、不写死具体标签名,换库/换语言也成立):
|
|
4203
|
+
# 1. 泛标签闸:某个标签/实体覆盖了超过 GRAPH_GENERIC_RATIO 的节点 → 视为元数据,
|
|
4204
|
+
# 不参与两两配对。实测阈值 15% 是自然断点:封存/即记/会话存档 全部被拦下,
|
|
4205
|
+
# 边从 9278 → 68(-99.3%),剩下的结构是真实相关的。
|
|
4206
|
+
# 2. 度数闸:单节点自动边只留最强的 GRAPH_MAX_DEGREE 条(Gephi 的 Degree Filter
|
|
4207
|
+
# 等价物;k-core 掉到 1 时仍能保证稀疏)。
|
|
4208
|
+
GRAPH_GENERIC_RATIO = 0.15 # 覆盖超过 15% 节点的标签/实体 = 元数据,不参与联想
|
|
4209
|
+
GRAPH_MAX_DEGREE = 6 # 单节点最多保留的自动联想边数
|
|
4210
|
+
|
|
4211
|
+
|
|
4212
|
+
def assoc_graph(limit: int = 300, generic_ratio: float | None = None,
|
|
4213
|
+
max_degree: int | None = None, hide_isolated: bool = False) -> dict:
|
|
4165
4214
|
"""联想图谱数据:面板 3D 空间用的节点与关联边。
|
|
4166
4215
|
|
|
4167
|
-
v2.32
|
|
4216
|
+
v2.32 起三处升级(均为自动,无需手动连线):
|
|
4168
4217
|
* 人格中心:虚构一个 __persona__ 中心节点,与所有非淡忘记忆自动连边——
|
|
4169
4218
|
图谱以人格为星核呈放射状,一眼看出"哪些记忆离我最近"。
|
|
4170
4219
|
* 自动联想:共享实体/标签的记忆对之间补自动边(复用 assoc_auto 的
|
|
4171
4220
|
计划逻辑但只读不落盘),图谱显示的关联远多于手工 link 的存量边。
|
|
4221
|
+
* **边密度闸门**(v3.48):泛标签(覆盖 >15% 节点,如「封存」「即记」)
|
|
4222
|
+
不参与配对;单节点自动边只留最强 6 条。没有这道闸,几百条记忆就会把
|
|
4223
|
+
图连成 9000+ 边的毛球,既看不出结构也画不动。
|
|
4172
4224
|
|
|
4173
4225
|
节点上限 limit(默认 300,太多画不动);边只保留两端都在图里的。
|
|
4226
|
+
返回里的 `pruned`/`generic_buckets` 是给面板显示"为什么边这么少"用的,
|
|
4227
|
+
不隐藏事实:关掉闸门会是什么规模,一眼可见。
|
|
4174
4228
|
"""
|
|
4229
|
+
ratio = GRAPH_GENERIC_RATIO if generic_ratio is None else float(generic_ratio)
|
|
4230
|
+
maxdeg = GRAPH_MAX_DEGREE if max_degree is None else int(max_degree)
|
|
4231
|
+
|
|
4175
4232
|
records = [m for m in load_all() if m.get("layer") != "dust"]
|
|
4176
4233
|
records.sort(key=lambda m: (_num(m.get("importance"), 0.5),
|
|
4177
4234
|
float(retention(m))), reverse=True)
|
|
@@ -4183,8 +4240,9 @@ def assoc_graph(limit: int = 300) -> dict:
|
|
|
4183
4240
|
edges.append({"src": r["src"], "dst": r["dst"],
|
|
4184
4241
|
"relation": r.get("relation", "相关"),
|
|
4185
4242
|
"weight": float(r.get("weight", 1))})
|
|
4243
|
+
manual_edges = len(edges) # 手工连线永远保留,不受下面两道闸影响
|
|
4186
4244
|
seen_edges = {(e["src"], e["dst"]) for e in edges}
|
|
4187
|
-
|
|
4245
|
+
|
|
4188
4246
|
# 倒排索引:实体/标签 -> 记忆 id 集合。两两组合只发生在同一桶内,
|
|
4189
4247
|
# 复杂度从 O(P×(E+T)) 降到 Σ(桶内两两),记忆多了不再卡面板。
|
|
4190
4248
|
by_ent, by_tag = {}, {}
|
|
@@ -4193,30 +4251,90 @@ def assoc_graph(limit: int = 300) -> dict:
|
|
|
4193
4251
|
by_ent.setdefault(e, set()).add(m["id"])
|
|
4194
4252
|
for t in m.get("tags", []):
|
|
4195
4253
|
by_tag.setdefault(t, set()).add(m["id"])
|
|
4196
|
-
|
|
4197
|
-
|
|
4198
|
-
|
|
4254
|
+
|
|
4255
|
+
n_nodes = max(1, len(nodes))
|
|
4256
|
+
generic_buckets = [] # 被判为元数据的标签/实体(附覆盖数,便于排错)
|
|
4257
|
+
buckets = [] # (bucket_key, id_set)
|
|
4258
|
+
for kind, table in (("标签", by_tag), ("实体", by_ent)):
|
|
4259
|
+
for name, bucket in table.items():
|
|
4260
|
+
if len(bucket) < 2:
|
|
4261
|
+
continue
|
|
4262
|
+
if len(bucket) / n_nodes > ratio:
|
|
4263
|
+
generic_buckets.append({"kind": kind, "name": name,
|
|
4264
|
+
"count": len(bucket),
|
|
4265
|
+
"ratio": round(len(bucket) / n_nodes, 3)})
|
|
4266
|
+
continue
|
|
4267
|
+
buckets.append(bucket)
|
|
4268
|
+
generic_buckets.sort(key=lambda x: -x["count"])
|
|
4269
|
+
|
|
4270
|
+
# 每条候选边的权重 = 两端共享的桶数(共享的标签/实体越多越相关)
|
|
4271
|
+
pair_weight: dict[tuple, int] = {}
|
|
4272
|
+
owner: dict[str, set] = {} # id -> 命中的桶下标集合(算共享数用)
|
|
4273
|
+
for bi, bucket in enumerate(buckets):
|
|
4199
4274
|
bl = sorted(bucket)
|
|
4200
4275
|
for i, a in enumerate(bl):
|
|
4276
|
+
owner.setdefault(a, set()).add(bi)
|
|
4201
4277
|
for b in bl[i + 1:]:
|
|
4278
|
+
owner.setdefault(b, set()).add(bi)
|
|
4202
4279
|
key = (a, b) if a < b else (b, a)
|
|
4203
|
-
if key
|
|
4204
|
-
|
|
4205
|
-
|
|
4206
|
-
|
|
4207
|
-
|
|
4280
|
+
if key in seen_edges:
|
|
4281
|
+
continue
|
|
4282
|
+
pair_weight[key] = pair_weight.get(key, 0) + 1
|
|
4283
|
+
|
|
4284
|
+
# 度数闸:优先保留"共享桶多(更相关)+ 两端总度数低(更稀缺)"的边,
|
|
4285
|
+
# 贪心填到每个节点 maxdeg 为止——避免大节点吃掉所有名额。
|
|
4286
|
+
degree_seen: dict[str, int] = {}
|
|
4287
|
+
kept = []
|
|
4288
|
+
for (a, b), w in sorted(pair_weight.items(),
|
|
4289
|
+
key=lambda kv: (-kv[1], kv[0])):
|
|
4290
|
+
if maxdeg and (degree_seen.get(a, 0) >= maxdeg or degree_seen.get(b, 0) >= maxdeg):
|
|
4291
|
+
continue
|
|
4292
|
+
kept.append((a, b, w))
|
|
4293
|
+
degree_seen[a] = degree_seen.get(a, 0) + 1
|
|
4294
|
+
degree_seen[b] = degree_seen.get(b, 0) + 1
|
|
4295
|
+
for a, b, w in kept:
|
|
4208
4296
|
edges.append({"src": a, "dst": b, "relation": "相关",
|
|
4209
|
-
"weight": min(3.0, 0.8 * w),
|
|
4210
|
-
|
|
4297
|
+
"weight": min(3.0, 0.8 * max(1, w)),
|
|
4298
|
+
"auto": True, "shared": w})
|
|
4299
|
+
|
|
4300
|
+
# 人格中心节点:星核。**不连全部记忆**——那是另一条"必成毛球"的路:
|
|
4301
|
+
# 300 个节点各连一根,中心点的视觉权重会盖过一切,且弹簧把全图拽向一点。
|
|
4302
|
+
# 改为只连"重要度高 + 自身已出现在联想里"的那一小撮(最多 GRAPH_MAX_DEGREE×2),
|
|
4303
|
+
# 星核仍然是视觉中心,但不再主导力学。
|
|
4211
4304
|
persona_id = "__persona__"
|
|
4212
4305
|
import persona as _persona_mod # 延迟导入避免循环依赖
|
|
4213
4306
|
p = _persona_mod.load_persona()
|
|
4307
|
+
|
|
4308
|
+
# 孤立记忆闸(v3.48):没有真实关联的记忆只留一个点,但它的**斥力还在**——
|
|
4309
|
+
# 137 个孤立节点会把 32 个有结构的节点挤成一坨,视觉上还是那个毛球。
|
|
4310
|
+
# 所以默认把它们整批排除出图(前端可一键「显示全部」重新拉)。
|
|
4311
|
+
isolated_hidden = 0
|
|
4312
|
+
if hide_isolated:
|
|
4313
|
+
linked = set()
|
|
4314
|
+
for a, b, _w in kept:
|
|
4315
|
+
linked.add(a)
|
|
4316
|
+
linked.add(b)
|
|
4317
|
+
for e in edges:
|
|
4318
|
+
if not e.get("auto"):
|
|
4319
|
+
linked.add(e["src"])
|
|
4320
|
+
linked.add(e["dst"])
|
|
4321
|
+
before = len(nodes)
|
|
4322
|
+
nodes = [m for m in nodes if m["id"] in linked]
|
|
4323
|
+
isolated_hidden = before - len(nodes)
|
|
4324
|
+
|
|
4214
4325
|
nodes.insert(0, {"id": persona_id, "gist": "人格 · " + (p.get("name") or "砚"),
|
|
4215
4326
|
"kind": "persona", "layer": "persona",
|
|
4216
4327
|
"importance": 1.0, "emotion": "", "recency": 1.0})
|
|
4217
|
-
|
|
4328
|
+
hub_cap = max(4, maxdeg * 2) if maxdeg else len(nodes)
|
|
4329
|
+
hub_ids = {i for pair in kept for i in pair[:2]}
|
|
4330
|
+
hub_targets = sorted(nodes[1:], key=lambda m: -_num(m.get("importance"), 0.5))
|
|
4331
|
+
# 优先连"已经在联想网里"的高重要度记忆,补足到 hub_cap
|
|
4332
|
+
hub_targets.sort(key=lambda m: (m["id"] not in hub_ids, -_num(m.get("importance"), 0.5)))
|
|
4333
|
+
for m in hub_targets[:hub_cap]:
|
|
4218
4334
|
edges.append({"src": persona_id, "dst": m["id"], "relation": "自我",
|
|
4219
4335
|
"weight": 0.4 + _num(m.get("importance"), 0.5), "auto": True})
|
|
4336
|
+
kept_ids = {n["id"] for n in nodes}
|
|
4337
|
+
edges = [e for e in edges if e["src"] in kept_ids and e["dst"] in kept_ids]
|
|
4220
4338
|
return {
|
|
4221
4339
|
"nodes": [{"id": m["id"], "gist": m.get("gist") or heuristic_gist(m.get("text", "")),
|
|
4222
4340
|
"kind": m.get("kind", ""), "layer": m.get("layer", "hippo"),
|
|
@@ -4226,6 +4344,20 @@ def assoc_graph(limit: int = 300) -> dict:
|
|
|
4226
4344
|
"edges": edges,
|
|
4227
4345
|
"connected": len({e["src"] for e in edges} - {persona_id}
|
|
4228
4346
|
| {e["dst"] for e in edges} - {persona_id}),
|
|
4347
|
+
# 闸门透明化:面板要能说"为什么这么少",而不是让人以为丢数据了
|
|
4348
|
+
"stats": {
|
|
4349
|
+
"nodes": len(nodes),
|
|
4350
|
+
"edges": len(edges),
|
|
4351
|
+
"manual": manual_edges,
|
|
4352
|
+
"auto_candidates": len(pair_weight),
|
|
4353
|
+
"auto_kept": len(kept),
|
|
4354
|
+
"generic_ratio": ratio,
|
|
4355
|
+
"max_degree": maxdeg,
|
|
4356
|
+
"generic_buckets": generic_buckets[:12],
|
|
4357
|
+
"generic_bucket_count": len(generic_buckets),
|
|
4358
|
+
"hide_isolated": bool(hide_isolated),
|
|
4359
|
+
"isolated_hidden": isolated_hidden,
|
|
4360
|
+
},
|
|
4229
4361
|
}
|
|
4230
4362
|
|
|
4231
4363
|
# ---------------------------------------------------------------- 上下文注入
|