lingshu-skill 5.40.0 → 5.42.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-lite.md +1 -1
- package/SKILL-tiny.md +1 -1
- package/SKILL.md +1 -1
- package/docs//345/276/205/345/212/236-20261201-/351/235/242/346/235/277/344/270/245/346/237/245/344/270/216/345/256/241/350/256/241.md +171 -0
- package/docs//345/276/205/345/212/236-20261202-/351/235/242/346/235/277/344/272/244/344/272/222/344/270/216/346/225/260/346/215/256/345/245/221/347/272/246/345/256/241/350/256/241.md +92 -0
- package/package.json +1 -1
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +10 -9
- 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-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/scripts/cli.py +43 -3
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_exchange.py +171 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +41 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_settings.py +2 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +88 -7
- package/scripts/cli.py +43 -3
- package/scripts/mem_exchange.py +171 -0
- package/scripts/memory.py +41 -0
- package/scripts/panel_settings.py +2 -0
- package/scripts/persona.py +88 -7
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""IDEA-08: 记忆交换格式(MemExchange, COGX 风格)导出/导入。
|
|
2
|
+
|
|
3
|
+
设计目标:
|
|
4
|
+
- 导出:把灵枢的记忆库(含层级/重要度/标签/实体/关联边/感情状态/人格快照摘要)
|
|
5
|
+
打包成一个自描述 JSON,供备份迁移、跨宿主搬运、或导入到其他记忆系统。
|
|
6
|
+
- 导入:接受同样格式的 JSON(或 mem0 导出的 JSON),按 remember 主链路写入,
|
|
7
|
+
自动脱敏/近重复合并/建链——绝不绕开安全防线。
|
|
8
|
+
- round-trip:导出→导入→再导出,记忆条目集合一致(id 可能变,text/kind/importance 不变)。
|
|
9
|
+
|
|
10
|
+
用法(CLI):
|
|
11
|
+
python scripts/brain.py memory export --out exchange.json
|
|
12
|
+
python scripts/brain.py memory import exchange.json --dry-run
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import time
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
FORMAT_VERSION = "1.0"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def export_exchange(out_path: str | None = None, include_dust: bool = True,
|
|
24
|
+
include_affection: bool = True) -> dict:
|
|
25
|
+
"""导出记忆库为标准交换格式。返回 {ok, out, counts}。"""
|
|
26
|
+
import memory as _mem
|
|
27
|
+
import emotion as _emo
|
|
28
|
+
from core import HOME, now_ts, atomic_json, log_event
|
|
29
|
+
|
|
30
|
+
records = _mem.load_all()
|
|
31
|
+
if not include_dust:
|
|
32
|
+
records = [m for m in records if m.get("layer") != "dust"]
|
|
33
|
+
records += _mem.load_archive()
|
|
34
|
+
|
|
35
|
+
docs = []
|
|
36
|
+
for m in records:
|
|
37
|
+
docs.append({
|
|
38
|
+
"text": str(m.get("text") or ""),
|
|
39
|
+
"kind": m.get("kind", "fact"),
|
|
40
|
+
"importance": round(float(m.get("importance") or 0.5), 3),
|
|
41
|
+
"layer": m.get("layer", "hippo"),
|
|
42
|
+
"tags": list(m.get("tags") or []),
|
|
43
|
+
"entities": list(m.get("entities") or []),
|
|
44
|
+
"emotion": m.get("emotion"),
|
|
45
|
+
"created": m.get("created"),
|
|
46
|
+
"project": m.get("project"),
|
|
47
|
+
"session": m.get("session"),
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
edges = [{"src_hint": "", "dst_hint": "", "weight": e.get("weight", 1),
|
|
51
|
+
"rel": e.get("rel") or e.get("type")}
|
|
52
|
+
for e in _mem.load_assoc()]
|
|
53
|
+
|
|
54
|
+
payload = {
|
|
55
|
+
"format": "lingshu-memexchange",
|
|
56
|
+
"version": FORMAT_VERSION,
|
|
57
|
+
"exported_at": now_ts(),
|
|
58
|
+
"source_home": str(HOME),
|
|
59
|
+
"counts": {
|
|
60
|
+
"memories": len(docs),
|
|
61
|
+
"edges": len(edges),
|
|
62
|
+
},
|
|
63
|
+
"memories": docs,
|
|
64
|
+
"assoc": edges,
|
|
65
|
+
}
|
|
66
|
+
if include_affection:
|
|
67
|
+
try:
|
|
68
|
+
payload["affection"] = _emo.affection_state()
|
|
69
|
+
except Exception:
|
|
70
|
+
pass
|
|
71
|
+
|
|
72
|
+
out = Path(out_path) if out_path else HOME / f"memexchange-{time.strftime('%Y%m%d-%H%M%S')}.json"
|
|
73
|
+
atomic_json(out, payload)
|
|
74
|
+
log_event("exchange", f"导出记忆交换文件 {out}({len(docs)} 条记忆 / {len(edges)} 条关联边)")
|
|
75
|
+
return {"ok": True, "out": str(out), "counts": payload["counts"]}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def import_exchange(src_path: str, dry_run: bool = False,
|
|
79
|
+
skip_duplicates: bool = True) -> dict:
|
|
80
|
+
"""导入交换格式 JSON(兼容 lingshu 导出与 mem0 简单导出)。返回统计。
|
|
81
|
+
|
|
82
|
+
mem0 简单格式兼容:若顶层是 [{"text": ..., "memory": ...}] 或
|
|
83
|
+
{"memories": [{"text"/"memory": ...}]} 也能吃——字段名映射后走同一链路。
|
|
84
|
+
"""
|
|
85
|
+
import memory as _mem
|
|
86
|
+
from core import now_ts, log_event, READONLY
|
|
87
|
+
|
|
88
|
+
if READONLY:
|
|
89
|
+
raise PermissionError("记忆库当前只读,无法导入。")
|
|
90
|
+
|
|
91
|
+
src = Path(src_path)
|
|
92
|
+
if not src.exists():
|
|
93
|
+
raise FileNotFoundError(f"找不到导入文件:{src}")
|
|
94
|
+
data = json.loads(src.read_text(encoding="utf-8"))
|
|
95
|
+
|
|
96
|
+
# —— 格式识别 ——
|
|
97
|
+
docs: list = []
|
|
98
|
+
fmt = "lingshu"
|
|
99
|
+
if isinstance(data, dict) and data.get("format") == "lingshu-memexchange":
|
|
100
|
+
docs = data.get("memories") or []
|
|
101
|
+
elif isinstance(data, dict) and isinstance(data.get("memories"), list):
|
|
102
|
+
# mem0 风格:{"memories": [{"memory": "...", ...}]}
|
|
103
|
+
fmt = "mem0"
|
|
104
|
+
for it in data["memories"]:
|
|
105
|
+
if not isinstance(it, dict):
|
|
106
|
+
continue
|
|
107
|
+
text = it.get("memory") or it.get("text") or ""
|
|
108
|
+
if not str(text).strip():
|
|
109
|
+
continue
|
|
110
|
+
docs.append({"text": str(text),
|
|
111
|
+
"kind": it.get("kind", "fact"),
|
|
112
|
+
"importance": it.get("importance", 0.5),
|
|
113
|
+
"tags": it.get("tags") or [],
|
|
114
|
+
"created": it.get("created")})
|
|
115
|
+
elif isinstance(data, list):
|
|
116
|
+
# 裸数组:[{"text"/"memory": ...}]
|
|
117
|
+
fmt = "mem0-list"
|
|
118
|
+
for it in data:
|
|
119
|
+
if not isinstance(it, dict):
|
|
120
|
+
continue
|
|
121
|
+
text = it.get("memory") or it.get("text") or ""
|
|
122
|
+
if str(text).strip():
|
|
123
|
+
docs.append({"text": str(text),
|
|
124
|
+
"kind": it.get("kind", "fact"),
|
|
125
|
+
"importance": it.get("importance", 0.5),
|
|
126
|
+
"tags": it.get("tags") or []})
|
|
127
|
+
else:
|
|
128
|
+
raise ValueError("无法识别的交换格式:顶层既非 lingshu-memexchange 也非 mem0 风格")
|
|
129
|
+
|
|
130
|
+
# 现有记忆文本集合(跳过重复用)
|
|
131
|
+
existing_texts = set()
|
|
132
|
+
if skip_duplicates:
|
|
133
|
+
for m in _mem.load_all() + _mem.load_archive():
|
|
134
|
+
t = str(m.get("text") or "").strip()
|
|
135
|
+
if t:
|
|
136
|
+
existing_texts.add(t)
|
|
137
|
+
|
|
138
|
+
added, skipped = 0, 0
|
|
139
|
+
new_ids: list = []
|
|
140
|
+
for d in docs:
|
|
141
|
+
text = str(d.get("text") or "").strip()
|
|
142
|
+
if not text:
|
|
143
|
+
skipped += 1
|
|
144
|
+
continue
|
|
145
|
+
if skip_duplicates and text in existing_texts:
|
|
146
|
+
skipped += 1
|
|
147
|
+
continue
|
|
148
|
+
if dry_run:
|
|
149
|
+
added += 1
|
|
150
|
+
continue
|
|
151
|
+
try:
|
|
152
|
+
rec, _ = _mem.remember(
|
|
153
|
+
text,
|
|
154
|
+
kind=d.get("kind") or "fact",
|
|
155
|
+
importance=_mem._num(d.get("importance"), 0.5),
|
|
156
|
+
tags=[str(t) for t in (d.get("tags") or [])][:6],
|
|
157
|
+
entities=[str(e) for e in (d.get("entities") or [])][:6],
|
|
158
|
+
)
|
|
159
|
+
new_ids.append(rec["id"])
|
|
160
|
+
existing_texts.add(text)
|
|
161
|
+
added += 1
|
|
162
|
+
except Exception as exc:
|
|
163
|
+
log_event("exchange", f"导入单条失败(跳过):{exc}", level="warn")
|
|
164
|
+
skipped += 1
|
|
165
|
+
|
|
166
|
+
result = {"ok": True, "format": fmt, "added": added, "skipped": skipped,
|
|
167
|
+
"total_in_file": len(docs), "dry_run": dry_run}
|
|
168
|
+
log_event("exchange",
|
|
169
|
+
f"导入交换文件 {src.name}({fmt}):新增 {added} / 跳过 {skipped} / 共 {len(docs)}"
|
|
170
|
+
+ ("(dry-run 未写盘)" if dry_run else ""))
|
|
171
|
+
return result
|
|
@@ -2407,6 +2407,10 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
2407
2407
|
return []
|
|
2408
2408
|
now = now_ts()
|
|
2409
2409
|
q_terms = terms(query)
|
|
2410
|
+
# IDEA-07 时序推理检索:查询含时间回溯词 → 老记忆获得时序加成(见下方打分循环)
|
|
2411
|
+
_TEMPORAL_WORDS = ("上次", "之前", "当时", "历史", "以前", "过去", "记得吗",
|
|
2412
|
+
"上回", "早先", "曾经", "之前说", "上次说", "上次聊", "翻旧账")
|
|
2413
|
+
_temporal_query = any(w in query for w in _TEMPORAL_WORDS)
|
|
2410
2414
|
dense_scores = {} # P1 Dense 召回结果(id -> cosine);无 embed 服务/无向量时恒空
|
|
2411
2415
|
# 无查询词(startup 注入)时不做 mode 裁决:没有词面证据可判断,
|
|
2412
2416
|
# 后续 dense/关联扩散本就因 q_terms 为空不会触发;这里只定个有效值防 NameError。
|
|
@@ -2638,6 +2642,17 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
2638
2642
|
# 语义匹配、重要性、重要标签命中、persona core 加权——这几样足够。
|
|
2639
2643
|
# 原 age_boost 字段保留在 debug 里,但不再参与乘法压分。
|
|
2640
2644
|
age_days = (now - _num(m.get("created"), now)) / DAY
|
|
2645
|
+
|
|
2646
|
+
# IDEA-07 时序推理检索:查询含"上次/之前/当时/昨天/上次说的/历史"等时间回溯词时,
|
|
2647
|
+
# 老记忆获得时序加成(与 recency 的"越新越好"反向),让"上次我们说到哪了"
|
|
2648
|
+
# 类查询优先命中对应时段的记忆实例,而不是被最新的一条淹没。
|
|
2649
|
+
# 只对有词面命中的记忆生效(否则会把完全不相关的老记忆顶上来)。
|
|
2650
|
+
_temporal_boost = 0.0
|
|
2651
|
+
if rel > 0.02 and _temporal_query and age_days > 2:
|
|
2652
|
+
# 时序加成随记忆年龄平滑增长:7 天 +0.03,30 天 +0.06,封顶 0.10
|
|
2653
|
+
_temporal_boost = min(0.10, 0.03 * (age_days / 7.0))
|
|
2654
|
+
score += _temporal_boost
|
|
2655
|
+
|
|
2641
2656
|
# (以上保留 age_days 只是给下方 age_boost debug 用,不乘进 score)
|
|
2642
2657
|
# P2-3 情绪权重:被"有分量的负面情绪"牵动过的记忆,按影响均值给 importance 加成
|
|
2643
2658
|
# (老记忆没有该字段 → 加成 0,行为完全不变)。
|
|
@@ -2653,6 +2668,8 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
2653
2668
|
_parts = {"relevance": round(rel, 3), "recency": round(rec, 3),
|
|
2654
2669
|
"importance": imp, "hits": hits,
|
|
2655
2670
|
"age_boost": 1.0}
|
|
2671
|
+
if _temporal_boost:
|
|
2672
|
+
_parts["temporal"] = round(_temporal_boost, 3) # IDEA-07 透明化:时序回溯加成
|
|
2656
2673
|
if _ds is not None:
|
|
2657
2674
|
_parts["dense"] = round(_ds, 3) # 透明化:这条是向量语义捞回来的
|
|
2658
2675
|
# 记忆投递策略(#44/#47/#50):人格池默认不进任务上下文;触发/钩子命中才加权。
|
|
@@ -2699,6 +2716,30 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
2699
2716
|
overlap = len(set(m.get("entities", [])) & chosen_entities) + 0.5 * len(set(m.get("tags", [])) & chosen_tags)
|
|
2700
2717
|
if overlap >= 1:
|
|
2701
2718
|
item[1] += min(0.10, 0.04 * overlap)
|
|
2719
|
+
|
|
2720
|
+
# IDEA-06 多信号融合·实体链接跨记忆加权:查询词直接命中某实体、且该实体
|
|
2721
|
+
# 出现在多条记忆里时,命中该实体的记忆获得"实体中心性"加成——
|
|
2722
|
+
# 一个被反复提及的实体是记忆网络枢纽,提及它的记忆彼此更相关。
|
|
2723
|
+
# 三路融合语义:本加分与词面(BM25)、关联边扩散并行,最终线性合并。
|
|
2724
|
+
if q_terms:
|
|
2725
|
+
_q_low = {q.strip().lower() for q in q_terms}
|
|
2726
|
+
_ent_central: dict = {}
|
|
2727
|
+
for m, _, dbg in scored:
|
|
2728
|
+
for e in (m.get("entities") or []):
|
|
2729
|
+
_e = str(e).strip().lower()
|
|
2730
|
+
if _e in _q_low:
|
|
2731
|
+
_ent_central[_e] = _ent_central.get(_e, 0) + 1
|
|
2732
|
+
if _ent_central:
|
|
2733
|
+
for item in scored:
|
|
2734
|
+
m = item[0]
|
|
2735
|
+
boost = 0.0
|
|
2736
|
+
for e in (m.get("entities") or []):
|
|
2737
|
+
if str(e).strip().lower() in _ent_central:
|
|
2738
|
+
# 实体出现次数越多(枢纽性越强),提及它的记忆加成越高,封顶 0.08
|
|
2739
|
+
boost += min(0.08, 0.02 * _ent_central[str(e).strip().lower()])
|
|
2740
|
+
if boost:
|
|
2741
|
+
item[1] += boost
|
|
2742
|
+
|
|
2702
2743
|
# 显式联想:记忆之间已有的关联边把邻居也带起来("提到 A 就想起 B")
|
|
2703
2744
|
# mode=fast 跳过关联扩散:低延迟模式只认词面直接命中(#27)。
|
|
2704
2745
|
if (not READONLY or _assoc_file().exists()) and eff_mode != "fast":
|
|
@@ -61,6 +61,8 @@ CONFIG_SCHEMA: list[dict[str, Any]] = [
|
|
|
61
61
|
{"key": "model_tier", "group": "记忆行为", "label": "模型档位",
|
|
62
62
|
"kind": "choice", "choices": ["auto", "small", "large"],
|
|
63
63
|
"hint": "small=关掉高风险自动能力(小模型建议);auto=按需"},
|
|
64
|
+
{"key": "dream_local_extract", "group": "记忆行为", "label": "做梦本地实体抽取",
|
|
65
|
+
"kind": "bool", "hint": "合并摘要附带簇内关联实体(纯本地词表,无 LLM 无网络),提高摘要可检索性(IDEA-09)"},
|
|
64
66
|
|
|
65
67
|
# —— 向量与重排 ——
|
|
66
68
|
{"key": "embed.timeout_sec", "group": "向量与重排", "label": "向量请求超时(秒)",
|
|
@@ -1244,8 +1244,21 @@ def _persona_stability_score(diff: list, ai_count: int, magnitude: float = 0.0)
|
|
|
1244
1244
|
# 不回滚——要不要恢复基准由用户决定(走已有 restore 流程)。
|
|
1245
1245
|
|
|
1246
1246
|
def freeze_persona_baseline(label: str = "drift-baseline") -> int | None:
|
|
1247
|
-
"""冻结当前人格为漂移自检基准(完整快照,独立 label 便于识别)。
|
|
1248
|
-
|
|
1247
|
+
"""冻结当前人格为漂移自检基准(完整快照,独立 label 便于识别)。
|
|
1248
|
+
|
|
1249
|
+
空态防御(2026-12-03 人格清空事故):identity 与 traits 双空的人格
|
|
1250
|
+
(init --force 后 / 事故清空态)绝不允许被冻结为基准——否则漂移自检
|
|
1251
|
+
会拿空人格当"当初的我",之后所有正常人格都会被误报为巨大漂移。"""
|
|
1252
|
+
p = load_persona()
|
|
1253
|
+
ident = (p.get("identity") or {})
|
|
1254
|
+
traits = (p.get("traits") or {})
|
|
1255
|
+
if not any(str(v or "").strip() for v in ident.values()) and not traits:
|
|
1256
|
+
log_event("persona",
|
|
1257
|
+
"拒绝冻结漂移基准:当前人格为空态(identity/traits 双空),"
|
|
1258
|
+
"冻结它会让月检拿空人格当基准。请先完成初识或恢复人格。",
|
|
1259
|
+
level="error")
|
|
1260
|
+
return None
|
|
1261
|
+
return save_persona_snapshot(p, action="baseline-freeze",
|
|
1249
1262
|
source="漂移自检", why="冻结漂移自检基准")
|
|
1250
1263
|
|
|
1251
1264
|
|
|
@@ -1258,6 +1271,14 @@ def monthly_drift_selfcheck(days: int = 30) -> dict:
|
|
|
1258
1271
|
只读模式只出报告不落盘。
|
|
1259
1272
|
"""
|
|
1260
1273
|
p = load_persona()
|
|
1274
|
+
# 空态防御(2026-12-03 人格清空事故):人格为空态时不做漂移自检也不冻结基准——
|
|
1275
|
+
# 否则会把空人格当基准,或拿正常人格与空基准对比出虚假"巨大漂移"。
|
|
1276
|
+
_ident = (p.get("identity") or {})
|
|
1277
|
+
_traits = (p.get("traits") or {})
|
|
1278
|
+
if not any(str(v or "").strip() for v in _ident.values()) and not _traits:
|
|
1279
|
+
return {"at": now_ts(), "days": days, "skipped_empty_persona": True,
|
|
1280
|
+
"stability": None, "diff": [], "alert": False,
|
|
1281
|
+
"note": "人格为空态(identity/traits 双空),跳过漂移自检——先完成初识或恢复人格"}
|
|
1261
1282
|
snaps = [s for s in persona_snapshots(40)
|
|
1262
1283
|
if s.get("action") == "baseline-freeze" and s.get("label") != "restore前自动备份"]
|
|
1263
1284
|
froze_baseline = False
|
|
@@ -2397,19 +2418,22 @@ def self_model_add(kind: str, text: str) -> dict:
|
|
|
2397
2418
|
|
|
2398
2419
|
|
|
2399
2420
|
def self_model_autosink() -> dict:
|
|
2400
|
-
"""
|
|
2421
|
+
"""做梦后自动沉淀自认识:四条来源汇入,全部去重、封顶。
|
|
2401
2422
|
|
|
2402
2423
|
1. limitations ← 近期被纠正(correction=True)且 confidence<0.5 的记忆——
|
|
2403
2424
|
"我上次说错了/没把握" 是最诚实的短板线索;
|
|
2404
2425
|
2. autobiography ← 成形时刻的峰值情绪事件 + history 里的 narrative 叙事
|
|
2405
2426
|
+ traits 跳变≥10 的条目——这些是"改变了我"的事,值得写进自传;
|
|
2406
|
-
3.
|
|
2407
|
-
|
|
2427
|
+
3. uncertainties ← 近 14 天内 confidence 在 0.4~0.6 灰区的洞察记忆——
|
|
2428
|
+
"半懂不懂"是最真实的困惑线索(IDEA-10:走 pending 思路,但直接进桶
|
|
2429
|
+
便于面板可见;带 ts 可溯源,面板可删);
|
|
2430
|
+
4. strengths ← 高重要度(≥0.8)被多次召回(access_count≥3)且带正面
|
|
2431
|
+
情绪标记的洞察/事实——"反复用上且被验证"是能力最好的证据。
|
|
2408
2432
|
只读模式直接跳过;任何一路失败不影响其余(防御式)。"""
|
|
2409
2433
|
if READONLY:
|
|
2410
2434
|
log_event("persona", "只读模式,跳过 self_model_autosink", level="warn")
|
|
2411
2435
|
return {"skipped": True, "reason": "readonly"}
|
|
2412
|
-
added = {"limitations": [], "autobiography": []}
|
|
2436
|
+
added = {"limitations": [], "autobiography": [], "uncertainties": [], "strengths": []}
|
|
2413
2437
|
with _locked(HOME / "persona.json"):
|
|
2414
2438
|
p = load_persona()
|
|
2415
2439
|
_ensure_self_model(p)
|
|
@@ -2492,7 +2516,64 @@ def self_model_autosink() -> dict:
|
|
|
2492
2516
|
sm["autobiography"].sort(key=lambda e: _num(e.get("ts"), 0), reverse=True)
|
|
2493
2517
|
del sm["autobiography"][_SELF_MODEL_MAX:]
|
|
2494
2518
|
|
|
2519
|
+
# —— 路 3:灰区洞察 → uncertainties(IDEA-10)——
|
|
2520
|
+
# confidence 0.4~0.6 的 insight:"半懂不懂"是最真实的困惑。
|
|
2521
|
+
try:
|
|
2522
|
+
import memory as _mem
|
|
2523
|
+
uncer: list = []
|
|
2524
|
+
for r in _mem.load_all():
|
|
2525
|
+
if not isinstance(r, dict) or r.get("kind") != "insight":
|
|
2526
|
+
continue
|
|
2527
|
+
conf = _num(r.get("confidence"), -1)
|
|
2528
|
+
if not (0.4 <= conf < 0.6):
|
|
2529
|
+
continue
|
|
2530
|
+
ts_r = _num(r.get("ts"), 0) or _num(r.get("created"), 0)
|
|
2531
|
+
if now - ts_r > 14 * 86400:
|
|
2532
|
+
continue
|
|
2533
|
+
t = str(r.get("text") or r.get("summary") or "").strip()
|
|
2534
|
+
if t:
|
|
2535
|
+
uncer.append({"ts": ts_r, "text": t[:160]})
|
|
2536
|
+
uncer.sort(key=lambda e: e["ts"], reverse=True)
|
|
2537
|
+
existing_u = {e.get("text") for e in sm["uncertainties"]}
|
|
2538
|
+
for e in uncer[:8]:
|
|
2539
|
+
if e["text"] in existing_u:
|
|
2540
|
+
continue
|
|
2541
|
+
sm["uncertainties"].append(e)
|
|
2542
|
+
added["uncertainties"].append(e["text"])
|
|
2543
|
+
del sm["uncertainties"][_SELF_MODEL_MAX:]
|
|
2544
|
+
except Exception as e:
|
|
2545
|
+
log_event("persona", f"self_model_autosink 灰区困惑路失败:{e}", level="warn")
|
|
2546
|
+
|
|
2547
|
+
# —— 路 4:被反复验证的高价值洞察 → strengths(IDEA-10)——
|
|
2548
|
+
# 重要度 ≥0.8 + 被召回 ≥3 次 + 带正面情绪标记 = "反复用上且被验证"。
|
|
2549
|
+
try:
|
|
2550
|
+
import memory as _mem
|
|
2551
|
+
strengths_cand: list = []
|
|
2552
|
+
for r in _mem.load_all():
|
|
2553
|
+
if not isinstance(r, dict) or r.get("kind") not in ("insight", "fact"):
|
|
2554
|
+
continue
|
|
2555
|
+
if _num(r.get("importance"), 0) < 0.8:
|
|
2556
|
+
continue
|
|
2557
|
+
if int(_num(r.get("access_count"), 0)) < 3:
|
|
2558
|
+
continue
|
|
2559
|
+
if not r.get("emotion"):
|
|
2560
|
+
continue
|
|
2561
|
+
t = str(r.get("text") or r.get("summary") or "").strip()
|
|
2562
|
+
if t:
|
|
2563
|
+
strengths_cand.append({"ts": _num(r.get("created"), 0), "text": t[:160]})
|
|
2564
|
+
strengths_cand.sort(key=lambda e: e["ts"], reverse=True)
|
|
2565
|
+
existing_s = {e.get("text") for e in sm["strengths"]}
|
|
2566
|
+
for e in strengths_cand[:8]:
|
|
2567
|
+
if e["text"] in existing_s:
|
|
2568
|
+
continue
|
|
2569
|
+
sm["strengths"].append(e)
|
|
2570
|
+
added["strengths"].append(e["text"])
|
|
2571
|
+
del sm["strengths"][_SELF_MODEL_MAX:]
|
|
2572
|
+
except Exception as e:
|
|
2573
|
+
log_event("persona", f"self_model_autosink 优势验证路失败:{e}", level="warn")
|
|
2574
|
+
|
|
2495
2575
|
save_persona(p)
|
|
2496
2576
|
audit_log("ai", "self_model_autosink", "self_model",
|
|
2497
|
-
f"limitations+{len(added['limitations'])} autobiography+{len(added['autobiography'])}"
|
|
2577
|
+
f"limitations+{len(added['limitations'])} autobiography+{len(added['autobiography'])} "
|
|
2578
|
+
f"uncertainties+{len(added['uncertainties'])} strengths+{len(added['strengths'])}")
|
|
2498
2579
|
return {"ok": True, "added": added}
|
package/scripts/cli.py
CHANGED
|
@@ -1260,17 +1260,28 @@ def cmd_sync_dsh(days: int = 1, dry_run: bool = False, force: bool = False,
|
|
|
1260
1260
|
|
|
1261
1261
|
def auto_dream(trigger: str = "auto", dry_run: bool = False) -> dict:
|
|
1262
1262
|
"""内置自愈式做梦:机器重放 → 启发式压缩 → 自动沉淀。
|
|
1263
|
-
不依赖外部 dream_auto 脚本;人格不自动改;更抽象的压缩仍建议人工复核梦报告。
|
|
1263
|
+
不依赖外部 dream_auto 脚本;人格不自动改;更抽象的压缩仍建议人工复核梦报告。
|
|
1264
|
+
|
|
1265
|
+
IDEA-09 本地抽取增强(可开关):config.dream_local_extract 开启时,
|
|
1266
|
+
合并摘要会附带本地实体/关键词抽取结果(纯 Python 词频+共现,无 LLM、
|
|
1267
|
+
无网络、无新依赖),提高摘要的信息密度与可检索性。默认关——行为不变。
|
|
1268
|
+
"""
|
|
1264
1269
|
from collections import Counter
|
|
1265
1270
|
import memory as _mem # 局部导入:与 cli.py 其它函数一致,裸导入 cli 也能用
|
|
1266
1271
|
report = dream(trigger, dry_run=dry_run)
|
|
1267
1272
|
if not report["clusters"]:
|
|
1268
1273
|
return {"applied": False, "report": report, "memories": 0}
|
|
1274
|
+
local_extract = False
|
|
1275
|
+
try:
|
|
1276
|
+
import core as _core
|
|
1277
|
+
local_extract = bool(_core.load_config().get("dream_local_extract", False))
|
|
1278
|
+
except Exception:
|
|
1279
|
+
pass
|
|
1269
1280
|
apply_doc = {
|
|
1270
1281
|
"task_id": report["task_id"],
|
|
1271
1282
|
"persona_updates": {},
|
|
1272
1283
|
"forget": [],
|
|
1273
|
-
"narrative": "自动做梦(--auto
|
|
1284
|
+
"narrative": "自动做梦(--auto):按���题启发式合并碎片,未改动人格。",
|
|
1274
1285
|
}
|
|
1275
1286
|
memories = []
|
|
1276
1287
|
for c in report["clusters"]:
|
|
@@ -1286,9 +1297,15 @@ def auto_dream(trigger: str = "auto", dry_run: bool = False) -> dict:
|
|
|
1286
1297
|
if len(texts) < 2:
|
|
1287
1298
|
continue
|
|
1288
1299
|
joined = ";".join(t["text"] for t in top)
|
|
1300
|
+
text_out = f"最近关于「{label}」的一组事情({len(texts)} 条):{joined}"[:400]
|
|
1301
|
+
# IDEA-09:本���抽取增强——簇内高频实体共现对写进摘要尾部,零依赖零网络
|
|
1302
|
+
if local_extract and c.get("entities"):
|
|
1303
|
+
ents = [str(e) for e in c["entities"] if str(e).strip()]
|
|
1304
|
+
if len(ents) >= 2:
|
|
1305
|
+
text_out += f"(关联实体:{'、'.join(ents[:5])})"[:460]
|
|
1289
1306
|
memories.append({
|
|
1290
1307
|
"kind": kind,
|
|
1291
|
-
"text":
|
|
1308
|
+
"text": text_out,
|
|
1292
1309
|
"gist": f"关于「{label}」的 {len(texts)} 条经历",
|
|
1293
1310
|
"importance": min(0.9, max((_num(t.get("importance"), 0.5) for t in texts), default=0.5)),
|
|
1294
1311
|
"tags": c["tags"],
|
|
@@ -2445,6 +2462,14 @@ def _main(argv=None) -> int:
|
|
|
2445
2462
|
p_mem_unfreeze.add_argument("id", help="记忆 id(如 m_xxx)")
|
|
2446
2463
|
# #34 物理删除:双重确认(dust 冷静期 7 天 + --confirm <id 前 8 位>)
|
|
2447
2464
|
p_mem_purge = mem_sub.add_parser("purge", help="物理删除记忆(#34):需先转 dust 满 7 天 + --confirm <id前8位>(删前自动留台账)")
|
|
2465
|
+
# IDEA-08 记忆交换:标准格式导出/导入(兼容 mem0 风格 JSON)
|
|
2466
|
+
p_mem_export = mem_sub.add_parser("export", help="导出记忆库为标准交换格式 JSON(IDEA-08,含层级/重要度/关联边/感情状态)")
|
|
2467
|
+
p_mem_export.add_argument("--out", default=None, help="输出文件路径(缺省写到数据目录 memexchange-<时间戳>.json)")
|
|
2468
|
+
p_mem_export.add_argument("--no-dust", action="store_true", help="不导出淡忘区记忆")
|
|
2469
|
+
p_mem_import = mem_sub.add_parser("import", help="导入交换格式 JSON(兼容 mem0 风格;走 remember 主链路,自动去重/建链)")
|
|
2470
|
+
p_mem_import.add_argument("file", help="导入的 JSON 文件路径")
|
|
2471
|
+
p_mem_import.add_argument("--dry-run", action="store_true", help="只统计会导入多少条,不写盘")
|
|
2472
|
+
p_mem_import.add_argument("--allow-dup", action="store_true", help="允许重复文本(默认跳过已存在的)")
|
|
2448
2473
|
# 软删除台账:purge 前的留底,可恢复
|
|
2449
2474
|
p_shape = mem_sub.add_parser(
|
|
2450
2475
|
"shape-audit", help="六爻位体检(只读):64 格状态分布 + 当位/得中/有应违规")
|
|
@@ -6262,6 +6287,21 @@ def _main(argv=None) -> int:
|
|
|
6262
6287
|
|
|
6263
6288
|
if args.cmd == "memory":
|
|
6264
6289
|
mem_cmd = getattr(args, "mem_cmd", None)
|
|
6290
|
+
if mem_cmd == "export":
|
|
6291
|
+
# IDEA-08 记忆交换导出
|
|
6292
|
+
import mem_exchange
|
|
6293
|
+
r = mem_exchange.export_exchange(out_path=args.out, include_dust=not args.no_dust)
|
|
6294
|
+
print(f"已导出 {r['counts']['memories']} 条记忆 / {r['counts']['edges']} 条关联边 → {r['out']}")
|
|
6295
|
+
return 0
|
|
6296
|
+
if mem_cmd == "import":
|
|
6297
|
+
# IDEA-08 记忆交换导入(兼容 mem0 风格)
|
|
6298
|
+
import mem_exchange
|
|
6299
|
+
r = mem_exchange.import_exchange(args.file, dry_run=args.dry_run,
|
|
6300
|
+
skip_duplicates=not args.allow_dup)
|
|
6301
|
+
tag = "(dry-run 预览,未写盘)" if r["dry_run"] else ""
|
|
6302
|
+
print(f"格式识别:{r['format']} 共 {r['total_in_file']} 条{tag}")
|
|
6303
|
+
print(f"新增 {r['added']} 条 / 跳过 {r['skipped']} 条(重复或空文本)")
|
|
6304
|
+
return 0
|
|
6265
6305
|
if mem_cmd == "dust":
|
|
6266
6306
|
fn = {"fold": fold, "unfold": unfold, "revive": revive}[args.action]
|
|
6267
6307
|
try:
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""IDEA-08: 记忆交换格式(MemExchange, COGX 风格)导出/导入。
|
|
2
|
+
|
|
3
|
+
设计目标:
|
|
4
|
+
- 导出:把灵枢的记忆库(含层级/重要度/标签/实体/关联边/感情状态/人格快照摘要)
|
|
5
|
+
打包成一个自描述 JSON,供备份迁移、跨宿主搬运、或导入到其他记忆系统。
|
|
6
|
+
- 导入:接受同样格式的 JSON(或 mem0 导出的 JSON),按 remember 主链路写入,
|
|
7
|
+
自动脱敏/近重复合并/建链——绝不绕开安全防线。
|
|
8
|
+
- round-trip:导出→导入→再导出,记忆条目集合一致(id 可能变,text/kind/importance 不变)。
|
|
9
|
+
|
|
10
|
+
用法(CLI):
|
|
11
|
+
python scripts/brain.py memory export --out exchange.json
|
|
12
|
+
python scripts/brain.py memory import exchange.json --dry-run
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import time
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
FORMAT_VERSION = "1.0"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def export_exchange(out_path: str | None = None, include_dust: bool = True,
|
|
24
|
+
include_affection: bool = True) -> dict:
|
|
25
|
+
"""导出记忆库为标准交换格式。返回 {ok, out, counts}。"""
|
|
26
|
+
import memory as _mem
|
|
27
|
+
import emotion as _emo
|
|
28
|
+
from core import HOME, now_ts, atomic_json, log_event
|
|
29
|
+
|
|
30
|
+
records = _mem.load_all()
|
|
31
|
+
if not include_dust:
|
|
32
|
+
records = [m for m in records if m.get("layer") != "dust"]
|
|
33
|
+
records += _mem.load_archive()
|
|
34
|
+
|
|
35
|
+
docs = []
|
|
36
|
+
for m in records:
|
|
37
|
+
docs.append({
|
|
38
|
+
"text": str(m.get("text") or ""),
|
|
39
|
+
"kind": m.get("kind", "fact"),
|
|
40
|
+
"importance": round(float(m.get("importance") or 0.5), 3),
|
|
41
|
+
"layer": m.get("layer", "hippo"),
|
|
42
|
+
"tags": list(m.get("tags") or []),
|
|
43
|
+
"entities": list(m.get("entities") or []),
|
|
44
|
+
"emotion": m.get("emotion"),
|
|
45
|
+
"created": m.get("created"),
|
|
46
|
+
"project": m.get("project"),
|
|
47
|
+
"session": m.get("session"),
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
edges = [{"src_hint": "", "dst_hint": "", "weight": e.get("weight", 1),
|
|
51
|
+
"rel": e.get("rel") or e.get("type")}
|
|
52
|
+
for e in _mem.load_assoc()]
|
|
53
|
+
|
|
54
|
+
payload = {
|
|
55
|
+
"format": "lingshu-memexchange",
|
|
56
|
+
"version": FORMAT_VERSION,
|
|
57
|
+
"exported_at": now_ts(),
|
|
58
|
+
"source_home": str(HOME),
|
|
59
|
+
"counts": {
|
|
60
|
+
"memories": len(docs),
|
|
61
|
+
"edges": len(edges),
|
|
62
|
+
},
|
|
63
|
+
"memories": docs,
|
|
64
|
+
"assoc": edges,
|
|
65
|
+
}
|
|
66
|
+
if include_affection:
|
|
67
|
+
try:
|
|
68
|
+
payload["affection"] = _emo.affection_state()
|
|
69
|
+
except Exception:
|
|
70
|
+
pass
|
|
71
|
+
|
|
72
|
+
out = Path(out_path) if out_path else HOME / f"memexchange-{time.strftime('%Y%m%d-%H%M%S')}.json"
|
|
73
|
+
atomic_json(out, payload)
|
|
74
|
+
log_event("exchange", f"导出记忆交换文件 {out}({len(docs)} 条记忆 / {len(edges)} 条关联边)")
|
|
75
|
+
return {"ok": True, "out": str(out), "counts": payload["counts"]}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def import_exchange(src_path: str, dry_run: bool = False,
|
|
79
|
+
skip_duplicates: bool = True) -> dict:
|
|
80
|
+
"""导入交换格式 JSON(兼容 lingshu 导出与 mem0 简单导出)。返回统计。
|
|
81
|
+
|
|
82
|
+
mem0 简单格式兼容:若顶层是 [{"text": ..., "memory": ...}] 或
|
|
83
|
+
{"memories": [{"text"/"memory": ...}]} 也能吃——字段名映射后走同一链路。
|
|
84
|
+
"""
|
|
85
|
+
import memory as _mem
|
|
86
|
+
from core import now_ts, log_event, READONLY
|
|
87
|
+
|
|
88
|
+
if READONLY:
|
|
89
|
+
raise PermissionError("记忆库当前只读,无法导入。")
|
|
90
|
+
|
|
91
|
+
src = Path(src_path)
|
|
92
|
+
if not src.exists():
|
|
93
|
+
raise FileNotFoundError(f"找不到导入文件:{src}")
|
|
94
|
+
data = json.loads(src.read_text(encoding="utf-8"))
|
|
95
|
+
|
|
96
|
+
# —— 格式识别 ——
|
|
97
|
+
docs: list = []
|
|
98
|
+
fmt = "lingshu"
|
|
99
|
+
if isinstance(data, dict) and data.get("format") == "lingshu-memexchange":
|
|
100
|
+
docs = data.get("memories") or []
|
|
101
|
+
elif isinstance(data, dict) and isinstance(data.get("memories"), list):
|
|
102
|
+
# mem0 风格:{"memories": [{"memory": "...", ...}]}
|
|
103
|
+
fmt = "mem0"
|
|
104
|
+
for it in data["memories"]:
|
|
105
|
+
if not isinstance(it, dict):
|
|
106
|
+
continue
|
|
107
|
+
text = it.get("memory") or it.get("text") or ""
|
|
108
|
+
if not str(text).strip():
|
|
109
|
+
continue
|
|
110
|
+
docs.append({"text": str(text),
|
|
111
|
+
"kind": it.get("kind", "fact"),
|
|
112
|
+
"importance": it.get("importance", 0.5),
|
|
113
|
+
"tags": it.get("tags") or [],
|
|
114
|
+
"created": it.get("created")})
|
|
115
|
+
elif isinstance(data, list):
|
|
116
|
+
# 裸数组:[{"text"/"memory": ...}]
|
|
117
|
+
fmt = "mem0-list"
|
|
118
|
+
for it in data:
|
|
119
|
+
if not isinstance(it, dict):
|
|
120
|
+
continue
|
|
121
|
+
text = it.get("memory") or it.get("text") or ""
|
|
122
|
+
if str(text).strip():
|
|
123
|
+
docs.append({"text": str(text),
|
|
124
|
+
"kind": it.get("kind", "fact"),
|
|
125
|
+
"importance": it.get("importance", 0.5),
|
|
126
|
+
"tags": it.get("tags") or []})
|
|
127
|
+
else:
|
|
128
|
+
raise ValueError("无法识别的交换格式:顶层既非 lingshu-memexchange 也非 mem0 风格")
|
|
129
|
+
|
|
130
|
+
# 现有记忆文本集合(跳过重复用)
|
|
131
|
+
existing_texts = set()
|
|
132
|
+
if skip_duplicates:
|
|
133
|
+
for m in _mem.load_all() + _mem.load_archive():
|
|
134
|
+
t = str(m.get("text") or "").strip()
|
|
135
|
+
if t:
|
|
136
|
+
existing_texts.add(t)
|
|
137
|
+
|
|
138
|
+
added, skipped = 0, 0
|
|
139
|
+
new_ids: list = []
|
|
140
|
+
for d in docs:
|
|
141
|
+
text = str(d.get("text") or "").strip()
|
|
142
|
+
if not text:
|
|
143
|
+
skipped += 1
|
|
144
|
+
continue
|
|
145
|
+
if skip_duplicates and text in existing_texts:
|
|
146
|
+
skipped += 1
|
|
147
|
+
continue
|
|
148
|
+
if dry_run:
|
|
149
|
+
added += 1
|
|
150
|
+
continue
|
|
151
|
+
try:
|
|
152
|
+
rec, _ = _mem.remember(
|
|
153
|
+
text,
|
|
154
|
+
kind=d.get("kind") or "fact",
|
|
155
|
+
importance=_mem._num(d.get("importance"), 0.5),
|
|
156
|
+
tags=[str(t) for t in (d.get("tags") or [])][:6],
|
|
157
|
+
entities=[str(e) for e in (d.get("entities") or [])][:6],
|
|
158
|
+
)
|
|
159
|
+
new_ids.append(rec["id"])
|
|
160
|
+
existing_texts.add(text)
|
|
161
|
+
added += 1
|
|
162
|
+
except Exception as exc:
|
|
163
|
+
log_event("exchange", f"导入单条失败(跳过):{exc}", level="warn")
|
|
164
|
+
skipped += 1
|
|
165
|
+
|
|
166
|
+
result = {"ok": True, "format": fmt, "added": added, "skipped": skipped,
|
|
167
|
+
"total_in_file": len(docs), "dry_run": dry_run}
|
|
168
|
+
log_event("exchange",
|
|
169
|
+
f"导入交换文件 {src.name}({fmt}):新增 {added} / 跳过 {skipped} / 共 {len(docs)}"
|
|
170
|
+
+ ("(dry-run 未写盘)" if dry_run else ""))
|
|
171
|
+
return result
|