lingshu-skill 5.29.0 → 5.31.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 +168 -0
- package/README.md +1 -1
- package/SKILL-lite.md +1 -1
- package/SKILL-tiny.md +1 -1
- package/SKILL.md +341 -405
- package/assets/panel.html +532 -19
- package/cordis-plugin/lingshu-cron/plugin.js +195 -29
- package/docs//344/275/277/347/224/250/346/214/207/345/215/227.md +229 -0
- package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +134 -43
- package/docs//345/276/205/345/212/236/346/250/241/346/235/277.md +140 -0
- package/package.json +1 -1
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +20 -17
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +168 -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 +341 -405
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +532 -19
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +47 -18
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +32 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +22 -7
- package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +14 -6
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +27 -5
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +15 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +641 -61
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_icon.py +220 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_launcher.py +114 -10
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +225 -72
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_shortcut.py +330 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_splash.py +181 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +31 -11
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety_net.py +45 -9
- package/scripts/cli.py +47 -18
- package/scripts/core.py +32 -0
- package/scripts/dream.py +22 -7
- package/scripts/emotion.py +14 -6
- package/scripts/growth.py +27 -5
- package/scripts/mem_dialogue.py +15 -0
- package/scripts/memory.py +641 -61
- package/scripts/panel_icon.py +220 -0
- package/scripts/panel_launcher.py +114 -10
- package/scripts/panel_server.py +225 -72
- package/scripts/panel_shortcut.py +330 -0
- package/scripts/panel_splash.py +181 -0
- package/scripts/persona.py +31 -11
- package/scripts/safety_net.py +45 -9
|
@@ -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
|
# ---------------------------------------------------------------- 记忆记录
|
|
@@ -2594,12 +2625,24 @@ def recent(k: int = 6, layers: tuple = ("hippo", "cortex")) -> list:
|
|
|
2594
2625
|
|
|
2595
2626
|
|
|
2596
2627
|
def forget(memory_id: str) -> bool:
|
|
2628
|
+
"""把一条记忆移入淡忘层(dust)。
|
|
2629
|
+
|
|
2630
|
+
**置顶(pinned)记忆拒绝**:与 `set_memory_review(discard)`、
|
|
2631
|
+
`apply_dream(forget)` 同一道防线——那两处都硬拒置顶记忆
|
|
2632
|
+
("用户置顶的不参与淡忘"),但 forget 原来不看 pinned,
|
|
2633
|
+
于是置顶记忆可被一条命令/一次误点移入淡忘区(审计 memory.py:2602)。
|
|
2634
|
+
口径不一致本身就是 bug:用户以为置顶锁住了,实际没锁。
|
|
2635
|
+
"""
|
|
2597
2636
|
# 读-改-写整体加锁:forget 用的是 save_all 整库快照覆写,
|
|
2598
2637
|
# 不加锁会把锁外并发写入的新记忆一起丢回旧状态。
|
|
2599
2638
|
with _locked(HOME / "hippocampus.jsonl"):
|
|
2600
2639
|
records = load_all()
|
|
2601
2640
|
for m in records:
|
|
2602
2641
|
if m.get("id") == memory_id and m.get("layer") != "dust":
|
|
2642
|
+
if m.get("pinned"):
|
|
2643
|
+
raise ValueError(
|
|
2644
|
+
"这条记忆是用户置顶的,不能移入淡忘区。"
|
|
2645
|
+
"如确需淡忘,先取消置顶(或手动处理)。")
|
|
2603
2646
|
m["layer"] = "dust"
|
|
2604
2647
|
m["forgotten_at"] = now_ts()
|
|
2605
2648
|
m["detail"] = round(max(0.15, _num(m.get("detail"), 1.0) * 0.5), 2)
|
|
@@ -4161,17 +4204,43 @@ def assoc_auto(weight: float = 0.8, dry_run: bool = False) -> dict:
|
|
|
4161
4204
|
"pairs": added[:20]}
|
|
4162
4205
|
|
|
4163
4206
|
|
|
4164
|
-
|
|
4207
|
+
# 联想图的边密度闸门。为什么需要(实测 2026-11-27):本机 165 条记忆、
|
|
4208
|
+
# 自动联想产生 **9278 条边**(密度 65%,完全图才 13530),前端力导向必然坍缩成一个毛球
|
|
4209
|
+
# 并且卡死。根因不是"记忆多",而是 **两个存档流程标签**:
|
|
4210
|
+
# 「封存」挂在 135 条记忆上(80.4%)→ 单这一个桶就是 135×134/2 = 9045 对
|
|
4211
|
+
# 「即记」挂在 103 条(61.3%) → 再 5253 对
|
|
4212
|
+
# 这类标签描述的是**存储动作**,不是内容关联,不该被当成"相关"。
|
|
4213
|
+
#
|
|
4214
|
+
# 处理分两道(都是数据驱动、不写死具体标签名,换库/换语言也成立):
|
|
4215
|
+
# 1. 泛标签闸:某个标签/实体覆盖了超过 GRAPH_GENERIC_RATIO 的节点 → 视为元数据,
|
|
4216
|
+
# 不参与两两配对。实测阈值 15% 是自然断点:封存/即记/会话存档 全部被拦下,
|
|
4217
|
+
# 边从 9278 → 68(-99.3%),剩下的结构是真实相关的。
|
|
4218
|
+
# 2. 度数闸:单节点自动边只留最强的 GRAPH_MAX_DEGREE 条(Gephi 的 Degree Filter
|
|
4219
|
+
# 等价物;k-core 掉到 1 时仍能保证稀疏)。
|
|
4220
|
+
GRAPH_GENERIC_RATIO = 0.15 # 覆盖超过 15% 节点的标签/实体 = 元数据,不参与联想
|
|
4221
|
+
GRAPH_MAX_DEGREE = 6 # 单节点最多保留的自动联想边数
|
|
4222
|
+
|
|
4223
|
+
|
|
4224
|
+
def assoc_graph(limit: int = 300, generic_ratio: float | None = None,
|
|
4225
|
+
max_degree: int | None = None, hide_isolated: bool = False) -> dict:
|
|
4165
4226
|
"""联想图谱数据:面板 3D 空间用的节点与关联边。
|
|
4166
4227
|
|
|
4167
|
-
v2.32
|
|
4228
|
+
v2.32 起三处升级(均为自动,无需手动连线):
|
|
4168
4229
|
* 人格中心:虚构一个 __persona__ 中心节点,与所有非淡忘记忆自动连边——
|
|
4169
4230
|
图谱以人格为星核呈放射状,一眼看出"哪些记忆离我最近"。
|
|
4170
4231
|
* 自动联想:共享实体/标签的记忆对之间补自动边(复用 assoc_auto 的
|
|
4171
4232
|
计划逻辑但只读不落盘),图谱显示的关联远多于手工 link 的存量边。
|
|
4233
|
+
* **边密度闸门**(v3.48):泛标签(覆盖 >15% 节点,如「封存」「即记」)
|
|
4234
|
+
不参与配对;单节点自动边只留最强 6 条。没有这道闸,几百条记忆就会把
|
|
4235
|
+
图连成 9000+ 边的毛球,既看不出结构也画不动。
|
|
4172
4236
|
|
|
4173
4237
|
节点上限 limit(默认 300,太多画不动);边只保留两端都在图里的。
|
|
4238
|
+
返回里的 `pruned`/`generic_buckets` 是给面板显示"为什么边这么少"用的,
|
|
4239
|
+
不隐藏事实:关掉闸门会是什么规模,一眼可见。
|
|
4174
4240
|
"""
|
|
4241
|
+
ratio = GRAPH_GENERIC_RATIO if generic_ratio is None else float(generic_ratio)
|
|
4242
|
+
maxdeg = GRAPH_MAX_DEGREE if max_degree is None else int(max_degree)
|
|
4243
|
+
|
|
4175
4244
|
records = [m for m in load_all() if m.get("layer") != "dust"]
|
|
4176
4245
|
records.sort(key=lambda m: (_num(m.get("importance"), 0.5),
|
|
4177
4246
|
float(retention(m))), reverse=True)
|
|
@@ -4183,8 +4252,9 @@ def assoc_graph(limit: int = 300) -> dict:
|
|
|
4183
4252
|
edges.append({"src": r["src"], "dst": r["dst"],
|
|
4184
4253
|
"relation": r.get("relation", "相关"),
|
|
4185
4254
|
"weight": float(r.get("weight", 1))})
|
|
4255
|
+
manual_edges = len(edges) # 手工连线永远保留,不受下面两道闸影响
|
|
4186
4256
|
seen_edges = {(e["src"], e["dst"]) for e in edges}
|
|
4187
|
-
|
|
4257
|
+
|
|
4188
4258
|
# 倒排索引:实体/标签 -> 记忆 id 集合。两两组合只发生在同一桶内,
|
|
4189
4259
|
# 复杂度从 O(P×(E+T)) 降到 Σ(桶内两两),记忆多了不再卡面板。
|
|
4190
4260
|
by_ent, by_tag = {}, {}
|
|
@@ -4193,39 +4263,544 @@ def assoc_graph(limit: int = 300) -> dict:
|
|
|
4193
4263
|
by_ent.setdefault(e, set()).add(m["id"])
|
|
4194
4264
|
for t in m.get("tags", []):
|
|
4195
4265
|
by_tag.setdefault(t, set()).add(m["id"])
|
|
4196
|
-
|
|
4197
|
-
|
|
4198
|
-
|
|
4266
|
+
|
|
4267
|
+
n_nodes = max(1, len(nodes))
|
|
4268
|
+
generic_buckets = [] # 被判为元数据的标签/实体(附覆盖数,便于排错)
|
|
4269
|
+
buckets = [] # (显示名, id_set) —— 名字留着给"边证据"用
|
|
4270
|
+
for kind, table in (("标签", by_tag), ("实体", by_ent)):
|
|
4271
|
+
for name, bucket in table.items():
|
|
4272
|
+
if len(bucket) < 2:
|
|
4273
|
+
continue
|
|
4274
|
+
if len(bucket) / n_nodes > ratio:
|
|
4275
|
+
generic_buckets.append({"kind": kind, "name": name,
|
|
4276
|
+
"count": len(bucket),
|
|
4277
|
+
"ratio": round(len(bucket) / n_nodes, 3)})
|
|
4278
|
+
continue
|
|
4279
|
+
buckets.append((f"{kind}·{name}", bucket))
|
|
4280
|
+
generic_buckets.sort(key=lambda x: -x["count"])
|
|
4281
|
+
|
|
4282
|
+
# 每条候选边的权重 = 两端共享的桶数(共享的标签/实体越多越相关)
|
|
4283
|
+
# pair_names 记下**具体共享了哪些**——边证据可视化要用("为什么连这一条")
|
|
4284
|
+
pair_weight: dict[tuple, int] = {}
|
|
4285
|
+
pair_names: dict[tuple, list] = {}
|
|
4286
|
+
owner: dict[str, set] = {} # id -> 命中的桶下标集合(算共享数用)
|
|
4287
|
+
for bi, (bname, bucket) in enumerate(buckets):
|
|
4199
4288
|
bl = sorted(bucket)
|
|
4200
4289
|
for i, a in enumerate(bl):
|
|
4290
|
+
owner.setdefault(a, set()).add(bi)
|
|
4201
4291
|
for b in bl[i + 1:]:
|
|
4292
|
+
owner.setdefault(b, set()).add(bi)
|
|
4202
4293
|
key = (a, b) if a < b else (b, a)
|
|
4203
|
-
if key
|
|
4204
|
-
|
|
4205
|
-
|
|
4206
|
-
|
|
4207
|
-
|
|
4294
|
+
if key in seen_edges:
|
|
4295
|
+
continue
|
|
4296
|
+
pair_weight[key] = pair_weight.get(key, 0) + 1
|
|
4297
|
+
names = pair_names.setdefault(key, [])
|
|
4298
|
+
if len(names) < 4:
|
|
4299
|
+
names.append(bname)
|
|
4300
|
+
|
|
4301
|
+
# 度数闸:优先保留"共享桶多(更相关)+ 两端总度数低(更稀缺)"的边,
|
|
4302
|
+
# 贪心填到每个节点 maxdeg 为止——避免大节点吃掉所有名额。
|
|
4303
|
+
degree_seen: dict[str, int] = {}
|
|
4304
|
+
kept = []
|
|
4305
|
+
for (a, b), w in sorted(pair_weight.items(),
|
|
4306
|
+
key=lambda kv: (-kv[1], kv[0])):
|
|
4307
|
+
if maxdeg and (degree_seen.get(a, 0) >= maxdeg or degree_seen.get(b, 0) >= maxdeg):
|
|
4308
|
+
continue
|
|
4309
|
+
kept.append((a, b, w))
|
|
4310
|
+
degree_seen[a] = degree_seen.get(a, 0) + 1
|
|
4311
|
+
degree_seen[b] = degree_seen.get(b, 0) + 1
|
|
4312
|
+
for a, b, w in kept:
|
|
4208
4313
|
edges.append({"src": a, "dst": b, "relation": "相关",
|
|
4209
|
-
"weight": min(3.0, 0.8 * w),
|
|
4210
|
-
|
|
4314
|
+
"weight": min(3.0, 0.8 * max(1, w)),
|
|
4315
|
+
"auto": True, "shared": w,
|
|
4316
|
+
"shared_names": pair_names.get((a, b), [])})
|
|
4317
|
+
|
|
4318
|
+
# 人格中心节点:星核。**不连全部记忆**——那是另一条"必成毛球"的路:
|
|
4319
|
+
# 300 个节点各连一根,中心点的视觉权重会盖过一切,且弹簧把全图拽向一点。
|
|
4320
|
+
# 改为只连"重要度高 + 自身已出现在联想里"的那一小撮(最多 GRAPH_MAX_DEGREE×2),
|
|
4321
|
+
# 星核仍然是视觉中心,但不再主导力学。
|
|
4211
4322
|
persona_id = "__persona__"
|
|
4212
4323
|
import persona as _persona_mod # 延迟导入避免循环依赖
|
|
4213
4324
|
p = _persona_mod.load_persona()
|
|
4325
|
+
|
|
4326
|
+
# 孤立记忆闸(v3.48):没有真实关联的记忆只留一个点,但它的**斥力还在**——
|
|
4327
|
+
# 137 个孤立节点会把 32 个有结构的节点挤成一坨,视觉上还是那个毛球。
|
|
4328
|
+
# 所以默认把它们整批排除出图(前端可一键「显示全部」重新拉)。
|
|
4329
|
+
isolated_hidden = 0
|
|
4330
|
+
if hide_isolated:
|
|
4331
|
+
linked = set()
|
|
4332
|
+
for a, b, _w in kept:
|
|
4333
|
+
linked.add(a)
|
|
4334
|
+
linked.add(b)
|
|
4335
|
+
for e in edges:
|
|
4336
|
+
if not e.get("auto"):
|
|
4337
|
+
linked.add(e["src"])
|
|
4338
|
+
linked.add(e["dst"])
|
|
4339
|
+
before = len(nodes)
|
|
4340
|
+
nodes = [m for m in nodes if m["id"] in linked]
|
|
4341
|
+
isolated_hidden = before - len(nodes)
|
|
4342
|
+
|
|
4214
4343
|
nodes.insert(0, {"id": persona_id, "gist": "人格 · " + (p.get("name") or "砚"),
|
|
4215
4344
|
"kind": "persona", "layer": "persona",
|
|
4216
4345
|
"importance": 1.0, "emotion": "", "recency": 1.0})
|
|
4217
|
-
|
|
4218
|
-
|
|
4219
|
-
|
|
4346
|
+
|
|
4347
|
+
# ---------------------------------------------------------------- 孤立自举
|
|
4348
|
+
# v3.50:**不再用「人格连所有记忆」的星形假连通**。
|
|
4349
|
+
# 星形能让每点都有边,但那些边不表达任何关系——记忆彼此之间仍然是散的,
|
|
4350
|
+
# 用户看到的是"中间一个核 + 一圈互不相干的点",不是记忆网络。
|
|
4351
|
+
#
|
|
4352
|
+
# 改成业界做法(参考 dsh-memory-nebula 的 orphan bootstrap):
|
|
4353
|
+
# 对「剪枝后度数仍为 0」的记忆,连一条**真实成立**的弱边——与它在
|
|
4354
|
+
# 稀有词上重叠最多的那条记忆。这样连通性来自内容,不是来自中心。
|
|
4355
|
+
# 细节三处(都是踩过的坑):
|
|
4356
|
+
# ① 只用**稀有词**(df 低的词)判相似:高频词("用户""记忆")人人都重叠,
|
|
4357
|
+
# 按它连边等于随机连;
|
|
4358
|
+
# ② 每个孤岛留 **2 条**候选:唯一邻居若在别处被过滤(stale/归档),
|
|
4359
|
+
# 这条边等于白连;
|
|
4360
|
+
# ③ 自举边权重压 0.32,不参与主图排序,也不会盖住真实关联。
|
|
4361
|
+
BOOT_WEIGHT = 0.32
|
|
4362
|
+
BOOT_MAX = 80 # 自举边上限,防极端库把图撑爆
|
|
4363
|
+
RARE_DF = 0.22 # 词频高于这个比例就不算"稀有词"
|
|
4364
|
+
RARE_KEEP = 26 # 每节点保留最稀有的若干个词做签名
|
|
4365
|
+
boot_edges = []
|
|
4366
|
+
orphan_ids = []
|
|
4367
|
+
anchors = [] # 人格接入点(真实度数最高的那几条记忆)
|
|
4368
|
+
try:
|
|
4369
|
+
import fallback_embed as _fe
|
|
4370
|
+
n_all = max(1, len(nodes))
|
|
4371
|
+
# 稀有词签名:每节点取 df 最低的若干个 token
|
|
4372
|
+
sig = {}
|
|
4373
|
+
df = {}
|
|
4374
|
+
for m in nodes[1:]:
|
|
4375
|
+
toks = set(_fe.tokenize(m.get("text") or m.get("gist") or ""))
|
|
4376
|
+
sig[m["id"]] = toks
|
|
4377
|
+
for t in toks:
|
|
4378
|
+
df[t] = df.get(t, 0) + 1
|
|
4379
|
+
rare_cut = max(2, int(n_all * RARE_DF))
|
|
4380
|
+
sig_rare = {k: {t for t in v if df.get(t, 0) <= rare_cut}
|
|
4381
|
+
for k, v in sig.items()}
|
|
4382
|
+
sig_rare = {k: v for k, v in sig_rare.items() if v}
|
|
4383
|
+
|
|
4384
|
+
# 现有度数(不含人格)
|
|
4385
|
+
deg = {}
|
|
4386
|
+
for e in edges:
|
|
4387
|
+
if e["src"] == persona_id or e["dst"] == persona_id:
|
|
4388
|
+
continue
|
|
4389
|
+
deg[e["src"]] = deg.get(e["src"], 0) + 1
|
|
4390
|
+
deg[e["dst"]] = deg.get(e["dst"], 0) + 1
|
|
4391
|
+
orphan_ids = [m["id"] for m in nodes[1:] if not deg.get(m["id"])]
|
|
4392
|
+
|
|
4393
|
+
# 倒排:稀有词 -> 命中节点。只算"孤岛 × 已有邻居"这一小片,不做 N²
|
|
4394
|
+
inv = {}
|
|
4395
|
+
for mid, toks in sig_rare.items():
|
|
4396
|
+
for t in toks:
|
|
4397
|
+
inv.setdefault(t, []).append(mid)
|
|
4398
|
+
for oid in orphan_ids:
|
|
4399
|
+
if len(boot_edges) >= BOOT_MAX:
|
|
4400
|
+
break
|
|
4401
|
+
toks_o = sig_rare.get(oid) or set()
|
|
4402
|
+
if not toks_o:
|
|
4403
|
+
continue
|
|
4404
|
+
hit = {}
|
|
4405
|
+
for t in toks_o:
|
|
4406
|
+
for other in inv.get(t, ()):
|
|
4407
|
+
if other != oid:
|
|
4408
|
+
hit[other] = hit.get(other, 0) + 1
|
|
4409
|
+
if not hit:
|
|
4410
|
+
continue
|
|
4411
|
+
# 共享稀有词越多越优先;同分时偏好重要度高、非归档的邻居
|
|
4412
|
+
scored = sorted(
|
|
4413
|
+
hit.items(),
|
|
4414
|
+
key=lambda kv: (-kv[1], -_num(
|
|
4415
|
+
next((m for m in nodes if m["id"] == kv[0]), {}).get("importance"), 0.5)),
|
|
4416
|
+
)
|
|
4417
|
+
for other, cnt in scored[:2]: # 留 2 条候选
|
|
4418
|
+
w = BOOT_WEIGHT if cnt >= 2 else BOOT_WEIGHT * 0.7
|
|
4419
|
+
boot_edges.append({
|
|
4420
|
+
"src": oid if oid < other else other,
|
|
4421
|
+
"dst": other if oid < other else oid,
|
|
4422
|
+
"relation": "稀有词重叠",
|
|
4423
|
+
"weight": round(w, 3), "auto": True, "boot": True,
|
|
4424
|
+
"shared_rare": cnt,
|
|
4425
|
+
})
|
|
4426
|
+
except Exception as exc: # noqa: BLE001 —— 自举失败不能拖垮整个图
|
|
4427
|
+
brain.log_event("growth", f"联想图孤立自举失败:{exc}", level="warn")
|
|
4428
|
+
|
|
4429
|
+
edges.extend(boot_edges)
|
|
4430
|
+
|
|
4431
|
+
# 人格只连"最有资格当根"的那几条:真实关联度数最高的记忆(不是全部)。
|
|
4432
|
+
# 这样人格稳在中心,但它是**接入**了记忆网络,而不是用放射线假装连通。
|
|
4433
|
+
real_deg = {}
|
|
4434
|
+
for e in edges:
|
|
4435
|
+
if e["src"] == persona_id or e["dst"] == persona_id:
|
|
4436
|
+
continue
|
|
4437
|
+
real_deg[e["src"]] = real_deg.get(e["src"], 0) + 1
|
|
4438
|
+
real_deg[e["dst"]] = real_deg.get(e["dst"], 0) + 1
|
|
4439
|
+
anchors = sorted(real_deg.items(), key=lambda kv: -kv[1])[:max(3, min(8, len(real_deg)))]
|
|
4440
|
+
for aid, _d in anchors:
|
|
4441
|
+
edges.append({"src": persona_id, "dst": aid, "relation": "自我",
|
|
4442
|
+
"weight": 0.9, "auto": True, "anchor": True})
|
|
4443
|
+
# 兜底:若整库一条边都没有(全新库),人格直连重要度最高的几条,
|
|
4444
|
+
# 否则画面上只有一个人格孤点,会被当成"面板坏了"。
|
|
4445
|
+
if not anchors:
|
|
4446
|
+
for m in sorted(nodes[1:], key=lambda x: -_num(x.get("importance"), 0.5))[:5]:
|
|
4447
|
+
edges.append({"src": persona_id, "dst": m["id"], "relation": "自我",
|
|
4448
|
+
"weight": 0.6, "auto": True, "anchor": True})
|
|
4449
|
+
|
|
4450
|
+
kept_ids = {n["id"] for n in nodes}
|
|
4451
|
+
edges = [e for e in edges if e["src"] in kept_ids and e["dst"] in kept_ids]
|
|
4452
|
+
|
|
4453
|
+
# ---------------------------------------------------------------- 连通分量合并
|
|
4454
|
+
# 自举只保证"每个孤岛至少有一条边",但**两条孤岛互相连**仍是一块接不进主图的
|
|
4455
|
+
# 小陆地块。用户要的是"最终肯定能连到人格",所以再补一道:找出所有不含人格的
|
|
4456
|
+
# 连通分量,把每个分量挂到主图上——优先挂给稀有词重叠最多的主图节点,
|
|
4457
|
+
# 没有任何重叠时才退回人格(这条一定成立,是最后兜底)。
|
|
4458
|
+
def _components():
|
|
4459
|
+
parent = {}
|
|
4460
|
+
|
|
4461
|
+
def find(x):
|
|
4462
|
+
parent.setdefault(x, x)
|
|
4463
|
+
while parent[x] != x:
|
|
4464
|
+
parent[x] = parent[parent[x]]
|
|
4465
|
+
x = parent[x]
|
|
4466
|
+
return x
|
|
4467
|
+
|
|
4468
|
+
def union(a, b):
|
|
4469
|
+
ra, rb = find(a), find(b)
|
|
4470
|
+
if ra != rb:
|
|
4471
|
+
parent[rb] = ra
|
|
4472
|
+
|
|
4473
|
+
for e in edges:
|
|
4474
|
+
union(e["src"], e["dst"])
|
|
4475
|
+
groups = {}
|
|
4476
|
+
for m in nodes:
|
|
4477
|
+
groups.setdefault(find(m["id"]), []).append(m["id"])
|
|
4478
|
+
return list(groups.values())
|
|
4479
|
+
|
|
4480
|
+
merged = 0
|
|
4481
|
+
try:
|
|
4482
|
+
import fallback_embed as _fe2
|
|
4483
|
+
for _ in range(4): # 最多四轮,正常一轮就收敛
|
|
4484
|
+
comps = _components()
|
|
4485
|
+
main = next((c for c in comps if persona_id in c), [persona_id])
|
|
4486
|
+
main_set = set(main)
|
|
4487
|
+
others = [c for c in comps if persona_id not in c]
|
|
4488
|
+
if not others:
|
|
4489
|
+
break
|
|
4490
|
+
for comp in others:
|
|
4491
|
+
# 分量里最该代表它的节点:重要度最高的
|
|
4492
|
+
head = max(comp, key=lambda mid: _num(
|
|
4493
|
+
next((m for m in nodes if m["id"] == mid), {}).get("importance"), 0.5))
|
|
4494
|
+
toks_head = set(_fe2.tokenize(
|
|
4495
|
+
next((m.get("text") or m.get("gist") or "" for m in nodes
|
|
4496
|
+
if m["id"] == head), "")))
|
|
4497
|
+
best, best_cnt = None, 0
|
|
4498
|
+
for mid in main_set:
|
|
4499
|
+
toks = set(_fe2.tokenize(
|
|
4500
|
+
next((m.get("text") or m.get("gist") or "" for m in nodes
|
|
4501
|
+
if m["id"] == mid), "")))
|
|
4502
|
+
cnt = len(toks_head & toks)
|
|
4503
|
+
if cnt > best_cnt:
|
|
4504
|
+
best, best_cnt = mid, cnt
|
|
4505
|
+
target = best if (best and best_cnt >= 2) else persona_id
|
|
4506
|
+
a, b = (head, target) if head < target else (target, head)
|
|
4507
|
+
edges.append({
|
|
4508
|
+
"src": a, "dst": b,
|
|
4509
|
+
"relation": "稀有词重叠" if target != persona_id else "自我",
|
|
4510
|
+
"weight": 0.28 if target != persona_id else 0.5,
|
|
4511
|
+
"auto": True, "boot": True, "merge": True,
|
|
4512
|
+
})
|
|
4513
|
+
merged += 1
|
|
4514
|
+
main_set.add(head)
|
|
4515
|
+
except Exception as exc: # noqa: BLE001
|
|
4516
|
+
brain.log_event("growth", f"联想图连通分量合并失败:{exc}", level="warn")
|
|
4517
|
+
|
|
4518
|
+
# 连通性自检:从人格出发 BFS,任何不可达的记忆都要报出来(不静默)
|
|
4519
|
+
adj = {}
|
|
4520
|
+
for e in edges:
|
|
4521
|
+
adj.setdefault(e["src"], set()).add(e["dst"])
|
|
4522
|
+
adj.setdefault(e["dst"], set()).add(e["src"])
|
|
4523
|
+
seen = {persona_id}
|
|
4524
|
+
stack = [persona_id]
|
|
4525
|
+
while stack:
|
|
4526
|
+
u = stack.pop()
|
|
4527
|
+
for v in adj.get(u, ()):
|
|
4528
|
+
if v not in seen:
|
|
4529
|
+
seen.add(v)
|
|
4530
|
+
stack.append(v)
|
|
4531
|
+
orphan = [n["id"] for n in nodes if n["id"] not in seen]
|
|
4532
|
+
|
|
4533
|
+
# ---------------------------------------------------------------- 主题簇
|
|
4534
|
+
# 为什么要有:稀疏图(平均度 2.7)画出来是"一片散点 + 几根线",看不出主题。
|
|
4535
|
+
# 社区检测把"互相连得紧"的记忆分成簇,簇就能当**语义分区**:同色=同一主题,
|
|
4536
|
+
# 缩放时聚成气泡,一眼看出"我的记忆分成哪几块"。
|
|
4537
|
+
#
|
|
4538
|
+
# 参考两种做法:
|
|
4539
|
+
# · Microsoft GraphRAG —— Leiden 分层社区 + 每簇生成报告(最完整,但要装 igraph,
|
|
4540
|
+
# 且分层报告要调 LLM,对本地零依赖技能太重);
|
|
4541
|
+
# · dsh-memory-nebula —— 对 w≥0.34 的**强边**做并查集,留 ≥3 成员的簇(O(E)、零依赖)。
|
|
4542
|
+
# 这里取后者:171 条记忆 / 231 条边,并查集毫秒级,效果足够。
|
|
4543
|
+
#
|
|
4544
|
+
# 一个必须遵守的细节:**人格边不参与聚类**。它是全图根,若参与聚类会把所有簇
|
|
4545
|
+
# 并成一坨(nebula 同样把 mentions 来源节点排除在簇外,是同一个道理)。
|
|
4546
|
+
CLUSTER_MIN_W = 0.34 # 只有"强关联"才参与聚类
|
|
4547
|
+
CLUSTER_MIN_SIZE = 3 # 小于 3 个成员不成簇(噪声)
|
|
4548
|
+
communities = []
|
|
4549
|
+
cluster_of = {}
|
|
4550
|
+
try:
|
|
4551
|
+
import hashlib as _hl
|
|
4552
|
+
|
|
4553
|
+
def _stable(s) -> int:
|
|
4554
|
+
return int(_hl.md5(str(s).encode("utf-8", "ignore")).hexdigest()[:8], 16)
|
|
4555
|
+
|
|
4556
|
+
# ---- Louvain 单层(模块度最大化)----
|
|
4557
|
+
# 为什么不用并查集:连通分量在"图本来就连通"时必然收敛成一个巨型簇,
|
|
4558
|
+
# 实测把 132 条记忆并成一块、标签还退化成一个毫无信息量的词。模块度不同——
|
|
4559
|
+
# 它衡量"簇内比随机更密",所以能在连通图上切出真正的主题分区。
|
|
4560
|
+
# 这也正是 GraphRAG 用 Leiden 而非连通分量的原因(Leiden = Louvain + 精修)。
|
|
4561
|
+
adjw = {}
|
|
4562
|
+
for e in edges:
|
|
4563
|
+
if e["src"] == persona_id or e["dst"] == persona_id:
|
|
4564
|
+
continue # 根不参与聚类
|
|
4565
|
+
w = float(e.get("weight") or 0)
|
|
4566
|
+
if w < CLUSTER_MIN_W:
|
|
4567
|
+
continue
|
|
4568
|
+
adjw.setdefault(e["src"], {})
|
|
4569
|
+
adjw.setdefault(e["dst"], {})
|
|
4570
|
+
adjw[e["src"]][e["dst"]] = adjw[e["src"]].get(e["dst"], 0.0) + w
|
|
4571
|
+
adjw[e["dst"]][e["src"]] = adjw[e["dst"]].get(e["src"], 0.0) + w
|
|
4572
|
+
|
|
4573
|
+
ids = [m["id"] for m in nodes[1:]]
|
|
4574
|
+
deg_w = {i: sum(adjw.get(i, {}).values()) for i in ids}
|
|
4575
|
+
m2 = sum(deg_w.values()) or 1.0
|
|
4576
|
+
comm = {i: i for i in ids}
|
|
4577
|
+
tot = dict(deg_w) # 社区 -> 内部度数之和
|
|
4578
|
+
# 按度数降序处理:高度节点先定型,结果更稳、也更快收敛
|
|
4579
|
+
order_ids = sorted(ids, key=lambda x: -deg_w[x])
|
|
4580
|
+
for _pass in range(15):
|
|
4581
|
+
moved = 0
|
|
4582
|
+
for i in order_ids:
|
|
4583
|
+
if not adjw.get(i):
|
|
4584
|
+
continue
|
|
4585
|
+
ci = comm[i]
|
|
4586
|
+
tot[ci] = tot.get(ci, 0.0) - deg_w[i]
|
|
4587
|
+
nb = {}
|
|
4588
|
+
for j, w in adjw[i].items():
|
|
4589
|
+
cj = comm[j]
|
|
4590
|
+
nb[cj] = nb.get(cj, 0.0) + w
|
|
4591
|
+
best_c, best_gain = ci, 1e-12
|
|
4592
|
+
for c, w in nb.items():
|
|
4593
|
+
gain = w - tot.get(c, 0.0) * deg_w[i] / m2
|
|
4594
|
+
if gain > best_gain:
|
|
4595
|
+
best_c, best_gain = c, gain
|
|
4596
|
+
comm[i] = best_c
|
|
4597
|
+
tot[best_c] = tot.get(best_c, 0.0) + deg_w[i]
|
|
4598
|
+
if best_c != ci:
|
|
4599
|
+
moved += 1
|
|
4600
|
+
if not moved:
|
|
4601
|
+
break
|
|
4602
|
+
|
|
4603
|
+
groups = {}
|
|
4604
|
+
for mid in ids:
|
|
4605
|
+
groups.setdefault(comm[mid], []).append(mid)
|
|
4606
|
+
by_id = {m["id"]: m for m in nodes}
|
|
4607
|
+
# 泛标签不参与命名(它们描述"怎么存的",不是"关于什么")
|
|
4608
|
+
generic_names = {g["name"] for g in generic_buckets if g["kind"] == "标签"}
|
|
4609
|
+
for root, members in groups.items():
|
|
4610
|
+
if len(members) < CLUSTER_MIN_SIZE:
|
|
4611
|
+
continue
|
|
4612
|
+
# 簇名要有信息量。实测退化有三种:① `episode`/`fact` 这类 kind 兜底值
|
|
4613
|
+
# (每条记忆都有,等于没名字);② 纯数字标签(`3`、`77`);③ 单字标签。
|
|
4614
|
+
# 所以先只在"像人话"的标签里挑,挑不到就用**簇内最重要的那条记忆**的
|
|
4615
|
+
# 摘要命名——那至少能让用户认出"这一簇讲的是什么"。
|
|
4616
|
+
cnt = {}
|
|
4617
|
+
for mid in members:
|
|
4618
|
+
for t in (by_id[mid].get("tags") or []):
|
|
4619
|
+
t = str(t).strip()
|
|
4620
|
+
if t in generic_names:
|
|
4621
|
+
continue
|
|
4622
|
+
if len(t) < 2 or t.isdigit():
|
|
4623
|
+
continue
|
|
4624
|
+
cnt[t] = cnt.get(t, 0) + 1
|
|
4625
|
+
label = ""
|
|
4626
|
+
if cnt:
|
|
4627
|
+
top = max(cnt.values())
|
|
4628
|
+
# 同频时取更长的那个(信息量更大),再按字典序保证确定性
|
|
4629
|
+
label = sorted([t for t, c in cnt.items() if c == top],
|
|
4630
|
+
key=lambda x: (-len(x), x))[0]
|
|
4631
|
+
if not label:
|
|
4632
|
+
head = max(members, key=lambda mid: _num(by_id[mid].get("importance"), 0.5))
|
|
4633
|
+
gist = (by_id[head].get("gist") or "").strip()
|
|
4634
|
+
# 会话摘要类记忆的 gist 常以 "user:" / "assistant:" 开头,
|
|
4635
|
+
# 那是来源标记不是内容,当簇名很难看,先剥掉。
|
|
4636
|
+
import re as _re2
|
|
4637
|
+
gist = _re2.sub(r"^(user|assistant|system|工具)\s*[::]\s*", "", gist,
|
|
4638
|
+
flags=_re2.IGNORECASE).strip()
|
|
4639
|
+
label = (gist[:14] + "…") if len(gist) > 14 else (gist or "记忆簇")
|
|
4640
|
+
cid = "c_" + format(_stable(label or root), "x")
|
|
4641
|
+
communities.append({
|
|
4642
|
+
"id": cid,
|
|
4643
|
+
"label": label or "记忆簇",
|
|
4644
|
+
"size": len(members),
|
|
4645
|
+
"members": members,
|
|
4646
|
+
"hue": _stable(label or root) % 360,
|
|
4647
|
+
})
|
|
4648
|
+
for mid in members:
|
|
4649
|
+
cluster_of[mid] = cid
|
|
4650
|
+
communities.sort(key=lambda c: -c["size"])
|
|
4651
|
+
except Exception as exc: # noqa: BLE001 —— 聚类失败降级为"没有簇",不影响出图
|
|
4652
|
+
brain.log_event("growth", f"联想图聚类失败:{exc}", level="warn")
|
|
4653
|
+
communities, cluster_of = [], {}
|
|
4654
|
+
|
|
4655
|
+
# ---------------------------------------------------------------- 分层社区(第二层)
|
|
4656
|
+
# 第一层(Louvain)切出 20+ 个细簇,数量太多、颜色用不过来。再对这些**簇**跑一次
|
|
4657
|
+
# Louvain,得到 3~8 个"大类"——这就是语义缩放的骨架:
|
|
4658
|
+
# 缩远 → 看大类("记忆分几块");拉近 → 看细簇("这块里分几组")。
|
|
4659
|
+
super_of = {}
|
|
4660
|
+
try:
|
|
4661
|
+
if len(communities) >= 3:
|
|
4662
|
+
cids = [c["id"] for c in communities]
|
|
4663
|
+
node2c = dict(cluster_of)
|
|
4664
|
+
cw = {}
|
|
4665
|
+
for e in edges:
|
|
4666
|
+
if e["src"] == persona_id or e["dst"] == persona_id:
|
|
4667
|
+
continue
|
|
4668
|
+
ca, cb = node2c.get(e["src"]), node2c.get(e["dst"])
|
|
4669
|
+
if not ca or not cb or ca == cb:
|
|
4670
|
+
continue
|
|
4671
|
+
w = float(e.get("weight") or 0)
|
|
4672
|
+
if w < CLUSTER_MIN_W:
|
|
4673
|
+
continue
|
|
4674
|
+
k = (ca, cb) if ca < cb else (cb, ca)
|
|
4675
|
+
cw[k] = cw.get(k, 0.0) + w
|
|
4676
|
+
cadj = {c: {} for c in cids}
|
|
4677
|
+
for (a, b), w in cw.items():
|
|
4678
|
+
cadj[a][b] = cadj[a].get(b, 0.0) + w
|
|
4679
|
+
cadj[b][a] = cadj[b].get(a, 0.0) + w
|
|
4680
|
+
cdeg = {c: sum(cadj[c].values()) for c in cids}
|
|
4681
|
+
cm2 = sum(cdeg.values()) or 1.0
|
|
4682
|
+
ccomm = {c: c for c in cids}
|
|
4683
|
+
ctot = dict(cdeg)
|
|
4684
|
+
for _p in range(10):
|
|
4685
|
+
moved = 0
|
|
4686
|
+
for a in sorted(cids, key=lambda x: -cdeg[x]):
|
|
4687
|
+
if not cadj.get(a):
|
|
4688
|
+
continue
|
|
4689
|
+
ca = ccomm[a]
|
|
4690
|
+
ctot[ca] = ctot.get(ca, 0.0) - cdeg[a]
|
|
4691
|
+
nb = {}
|
|
4692
|
+
for b, w in cadj[a].items():
|
|
4693
|
+
cb = ccomm[b]
|
|
4694
|
+
nb[cb] = nb.get(cb, 0.0) + w
|
|
4695
|
+
best, bg = ca, 1e-12
|
|
4696
|
+
for cb, w in nb.items():
|
|
4697
|
+
g = w - ctot.get(cb, 0.0) * cdeg[a] / cm2
|
|
4698
|
+
if g > bg:
|
|
4699
|
+
best, bg = cb, g
|
|
4700
|
+
ccomm[a] = best
|
|
4701
|
+
ctot[best] = ctot.get(best, 0.0) + cdeg[a]
|
|
4702
|
+
if best != ca:
|
|
4703
|
+
moved += 1
|
|
4704
|
+
if not moved:
|
|
4705
|
+
break
|
|
4706
|
+
l2_groups = {}
|
|
4707
|
+
for c in cids:
|
|
4708
|
+
l2_groups.setdefault(ccomm[c], []).append(c)
|
|
4709
|
+
size_of = {c["id"]: c["size"] for c in communities}
|
|
4710
|
+
cid2parent = {}
|
|
4711
|
+
for root, members in l2_groups.items():
|
|
4712
|
+
if len(members) < 2:
|
|
4713
|
+
continue # 单独成不了大类
|
|
4714
|
+
top = max(members, key=lambda c: size_of.get(c, 0))
|
|
4715
|
+
pid = "g_" + format(_stable(top), "x")
|
|
4716
|
+
for c in members:
|
|
4717
|
+
cid2parent[c] = pid
|
|
4718
|
+
for c in communities:
|
|
4719
|
+
if c["id"] in cid2parent:
|
|
4720
|
+
c["parent"] = cid2parent[c["id"]]
|
|
4721
|
+
for mid, cid in node2c.items():
|
|
4722
|
+
if cid in cid2parent:
|
|
4723
|
+
super_of[mid] = cid2parent[cid]
|
|
4724
|
+
except Exception as exc: # noqa: BLE001 —— 第二层失败就只保留第一层
|
|
4725
|
+
brain.log_event("growth", f"联想图分层社区失败:{exc}", level="warn")
|
|
4726
|
+
super_of = {}
|
|
4727
|
+
|
|
4728
|
+
# ---------------------------------------------------------------- 双时态 + 边证据
|
|
4729
|
+
# 双时态(借 Zep / Graphiti 的 bi-temporal 模型):一条关联不是"永远成立"的,
|
|
4730
|
+
# 它有生效窗口。用记忆自己的时间戳推:
|
|
4731
|
+
# t_from = 两端 created 的较大者(两边都写下了,才可能"相关")
|
|
4732
|
+
# t_to = 任一端 forgotten_at(被淡忘即失效);被取代(superseded_by)也算失效
|
|
4733
|
+
# 时间轴视图按 t_from/t_to 过滤,就能回答"那个时间点我知道什么、它们怎么连的"。
|
|
4734
|
+
by_id_full = {m["id"]: m for m in nodes}
|
|
4735
|
+
for e in edges:
|
|
4736
|
+
a = by_id_full.get(e["src"]) or {}
|
|
4737
|
+
b = by_id_full.get(e["dst"]) or {}
|
|
4738
|
+
ca = int(_num(a.get("created"), 0))
|
|
4739
|
+
cb = int(_num(b.get("created"), 0))
|
|
4740
|
+
e["t_from"] = max(ca, cb) or None
|
|
4741
|
+
fa = int(_num(a.get("forgotten_at"), 0))
|
|
4742
|
+
fb = int(_num(b.get("forgotten_at"), 0))
|
|
4743
|
+
e["t_to"] = ((min(fa, fb) if (fa and fb) else (fa or fb)) or None)
|
|
4744
|
+
e["superseded"] = bool(a.get("superseded_by") or b.get("superseded_by"))
|
|
4745
|
+
# ---- 边证据:把"为什么连这一条"写成一句人话 ----
|
|
4746
|
+
if e.get("anchor"):
|
|
4747
|
+
e["why"] = "人格接入点:它是联想度最高的记忆之一"
|
|
4748
|
+
elif e.get("merge"):
|
|
4749
|
+
e["why"] = "连通合并:这一小簇与主图不连通,按稀有词最近邻接上"
|
|
4750
|
+
elif e.get("boot"):
|
|
4751
|
+
cnt = e.get("shared_rare")
|
|
4752
|
+
e["why"] = (f"孤立自举:与它共享 {cnt} 个稀有词" if cnt
|
|
4753
|
+
else "孤立自举:按稀有词最近邻接上")
|
|
4754
|
+
elif e.get("auto"):
|
|
4755
|
+
names = e.get("shared_names") or []
|
|
4756
|
+
e["why"] = (("共享 " + "、".join(names[:3]) + ("…" if len(names) > 3 else ""))
|
|
4757
|
+
if names else f"共享 {e.get('shared', 1)} 个标签/实体")
|
|
4758
|
+
else:
|
|
4759
|
+
e["why"] = f"手工连线({e.get('relation') or '相关'})"
|
|
4760
|
+
|
|
4220
4761
|
return {
|
|
4221
4762
|
"nodes": [{"id": m["id"], "gist": m.get("gist") or heuristic_gist(m.get("text", "")),
|
|
4222
4763
|
"kind": m.get("kind", ""), "layer": m.get("layer", "hippo"),
|
|
4223
4764
|
"importance": _num(m.get("importance"), 0.5),
|
|
4224
4765
|
"emotion": m.get("emotion", ""),
|
|
4225
|
-
"recency": round(retention(m), 2)
|
|
4766
|
+
"recency": round(retention(m), 2),
|
|
4767
|
+
# 时间轴视图与双时态都用它:这条记忆"什么时候存在的"
|
|
4768
|
+
"created": int(_num(m.get("created"), 0)),
|
|
4769
|
+
"forgotten_at": int(_num(m.get("forgotten_at"), 0)) or None,
|
|
4770
|
+
"superseded": bool(m.get("superseded_by")),
|
|
4771
|
+
# 主题簇 id(不在任何簇里 = None);前端据此上色 / 画簇标签
|
|
4772
|
+
"community": cluster_of.get(m["id"]),
|
|
4773
|
+
# 分层社区:一层是细簇,二层是它属于哪个大类
|
|
4774
|
+
"community_l1": cluster_of.get(m["id"]),
|
|
4775
|
+
"community_l2": super_of.get(m["id"])} for m in nodes],
|
|
4226
4776
|
"edges": edges,
|
|
4777
|
+
# 簇摘要:前端在簇中心画标签(LOD),点标签可只看该簇
|
|
4778
|
+
"communities": [{"id": c["id"], "label": c["label"], "size": c["size"],
|
|
4779
|
+
"hue": c["hue"], "parent": c.get("parent")} for c in communities],
|
|
4227
4780
|
"connected": len({e["src"] for e in edges} - {persona_id}
|
|
4228
4781
|
| {e["dst"] for e in edges} - {persona_id}),
|
|
4782
|
+
# 闸门透明化:面板要能说"为什么这么少",而不是让人以为丢数据了
|
|
4783
|
+
"stats": {
|
|
4784
|
+
"nodes": len(nodes),
|
|
4785
|
+
"edges": len(edges),
|
|
4786
|
+
"manual": manual_edges,
|
|
4787
|
+
"auto_candidates": len(pair_weight),
|
|
4788
|
+
"auto_kept": len(kept),
|
|
4789
|
+
"generic_ratio": ratio,
|
|
4790
|
+
"max_degree": maxdeg,
|
|
4791
|
+
"generic_buckets": generic_buckets[:12],
|
|
4792
|
+
"generic_bucket_count": len(generic_buckets),
|
|
4793
|
+
"hide_isolated": bool(hide_isolated),
|
|
4794
|
+
"isolated_hidden": isolated_hidden,
|
|
4795
|
+
# 自举边 = 孤立记忆靠"稀有词重叠"接进网的边;anchor = 人格接入点
|
|
4796
|
+
"boot_edges": len(boot_edges),
|
|
4797
|
+
"boot_orphans": len(orphan_ids),
|
|
4798
|
+
"anchors": len(anchors),
|
|
4799
|
+
"merged": merged,
|
|
4800
|
+
"communities": len(communities),
|
|
4801
|
+
"orphans": orphan[:8],
|
|
4802
|
+
"orphan_count": len(orphan),
|
|
4803
|
+
},
|
|
4229
4804
|
}
|
|
4230
4805
|
|
|
4231
4806
|
# ---------------------------------------------------------------- 上下文注入
|
|
@@ -5274,7 +5849,12 @@ def build_injection(query: str = "", budget_tokens: int | None = None,
|
|
|
5274
5849
|
# 账单模式(report 非 None)不落缓存:观测命令不该改写下次 startup 的快照。
|
|
5275
5850
|
if report is None and cfg.get("session_state_cache"):
|
|
5276
5851
|
_save_cfg = load_config()
|
|
5277
|
-
|
|
5852
|
+
# ⚠ 读侧用 _inject_cache_key(query, budget, cfg, _p_tier) 带压力档位,
|
|
5853
|
+
# 写侧原来只传三个参数 → tier 默认 "full"。于是处于 lazy/minimal 时
|
|
5854
|
+
# 写进去的键与任何一次读的键都不相等,session_state_cache 在压力期
|
|
5855
|
+
# **永远不命中**(用户开了开关也看不出异常,只是白白每次写盘)。
|
|
5856
|
+
# 审计 memory.py:5718。
|
|
5857
|
+
_save_key = _inject_cache_key(query, budget, _save_cfg, _p_tier)
|
|
5278
5858
|
if _save_key:
|
|
5279
5859
|
_inject_cache_save(_save_cfg, _save_key, _result)
|
|
5280
5860
|
return _result
|