lingshu-skill 5.30.0 → 5.32.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +121 -0
  2. package/README.md +1577 -1577
  3. package/SKILL-lite.md +59 -59
  4. package/SKILL-tiny.md +38 -38
  5. package/SKILL.md +317 -405
  6. package/assets/panel.html +505 -19
  7. package/cordis-plugin/lingshu-cron/plugin.js +195 -29
  8. package/docs//344/275/277/347/224/250/346/214/207/345/215/227.md +229 -0
  9. package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +73 -31
  10. package/docs//345/276/205/345/212/236/346/250/241/346/235/277.md +140 -0
  11. package/package.json +52 -52
  12. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +20 -17
  13. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +121 -0
  14. package/scripts/astrbot_plugin_lingshu/engine/README.md +1577 -1577
  15. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +59 -59
  16. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +38 -38
  17. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +317 -405
  18. package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +505 -19
  19. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +47 -18
  20. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +32 -0
  21. package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +7 -1
  22. package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +14 -6
  23. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +27 -5
  24. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +15 -0
  25. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +489 -16
  26. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_icon.py +220 -0
  27. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_launcher.py +114 -10
  28. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +165 -41
  29. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_shortcut.py +330 -0
  30. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_splash.py +181 -0
  31. package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +19 -5
  32. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety_net.py +29 -3
  33. package/scripts/cli.py +47 -18
  34. package/scripts/core.py +32 -0
  35. package/scripts/dream.py +7 -1
  36. package/scripts/emotion.py +14 -6
  37. package/scripts/growth.py +27 -5
  38. package/scripts/mem_dialogue.py +15 -0
  39. package/scripts/memory.py +489 -16
  40. package/scripts/panel_icon.py +220 -0
  41. package/scripts/panel_launcher.py +114 -10
  42. package/scripts/panel_server.py +165 -41
  43. package/scripts/panel_shortcut.py +330 -0
  44. package/scripts/panel_splash.py +181 -0
  45. package/scripts/persona.py +19 -5
  46. package/scripts/safety_net.py +29 -3
@@ -2625,12 +2625,24 @@ def recent(k: int = 6, layers: tuple = ("hippo", "cortex")) -> list:
2625
2625
 
2626
2626
 
