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
|
@@ -551,6 +551,19 @@ def _migrate_home(target_raw: str) -> dict:
|
|
|
551
551
|
raise ValueError("目标目录不能为空")
|
|
552
552
|
if target == brain.HOME.resolve():
|
|
553
553
|
raise ValueError("目标目录与当前数据目录相同")
|
|
554
|
+
# ★ 目标不能落在数据目录**内部**(审计 panel_server.py:559):
|
|
555
|
+
# `copytree(HOME, target)` 时目标若在 HOME 底下,copytree 边复制边把刚创建的
|
|
556
|
+
# 目标目录自己也扫进去 → 递归膨胀,或中途 OSError 留下一份半截副本,
|
|
557
|
+
# 而且此时指针文件还没写,用户会得到一个"看起来迁好了、其实不完整"的目录。
|
|
558
|
+
# CLI 的 `home move` 有这道检查(relative_to 直接拒),这里漏了。
|
|
559
|
+
try:
|
|
560
|
+
target.relative_to(brain.HOME.resolve())
|
|
561
|
+
except ValueError:
|
|
562
|
+
pass # 不在内部,正常
|
|
563
|
+
else:
|
|
564
|
+
raise ValueError(
|
|
565
|
+
"目标目录在数据目录内部——复制时会把目标自己也扫进去(递归膨胀)。"
|
|
566
|
+
f"请选数据目录之外的路径(当前数据目录:{brain.HOME})")
|
|
554
567
|
if target.exists() and any(target.iterdir()):
|
|
555
568
|
raise ValueError("目标目录已存在且非空——请选一个空目录(或先手动清理)")
|
|
556
569
|
# 计划写指针的位置必须可写:指针文件永远在默认位置 ~/.brain-memory/ 下
|
|
@@ -909,7 +922,26 @@ class Handler(BaseHTTPRequestHandler):
|
|
|
909
922
|
return
|
|
910
923
|
if path == "/api/graph":
|
|
911
924
|
limit = _int_param(url, "limit", 300, 10, 800)
|
|
912
|
-
|
|
925
|
+
# v3.48 联想图密度闸门:把"元数据标签不算关联""单节点边数上限"
|
|
926
|
+
# "孤立记忆是否入图"三个开关暴露出来,面板可调、也可用它自查边爆炸。
|
|
927
|
+
qs = parse_qs(url.query)
|
|
928
|
+
def _flag(name: str, default: bool) -> bool:
|
|
929
|
+
v = (qs.get(name) or [""])[0].strip().lower()
|
|
930
|
+
if not v:
|
|
931
|
+
return default
|
|
932
|
+
return v not in ("0", "false", "no", "off")
|
|
933
|
+
def _num(name: str, default):
|
|
934
|
+
v = (qs.get(name) or [""])[0].strip()
|
|
935
|
+
try:
|
|
936
|
+
return float(v)
|
|
937
|
+
except (TypeError, ValueError):
|
|
938
|
+
return default
|
|
939
|
+
self._json(brain.assoc_graph(
|
|
940
|
+
limit,
|
|
941
|
+
generic_ratio=_num("generic_ratio", None),
|
|
942
|
+
max_degree=_num("max_degree", None),
|
|
943
|
+
hide_isolated=_flag("hide_isolated", True),
|
|
944
|
+
))
|
|
913
945
|
return
|
|
914
946
|
if path == "/api/diagnostics":
|
|
915
947
|
# 自诊断:死链 / 冲突未裁决 / 数据膨胀 / 淡忘可逆状态 / 来源归属完整率
|
|
@@ -2578,6 +2610,28 @@ def ollama_status() -> dict:
|
|
|
2578
2610
|
return st
|
|
2579
2611
|
|
|
2580
2612
|
|
|
2613
|
+
def _ollama_write_embed_cfg() -> None:
|
|
2614
|
+
"""在 `config.json` 写锁内把 Ollama 的 embed 配置写进去。
|
|
2615
|
+
|
|
2616
|
+
审计 panel_server.py:2599:Ollama 的 enable / setup / install / auto_probe
|
|
2617
|
+
原来都是 `brain.load_config()` → 改 `embed` → `brain.atomic_json(config.json)`
|
|
2618
|
+
**整份回写**,绕开了 `config_set` / `_set_cfg_path` 用的
|
|
2619
|
+
`_locked(HOME / "config.json")`。与设置页保存或 CLI `config set` 并发时,
|
|
2620
|
+
后写者会把对方刚设的 token / 阈值 / 档位静默覆盖掉——用户改完设置发现又变回去,
|
|
2621
|
+
却找不到原因。
|
|
2622
|
+
|
|
2623
|
+
统一走这里:读-改-写在同一个锁内完成,和 `_set_cfg_path` 同一互斥口径。
|
|
2624
|
+
`_locked` 可重入,所以外层若已持锁也不会死锁。
|
|
2625
|
+
"""
|
|
2626
|
+
with brain._locked(brain.HOME / "config.json"):
|
|
2627
|
+
cfg = brain.load_config()
|
|
2628
|
+
embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
|
|
2629
|
+
embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
|
|
2630
|
+
embed["model"] = _OLLAMA_MODEL
|
|
2631
|
+
cfg["embed"] = embed
|
|
2632
|
+
brain.atomic_json(brain.HOME / "config.json", cfg)
|
|
2633
|
+
|
|
2634
|
+
|
|
2581
2635
|
def _api_ollama_enable(self, path, data):
|
|
2582
2636
|
"""自动探测接管:Ollama 已在跑但没接入灵枢时,一键写好 embed 配置。
|
|
2583
2637
|
模型没拉则先拉(同步,拉模型耗时可观但属于用户显式点按钮)。"""
|
|
@@ -2591,12 +2645,7 @@ def _api_ollama_enable(self, path, data):
|
|
|
2591
2645
|
if not _ollama_pull_model():
|
|
2592
2646
|
self._json({"ok": False, "error": f"模型 {_OLLAMA_MODEL} 拉取失败"}, 502)
|
|
2593
2647
|
return
|
|
2594
|
-
|
|
2595
|
-
embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
|
|
2596
|
-
embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
|
|
2597
|
-
embed["model"] = _OLLAMA_MODEL
|
|
2598
|
-
cfg["embed"] = embed
|
|
2599
|
-
brain.atomic_json(brain.HOME / "config.json", cfg)
|
|
2648
|
+
_ollama_write_embed_cfg()
|
|
2600
2649
|
self._json({"ok": True, "stage": "done"})
|
|
2601
2650
|
except Exception as exc:
|
|
2602
2651
|
self._log_write_failure("ollama enable", exc, 500)
|
|
@@ -2652,12 +2701,7 @@ def _ollama_setup_async() -> None:
|
|
|
2652
2701
|
_ollama_state_write("error", detail=f"模型 {_OLLAMA_MODEL} 拉取失败(网络或磁盘问题)")
|
|
2653
2702
|
return
|
|
2654
2703
|
# ④ 写 embed 配置启用向量(与 enable/install 同款读-改-写)
|
|
2655
|
-
|
|
2656
|
-
embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
|
|
2657
|
-
embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
|
|
2658
|
-
embed["model"] = _OLLAMA_MODEL
|
|
2659
|
-
cfg["embed"] = embed
|
|
2660
|
-
brain.atomic_json(brain.HOME / "config.json", cfg)
|
|
2704
|
+
_ollama_write_embed_cfg()
|
|
2661
2705
|
_ollama_state_write("done", percent=100, detail="语义召回已就绪(真模型向量)")
|
|
2662
2706
|
except Exception as exc:
|
|
2663
2707
|
_ollama_state_write("error", detail=f"一键流程失败:{exc}")
|
|
@@ -2742,24 +2786,14 @@ def _ollama_auto_probe() -> None:
|
|
|
2742
2786
|
# 服务在跑但灵枢还没接入 → 接管写配置
|
|
2743
2787
|
if not _ollama_embed_configured():
|
|
2744
2788
|
if _OLLAMA_MODEL in _ollama_model_names():
|
|
2745
|
-
|
|
2746
|
-
embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
|
|
2747
|
-
embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
|
|
2748
|
-
embed["model"] = _OLLAMA_MODEL
|
|
2749
|
-
cfg["embed"] = embed
|
|
2750
|
-
brain.atomic_json(brain.HOME / "config.json", cfg)
|
|
2789
|
+
_ollama_write_embed_cfg()
|
|
2751
2790
|
return
|
|
2752
2791
|
# 模型没拉:整个生命周期只自动 pull 一次(避免反复打扰/重复下载)
|
|
2753
2792
|
if _AUTO_PROBE_STATE["pulled"]:
|
|
2754
2793
|
return
|
|
2755
2794
|
_AUTO_PROBE_STATE["pulled"] = True
|
|
2756
2795
|
if _ollama_pull_model():
|
|
2757
|
-
|
|
2758
|
-
embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
|
|
2759
|
-
embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
|
|
2760
|
-
embed["model"] = _OLLAMA_MODEL
|
|
2761
|
-
cfg["embed"] = embed
|
|
2762
|
-
brain.atomic_json(brain.HOME / "config.json", cfg)
|
|
2796
|
+
_ollama_write_embed_cfg()
|
|
2763
2797
|
except Exception:
|
|
2764
2798
|
pass # 探测接管是锦上添花:任何失败都静默,降级兜底照常
|
|
2765
2799
|
finally:
|
|
@@ -2832,12 +2866,7 @@ def _ollama_install_async() -> None:
|
|
|
2832
2866
|
_ollama_state_write("error", detail=f"模型 {_OLLAMA_MODEL} 拉取失败(网络或磁盘问题)")
|
|
2833
2867
|
return
|
|
2834
2868
|
# 写 embed 配置:config_set 是扁平键,embed 是嵌套对象,读-改-写整段 config.json
|
|
2835
|
-
|
|
2836
|
-
embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
|
|
2837
|
-
embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
|
|
2838
|
-
embed["model"] = _OLLAMA_MODEL
|
|
2839
|
-
cfg["embed"] = embed
|
|
2840
|
-
brain.atomic_json(brain.HOME / "config.json", cfg)
|
|
2869
|
+
_ollama_write_embed_cfg()
|
|
2841
2870
|
_ollama_state_write("done", percent=100, detail="语义召回已就绪")
|
|
2842
2871
|
except Exception as exc:
|
|
2843
2872
|
_ollama_state_write("error", detail=f"安装失败:{exc}")
|
|
@@ -447,14 +447,20 @@ def rollback_persona_snapshot(version: int) -> dict | None:
|
|
|
447
447
|
return None
|
|
448
448
|
if not target or not isinstance(target.get("persona"), dict):
|
|
449
449
|
return None
|
|
450
|
-
# 先存一份"回滚前"的快照,这样用户回滚错了还能再回回来
|
|
451
|
-
try:
|
|
452
|
-
save_persona_snapshot(load_persona(), action="pre_rollback", source="rollback",
|
|
453
|
-
why=f"即将回滚到 v{version}")
|
|
454
|
-
except Exception:
|
|
455
|
-
pass
|
|
456
450
|
p = target["persona"]
|
|
457
|
-
|
|
451
|
+
# ★ 快照 + 覆写必须��**同一把锁内**(审计 persona.py:457):
|
|
452
|
+
# 原来 `load_persona()`(读当前值做"回滚前快照")在锁外,`save_persona(p)`
|
|
453
|
+
# 内部才有锁——两步之间的窗口里若有 update_persona / 面板保存写进来,
|
|
454
|
+
# 紧接着的整份覆写会把那次写入静默抹掉(回滚本身就是全量覆盖,最容易吃掉并发写)。
|
|
455
|
+
# `_locked` 可重入,所以内层 save_persona 再取一次同一把锁是安全的。
|
|
456
|
+
with _locked(HOME / "persona.json"):
|
|
457
|
+
# 先存一份"回滚前"的快照,这样用户回滚错了还能再回回来
|
|
458
|
+
try:
|
|
459
|
+
save_persona_snapshot(load_persona(), action="pre_rollback", source="rollback",
|
|
460
|
+
why=f"即将回滚到 v{version}")
|
|
461
|
+
except Exception:
|
|
462
|
+
pass
|
|
463
|
+
save_persona(p)
|
|
458
464
|
return p
|
|
459
465
|
|
|
460
466
|
|
|
@@ -232,7 +232,12 @@ def restore(snap_id: str) -> dict:
|
|
|
232
232
|
except Exception:
|
|
233
233
|
meta = {}
|
|
234
234
|
want = meta.get("sha256") or {}
|
|
235
|
-
|
|
235
|
+
# ★ 两阶段:**先全部校验,再统一写盘**(审计 safety_net.py:257)。
|
|
236
|
+
# 原来是一边校验一边 `_replace_retry` 覆盖,等循环跑完才 `if corrupt: raise`
|
|
237
|
+
# ——于是某个文件指纹不符时,前面几个已经被改成旧内容了,库处于「半新半旧」,
|
|
238
|
+
# 调用方只看到一个异常,却不知道数据已经被部分回滚。
|
|
239
|
+
# 校验阶段不碰工作文件,任何一份不干净就整体拒绝,数据保持原样。
|
|
240
|
+
verified, corrupt = [], []
|
|
236
241
|
for f in sorted(src.glob("*")):
|
|
237
242
|
if f.name == "meta.json" or f.is_dir():
|
|
238
243
|
continue
|
|
@@ -251,16 +256,21 @@ def restore(snap_id: str) -> dict:
|
|
|
251
256
|
except OSError:
|
|
252
257
|
corrupt.append(f.name)
|
|
253
258
|
continue
|
|
259
|
+
verified.append(f)
|
|
260
|
+
if corrupt:
|
|
261
|
+
raise RuntimeError(
|
|
262
|
+
"快照已被污染(内容与快照时记录的 sha256 不符),拒绝用它回滚:"
|
|
263
|
+
+ ", ".join(corrupt)
|
|
264
|
+
+ "。已中止,**未写入任何文件**,库保持回滚前的状态。"
|
|
265
|
+
+ "原因通常是有代码路径就地写文件而不是原子替换。")
|
|
266
|
+
# 写盘阶段:到这里所有文件都已验过,不会再中途因为某个坏文件留下半截状态
|
|
267
|
+
restored = []
|
|
268
|
+
for f in verified:
|
|
254
269
|
dst = _home() / f.name
|
|
255
270
|
tmp = dst.with_name(dst.name + ".restore.tmp")
|
|
256
271
|
shutil.copy2(f, tmp)
|
|
257
272
|
core._replace_retry(tmp, dst)
|
|
258
273
|
restored.append(f.name)
|
|
259
|
-
if corrupt:
|
|
260
|
-
raise RuntimeError(
|
|
261
|
-
"快照已被污染(内容与快照时记录的 sha256 不符),拒绝用它回滚:"
|
|
262
|
-
+ ", ".join(corrupt)
|
|
263
|
-
+ "。原因通常是有代码路径就地写文件而不是原子替换。")
|
|
264
274
|
try:
|
|
265
275
|
core.log_event("safety", f"已从快照回滚 {snap_id}:{', '.join(restored)}",
|
|
266
276
|
level="warn")
|
package/scripts/cli.py
CHANGED
|
@@ -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()
|
package/scripts/dream.py
CHANGED
|
@@ -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()
|
package/scripts/memory.py
CHANGED
|
@@ -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
|
# ---------------------------------------------------------------- 上下文注入
|