2627
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
+ """
2628
2636
  # 读-改-写整体加锁:forget 用的是 save_all 整库快照覆写,
2629
2637
  # 不加锁会把锁外并发写入的新记忆一起丢回旧状态。
2630
2638
  with _locked(HOME / "hippocampus.jsonl"):
2631
2639
  records = load_all()
2632
2640
  for m in records:
2633
2641
  if m.get("id") == memory_id and m.get("layer") != "dust":
2642
+ if m.get("pinned"):
2643
+ raise ValueError(
2644
+ "这条记忆是用户置顶的,不能移入淡忘区。"
2645
+ "如确需淡忘,先取消置顶(或手动处理)。")
2634
2646
  m["layer"] = "dust"
2635
2647
  m["forgotten_at"] = now_ts()
2636
2648
  m["detail"] = round(max(0.15, _num(m.get("detail"), 1.0) * 0.5), 2)
@@ -4254,7 +4266,7 @@ def assoc_graph(limit: int = 300, generic_ratio: float | None = None,
4254
4266
 
4255
4267
  n_nodes = max(1, len(nodes))
4256
4268
  generic_buckets = [] # 被判为元数据的标签/实体(附覆盖数,便于排错)
4257
- buckets = [] # (bucket_key, id_set)
4269
+ buckets = [] # (显示名, id_set) —— 名字留着给"边证据"用
4258
4270
  for kind, table in (("标签", by_tag), ("实体", by_ent)):
4259
4271
  for name, bucket in table.items():
4260
4272
  if len(bucket) < 2:
@@ -4264,13 +4276,15 @@ def assoc_graph(limit: int = 300, generic_ratio: float | None = None,
4264
4276
  "count": len(bucket),
4265
4277
  "ratio": round(len(bucket) / n_nodes, 3)})
4266
4278
  continue
4267
- buckets.append(bucket)
4279
+ buckets.append((f"{kind}·{name}", bucket))
4268
4280
  generic_buckets.sort(key=lambda x: -x["count"])
4269
4281
 
4270
4282
  # 每条候选边的权重 = 两端共享的桶数(共享的标签/实体越多越相关)
4283
+ # pair_names 记下**具体共享了哪些**——边证据可视化要用("为什么连这一条")
4271
4284
  pair_weight: dict[tuple, int] = {}
4285
+ pair_names: dict[tuple, list] = {}
4272
4286
  owner: dict[str, set] = {} # id -> 命中的桶下标集合(算共享数用)
4273
- for bi, bucket in enumerate(buckets):
4287
+ for bi, (bname, bucket) in enumerate(buckets):
4274
4288
  bl = sorted(bucket)
4275
4289
  for i, a in enumerate(bl):
4276
4290
  owner.setdefault(a, set()).add(bi)
@@ -4280,6 +4294,9 @@ def assoc_graph(limit: int = 300, generic_ratio: float | None = None,
4280
4294
  if key in seen_edges:
4281
4295
  continue
4282
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)
4283
4300
 
4284
4301
  # 度数闸:优先保留"共享桶多(更相关)+ 两端总度数低(更稀缺)"的边,
4285
4302
  # 贪心填到每个节点 maxdeg 为止——避免大节点吃掉所有名额。
@@ -4295,7 +4312,8 @@ def assoc_graph(limit: int = 300, generic_ratio: float | None = None,
4295
4312
  for a, b, w in kept:
4296
4313
  edges.append({"src": a, "dst": b, "relation": "相关",
4297
4314
  "weight": min(3.0, 0.8 * max(1, w)),
4298
- "auto": True, "shared": w})
4315
+ "auto": True, "shared": w,
4316
+ "shared_names": pair_names.get((a, b), [])})
4299
4317
 
4300
4318
  # 人格中心节点:星核。**不连全部记忆**——那是另一条"必成毛球"的路:
4301
4319
  # 300 个节点各连一根,中心点的视觉权重会盖过一切,且弹簧把全图拽向一点。
@@ -4325,23 +4343,440 @@ def assoc_graph(limit: int = 300, generic_ratio: float | None = None,
4325
4343
  nodes.insert(0, {"id": persona_id, "gist": "人格 · " + (p.get("name") or "砚"),
4326
4344
  "kind": "persona", "layer": "persona",
4327
4345
  "importance": 1.0, "emotion": "", "recency": 1.0})
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]:
4334
- edges.append({"src": persona_id, "dst": m["id"], "relation": "自我",
4335
- "weight": 0.4 + _num(m.get("importance"), 0.5), "auto": True})
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
+
4336
4450
  kept_ids = {n["id"] for n in nodes}
4337
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
+
4338
4761
  return {
4339
4762
  "nodes": [{"id": m["id"], "gist": m.get("gist") or heuristic_gist(m.get("text", "")),
4340
4763
  "kind": m.get("kind", ""), "layer": m.get("layer", "hippo"),
4341
4764
  "importance": _num(m.get("importance"), 0.5),
4342
4765
  "emotion": m.get("emotion", ""),
4343
- "recency": round(retention(m), 2)} for m in nodes],
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],
4344
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],
4345
4780
  "connected": len({e["src"] for e in edges} - {persona_id}
4346
4781
  | {e["dst"] for e in edges} - {persona_id}),
4347
4782
  # 闸门透明化:面板要能说"为什么这么少",而不是让人以为丢数据了
@@ -4357,6 +4792,14 @@ def assoc_graph(limit: int = 300, generic_ratio: float | None = None,
4357
4792
  "generic_bucket_count": len(generic_buckets),
4358
4793
  "hide_isolated": bool(hide_isolated),
4359
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),
4360
4803
  },
4361
4804
  }
4362
4805
 
@@ -5376,8 +5819,33 @@ def build_injection(query: str = "", budget_tokens: int | None = None,
5376
5819
  "budget_frac": round(t / budget, 4) if budget else 0.0})
5377
5820
  total_chars += c
5378
5821
  total_tokens += t
5379
- # 自检:各段 chars 求和必须严格等于最终文本长度,否则账单不可信。
5380
- assert total_chars == len(_result), (total_chars, len(_result))
5822
+ # 自检:各段 chars 求和应等于最终文本长度。
5823
+ # ⚠ 不能用 assert(v5.31 实测修):
5824
+ # 1) 上方对 _result 做过指针标记替换,长度会变,按未替换的 out 累加必然不等;
5825
+ # 2) 生产代码用 assert 校验数据,`python -O` 下会被整体跳过;
5826
+ # 3) 它把观测工具变成崩溃源——`context-stats` 会因为这里直接退出。
5827
+ # 改为:按真实长度把差额归到 other 段(保证 Σ段 == 总长、账单可信),
5828
+ # 同时记 warn,真实装配 bug 仍然看得见。
5829
+ if total_chars != len(_result):
5830
+ _delta = len(_result) - total_chars
5831
+ for _s in sections:
5832
+ if _s["name"] == "other":
5833
+ _s["chars"] += _delta
5834
+ _s["tokens"] = int(math.ceil(_s["chars"] / ratio)) if _s["chars"] > 0 else 0
5835
+ _s["budget_frac"] = round(_s["tokens"] / budget, 4) if budget else 0.0
5836
+ break
5837
+ else:
5838
+ sections.append({"name": "other", "chars": _delta,
5839
+ "tokens": int(math.ceil(max(0, _delta) / ratio)),
5840
+ "budget_frac": 0.0})
5841
+ total_chars = len(_result)
5842
+ total_tokens = sum(_s["tokens"] for _s in sections)
5843
+ try:
5844
+ log_event("inject",
5845
+ f"注入账单字符数与实际不符(已按实际校正 {_delta:+d}):"
5846
+ "通常是指针标记替换改变了长度", level="warn")
5847
+ except Exception: # noqa: BLE001
5848
+ pass
5381
5849
  report.update({"sections": sections, "total_chars": total_chars,
5382
5850
  "total_tokens": total_tokens, "budget": budget,
5383
5851
  "chars_per_token": ratio})
@@ -5406,7 +5874,12 @@ def build_injection(query: str = "", budget_tokens: int | None = None,
5406
5874
  # 账单模式(report 非 None)不落缓存:观测命令不该改写下次 startup 的快照。
5407
5875
  if report is None and cfg.get("session_state_cache"):
5408
5876
  _save_cfg = load_config()
5409
- _save_key = _inject_cache_key(query, budget, _save_cfg)
5877
+ # ⚠ 读侧用 _inject_cache_key(query, budget, cfg, _p_tier) 带压力档位,
5878
+ # 写侧原来只传三个参数 → tier 默认 "full"。于是处于 lazy/minimal 时
5879
+ # 写进去的键与任何一次读的键都不相等,session_state_cache 在压力期
5880
+ # **永远不命中**(用户开了开关也看不出异常,只是白白每次写盘)。
5881
+ # 审计 memory.py:5718。
5882
+ _save_key = _inject_cache_key(query, budget, _save_cfg, _p_tier)
5410
5883
  if _save_key:
5411
5884
  _inject_cache_save(_save_cfg, _save_key, _result)
5412
5885
  return _result