lingshu-skill 5.29.0 → 5.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- <!doctype html>
1
+ <!doctype html>
2
2
  <html lang="zh-CN"><head>
3
3
  <meta charset="utf-8">
4
4
  <meta name="lingshu-panel" content="1" />
@@ -785,6 +785,10 @@
785
785
  <option value="300" selected>300 节点</option>
786
786
  <option value="600">600 节点</option>
787
787
  </select>
788
+ <label class="sub" style="display:flex;align-items:center;gap:5px;cursor:pointer;user-select:none"
789
+ title="只画有真实联想关系的记忆。孤立记忆不贡献结构,还会用斥力把可见部分挤成一坨——这是「点开就是个球」的主因之一。取消勾选可看全部">
790
+ <input type="checkbox" id="graph-hide-isolated" checked>只看有联想的
791
+ </label>
788
792
  <button class="ghost" id="btn-graph-reset">重置视角</button>
789
793
  <button class="ghost" id="btn-graph-refresh">刷新</button>
790
794
  <button class="ghost" id="btn-graph-auto">自动联想</button>
@@ -1754,9 +1758,12 @@ function renderDailyCards(){
1754
1758
  }
1755
1759
 
1756
1760
  // ---------------- 记忆联想 · 3D 空间(零依赖力导向) ----------------
1761
+ // hideIsolated:默认只看"真有联想关系"的记忆。孤立记忆不是被丢了,是被收起——
1762
+ // 它们在图里既不贡献结构、又用斥力把可见部分挤成一坨(毛球的主要成因之一)。
1757
1763
  const GRAPH = { data: null, pos: [], yaw: 0.6, pitch: -0.35, dist: 360,
1758
1764
  focus: {x: 0, y: 0, z: 0}, target: {x: 0, y: 0, z: 0}, targetDist: 360,
1759
- selected: null, hover: null, loaded: false, nbrs: null, anim: null, pathEdges: null };
1765
+ selected: null, hover: null, loaded: false, nbrs: null, anim: null,
1766
+ pathEdges: null, hideIsolated: true, stats: null, deg: null };
1760
1767
  const LAYER_COLOR = { cortex: "#d9a441", hippo: "#5fa8a0", dust: "#5d646e", archive: "#8f92b8" };
1761
1768
  // 颜色 = 重要程度(与图例一致):红=很重要 / 金=较重要 / 青=一般 / 灰=不重要;人格星核专属暖金
1762
1769
  // 主题跟随:取 --node-* RGB 三元组(浅色主题在 enhance.css 里覆盖为深色版本)
@@ -1812,6 +1819,9 @@ function startPhysics(){
1812
1819
  if (!nodes || !pos || !vel || !GRAPH.loaded){ GRAPH.phys = null; return; }
1813
1820
  const n = Math.min(nodes.length, 260);
1814
1821
  const kk = 24, rep = 5200;
1822
+ // 初始半径随节点数放大:节点多时还按 24 的"理想边长"铺,力不够撑开,
1823
+ // 一堆节点只能互相重叠着挤在中心——那是"一个球"的另一半原因。
1824
+ const ideal = kk * Math.max(1, Math.sqrt(nodes.length / 12));
1815
1825
  // 防重叠:硬斥力只对"贴在一起"的节点生效,避免大图里互相穿透成一坨;>250 个节点跳过保性能
1816
1826
  const overlap = nodes.length <= 250;
1817
1827
  let energy = 0;
@@ -1834,7 +1844,13 @@ function startPhysics(){
1834
1844
  (GRAPH.springs[i] || []).forEach(([j, w]) => {
1835
1845
  const dx = pos[j].x - pos[i].x, dy = pos[j].y - pos[i].y, dz = pos[j].z - pos[i].z;
1836
1846
  const d = Math.sqrt(dx*dx + dy*dy + dz*dz) + 1e-6;
1837
- const f = (d - kk) * 0.03 * (0.5 + w * 0.5);
1847
+ // 弹簧力按两端度数归一(除以 sqrt(deg)):枢纽节点连了十几条边时,
1848
+ // 每条边都按原样拉会让整个子图被拽进一点、坍缩成球。
1849
+ // 归一后"每个连接的权重"相近,结构才铺得开——这是力导向做密度补偿的常规做法。
1850
+ const di = Math.max(1, (GRAPH.deg && GRAPH.deg[i]) || 1);
1851
+ const dj = Math.max(1, (GRAPH.deg && GRAPH.deg[j]) || 1);
1852
+ const norm = 1 / Math.sqrt(di * dj);
1853
+ const f = (d - ideal) * 0.03 * (0.5 + w * 0.5) * norm;
1838
1854
  fx += dx / d * f; fy += dy / d * f; fz += dz / d * f;
1839
1855
  });
1840
1856
  vel[i].x = (vel[i].x + fx * 0.06) * 0.86;
@@ -1861,7 +1877,7 @@ function startPhysics(){
1861
1877
  for (let i = n; i < nodes.length; i++){
1862
1878
  const p = pos[i];
1863
1879
  const d = Math.sqrt(p.x*p.x + p.y*p.y + p.z*p.z) + 1e-6;
1864
- const f = (d - kk) / d * -0.006; // 远的往回收、近的往外推,缓慢归位到 kk 半径
1880
+ const f = (d - ideal) / d * -0.006; // 远的往回收、近的往外推,缓慢归位到 ideal 半径
1865
1881
  vel[i].x = (vel[i].x + p.x * f) * 0.9;
1866
1882
  vel[i].y = (vel[i].y + p.y * f) * 0.9;
1867
1883
  vel[i].z = (vel[i].z + p.z * f) * 0.9;
@@ -1919,7 +1935,9 @@ async function loadGraph(limit){
1919
1935
  GRAPH.focus = {x: 0, y: 0, z: 0}; GRAPH.target = {x: 0, y: 0, z: 0};
1920
1936
  GRAPH.targetDist = 360;
1921
1937
  try {
1922
- GRAPH.data = await api("/api/graph?limit=" + (limit || 300));
1938
+ GRAPH.data = await api("/api/graph?limit=" + (limit || 300)
1939
+ + (GRAPH.hideIsolated ? "&hide_isolated=1" : "&hide_isolated=0"));
1940
+ GRAPH.stats = GRAPH.data.stats || null;
1923
1941
  // 节点从中心附近"绽放"散开(借鉴 Obsidian graph view 的加载动效)
1924
1942
  GRAPH.vel = GRAPH.data.nodes.map(() => ({ x: 0, y: 0, z: 0 }));
1925
1943
  GRAPH.pos = GRAPH.data.nodes.map(n => {
@@ -1938,6 +1956,14 @@ async function loadGraph(limit){
1938
1956
  nodes.forEach((_, i) => GRAPH.nbrs.set(i, new Set()));
1939
1957
  edges.forEach(e => { const a = idx.get(e.src), b = idx.get(e.dst);
1940
1958
  if (a != null && b != null){ GRAPH.nbrs.get(a).add(b); GRAPH.nbrs.get(b).add(a); } });
1959
+ // 真实关联度数(不含人格星核):孤立节点判定、LOD 都用它
1960
+ GRAPH.deg = nodes.map(() => 0);
1961
+ edges.forEach(e => {
1962
+ if (e.src === "__persona__" || e.dst === "__persona__") return;
1963
+ const a = idx.get(e.src), b = idx.get(e.dst);
1964
+ if (a != null) GRAPH.deg[a]++;
1965
+ if (b != null) GRAPH.deg[b]++;
1966
+ });
1941
1967
  GRAPH.loaded = true;
1942
1968
  startPhysics(); // 持续物理模拟:节点像活物一样漂浮舒展
1943
1969
  renderGraph();
@@ -1950,7 +1976,16 @@ async function loadGraph(limit){
1950
1976
  } else {
1951
1977
  if (loadTip) loadTip.classList.add("hidden");
1952
1978
  const nAuto = edges.filter(e => e.auto).length;
1953
- $("graph-hint").textContent = `${nodes.length} 条记忆 · ${edges.length} 条关联(${nAuto} 条自动联想)· 点节点:以它为中心 + 激活相邻记忆`;
1979
+ const s = GRAPH.stats || {};
1980
+ // 把"为什么边这么少"讲明白:拦下了哪几个泛标签、收起了多少孤立记忆。
1981
+ // 不解释的话,用户会以为记忆丢了——这是比"球"更难查的误解。
1982
+ const gb = (s.generic_buckets || []).slice(0, 3)
1983
+ .map(b => `${b.name}(${b.count})`).join("、");
1984
+ const bits = [`${nodes.length} 条记忆`, `${edges.length} 条关联`];
1985
+ if (s.auto_candidates != null) bits.push(`候选 ${s.auto_candidates} → 保留 ${s.auto_kept}`);
1986
+ if (gb) bits.push(`泛标签已忽略:${gb}${s.generic_bucket_count > 3 ? " 等" + s.generic_bucket_count + "个" : ""}`);
1987
+ if (s.isolated_hidden) bits.push(`收起 ${s.isolated_hidden} 条无联想的记忆(可勾选显示)`);
1988
+ $("graph-hint").textContent = bits.join(" · ") + " · 点节点:以它为中心 + 激活相邻记忆";
1954
1989
  $("graph-stat").textContent = `${nodes.length} 节点 · ${edges.length} 关联边 · 手动 ${edges.length - nAuto} / 自动 ${nAuto}`;
1955
1990
  }
1956
1991
  } catch (e) {
@@ -3843,6 +3878,12 @@ if (btnGa) btnGa.addEventListener("click", async () => {
3843
3878
  } catch (e) { console.error("自动联想:", e); toast(e.message, true); }
3844
3879
  });
3845
3880
  $("graph-limit").addEventListener("change", () => loadGraph(Number($("graph-limit").value || 300)));
3881
+ // 「只看有联想的」:切换要重新拉图——孤立记忆必须整批退出力学,只在前端隐藏没用,
3882
+ // 它们看不见的斥力照样会把可见部分挤成一坨。
3883
+ $("graph-hide-isolated") && $("graph-hide-isolated").addEventListener("change", e => {
3884
+ GRAPH.hideIsolated = !!e.target.checked;
3885
+ loadGraph(Number($("graph-limit").value || 300));
3886
+ });
3846
3887
  // 图内搜索:输入即定位(300ms 防抖),回车看下一个命中
3847
3888
  let _gsTimer = null;
3848
3889
  $("graph-search").addEventListener("input", e => {
@@ -237,9 +237,14 @@ def cluster_memories(records: list, max_clusters: int = 6, include_ids: set | No
237
237
  def _dream_snapshot() -> str:
238
238
  """做梦改库前的自动快照(借鉴 sage-mem:整理前强制建回滚点)。
239
239
 
240
- 只打包记忆相关的核心文件(hippocampus/assoc/archive 等),比全库 backup
241
- 轻量得多;存在 ~/.brain-memory/dream-snapshots/ 下,保留最近 10 份。
240
+ 存 ~/.brain-memory/dream-snapshots/ 下,保留最近 10 份。
242
241
  失败返回 "" 并记事件日志;调用方(dream)fail-closed:拿不到快照就拒绝整理。
242
+
243
+ **core_files 必须覆盖 `save_all` 真正会写的全部文件**。`save_all` 写的是
244
+ ("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl"),而 dream 恰好会 promote 到
245
+ cortex、淡忘到 dust——早期版本只备份 hippocampus 一层,于是 restore 之后
246
+ cortex/dust 保持新状态、hippocampus 回到旧状态,同一条记忆同时出现在两处,
247
+ 库处于半新半旧状态,而报告却写着"可用 restore 还原"(审计 dream.py:253)。
243
248
  """
244
249
  snap_dir = HOME / "dream-snapshots"
245
250
  try:
@@ -250,19 +255,23 @@ def _dream_snapshot() -> str:
250
255
  while path.exists():
251
256
  k += 1
252
257
  path = snap_dir / f"dream-snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{k}.zip"
253
- core_files = ["hippocampus.jsonl", "archive.jsonl", "assoc.jsonl",
258
+ # 三层记忆全都要(hippo/cortex/dust 是 save_all 的写入目标,缺一层回滚点就是残的)
259
+ core_files = ["hippocampus.jsonl", "cortex.jsonl", "dust.jsonl",
260
+ "archive.jsonl", "assoc.jsonl",
254
261
  "knowledge.jsonl", "persona.json", "dream_state.json"]
255
262
  with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as zf:
256
263
  for name in core_files:
257
264
  f = HOME / name
258
265
  if f.is_file():
259
266
  zf.write(f, name)
260
- # 保留最近 10 份,旧的删掉
267
+ # 保留最近 10 份;旧的移入 .pruned/ 而不是删除(用户规矩:要删的进垃圾桶/归档)
268
+ pruned = snap_dir / ".pruned"
261
269
  snaps = sorted(snap_dir.glob("dream-snap_*.zip"))
262
270
  for p in snaps[:-10]:
263
271
  try:
264
- p.unlink()
265
- except OSError:
272
+ pruned.mkdir(parents=True, exist_ok=True)
273
+ shutil.move(str(p), str(pruned / p.name))
274
+ except (OSError, shutil.Error):
266
275
  pass
267
276
  return str(path)
268
277
  except Exception as exc:
@@ -678,17 +678,38 @@ def verify_integrity() -> dict:
678
678
 
679
679
 
680
680
  def load_all() -> list:
681
- """三层热层合并;缺 id 或不是 dict 的畸形记录一律跳过——
682
- 项目里没有任何调用方想处理畸形记录,在这里统一过滤最省事。"""
683
- raw = read_jsonl(HOME / "hippocampus.jsonl") + read_jsonl(HOME / "cortex.jsonl") + read_jsonl(HOME / "dust.jsonl")
684
- good, bad = [], 0
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) and r.get("id"):
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} 条畸形记录(缺 id 或类型错)", level="warning")
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
- staged = []
921
- try:
922
- for fname, rows in targets:
923
- p = HOME / fname
924
- p.parent.mkdir(parents=True, exist_ok=True)
925
- tmp = _tmp_path(p)
926
- with open(tmp, "w", encoding="utf-8", newline="\n") as f:
927
- for r in rows:
928
- f.write(json.dumps(r, ensure_ascii=False) + "\n")
929
- staged.append((tmp, p))
930
- except Exception:
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
- _v = _sn.verify(("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl"))
945
- if not _v.get("ok"):
946
- _sn.restore(_snap)
947
- raise RuntimeError(
948
- "save_all 写后校验失败,已从快照自动回滚:"
949
- + ";".join((_v.get("issues") or [])[:3]))
950
- except RuntimeError:
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
- except Exception as exc: # noqa: BLE001
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
- log_event("safety", f"写后校验本身出错(已跳过,数据未动):{exc}",
955
- level="warn")
956
- except Exception:
957
- pass
975
+ _v = _sn.verify(("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl"))
976
+ if not _v.get("ok"):
977
+ _sn.restore(_snap)
978
+ raise RuntimeError(
979
+ "save_all 写后校验失败,已从快照自动回滚:"
980
+ + ";".join((_v.get("issues") or [])[:3]))
981
+ except RuntimeError:
982
+ raise
983
+ except Exception as exc: # noqa: BLE001
984
+ try:
985
+ log_event("safety", f"写后校验本身出错(已跳过,数据未动):{exc}",
986
+ level="warn")
987
+ except Exception:
988
+ pass
958
989
 
959
990
 
960
991
  # ---------------------------------------------------------------- 记忆记录
@@ -4161,17 +4192,43 @@ def assoc_auto(weight: float = 0.8, dry_run: bool = False) -> dict:
4161
4192
  "pairs": added[:20]}
4162
4193
 
4163
4194
 
4164
- def assoc_graph(limit: int = 300) -> dict:
4195
+ # 联想图的边密度闸门。为什么需要(实测 2026-11-27):本机 165 条记忆、
4196
+ # 自动联想产生 **9278 条边**(密度 65%,完全图才 13530),前端力导向必然坍缩成一个毛球
4197
+ # 并且卡死。根因不是"记忆多",而是 **两个存档流程标签**:
4198
+ # 「封存」挂在 135 条记忆上(80.4%)→ 单这一个桶就是 135×134/2 = 9045 对
4199
+ # 「即记」挂在 103 条(61.3%) → 再 5253 对
4200
+ # 这类标签描述的是**存储动作**,不是内容关联,不该被当成"相关"。
4201
+ #
4202
+ # 处理分两道(都是数据驱动、不写死具体标签名,换库/换语言也成立):
4203
+ # 1. 泛标签闸:某个标签/实体覆盖了超过 GRAPH_GENERIC_RATIO 的节点 → 视为元数据,
4204
+ # 不参与两两配对。实测阈值 15% 是自然断点:封存/即记/会话存档 全部被拦下,
4205
+ # 边从 9278 → 68(-99.3%),剩下的结构是真实相关的。
4206
+ # 2. 度数闸:单节点自动边只留最强的 GRAPH_MAX_DEGREE 条(Gephi 的 Degree Filter
4207
+ # 等价物;k-core 掉到 1 时仍能保证稀疏)。
4208
+ GRAPH_GENERIC_RATIO = 0.15 # 覆盖超过 15% 节点的标签/实体 = 元数据,不参与联想
4209
+ GRAPH_MAX_DEGREE = 6 # 单节点最多保留的自动联想边数
4210
+
4211
+
4212
+ def assoc_graph(limit: int = 300, generic_ratio: float | None = None,
4213
+ max_degree: int | None = None, hide_isolated: bool = False) -> dict:
4165
4214
  """联想图谱数据:面板 3D 空间用的节点与关联边。
4166
4215
 
4167
- v2.32 起两处升级(均为自动,无需手动连线):
4216
+ v2.32 起三处升级(均为自动,无需手动连线):
4168
4217
  * 人格中心:虚构一个 __persona__ 中心节点,与所有非淡忘记忆自动连边——
4169
4218
  图谱以人格为星核呈放射状,一眼看出"哪些记忆离我最近"。
4170
4219
  * 自动联想:共享实体/标签的记忆对之间补自动边(复用 assoc_auto 的
4171
4220
  计划逻辑但只读不落盘),图谱显示的关联远多于手工 link 的存量边。
4221
+ * **边密度闸门**(v3.48):泛标签(覆盖 >15% 节点,如「封存」「即记」)
4222
+ 不参与配对;单节点自动边只留最强 6 条。没有这道闸,几百条记忆就会把
4223
+ 图连成 9000+ 边的毛球,既看不出结构也画不动。
4172
4224
 
4173
4225
  节点上限 limit(默认 300,太多画不动);边只保留两端都在图里的。
4226
+ 返回里的 `pruned`/`generic_buckets` 是给面板显示"为什么边这么少"用的,
4227
+ 不隐藏事实:关掉闸门会是什么规模,一眼可见。
4174
4228
  """
4229
+ ratio = GRAPH_GENERIC_RATIO if generic_ratio is None else float(generic_ratio)
4230
+ maxdeg = GRAPH_MAX_DEGREE if max_degree is None else int(max_degree)
4231
+
4175
4232
  records = [m for m in load_all() if m.get("layer") != "dust"]
4176
4233
  records.sort(key=lambda m: (_num(m.get("importance"), 0.5),
4177
4234
  float(retention(m))), reverse=True)
@@ -4183,8 +4240,9 @@ def assoc_graph(limit: int = 300) -> dict:
4183
4240
  edges.append({"src": r["src"], "dst": r["dst"],
4184
4241
  "relation": r.get("relation", "相关"),
4185
4242
  "weight": float(r.get("weight", 1))})
4243
+ manual_edges = len(edges) # 手工连线永远保留,不受下面两道闸影响
4186
4244
  seen_edges = {(e["src"], e["dst"]) for e in edges}
4187
- # 自动联想边(只读计划,不落盘——面板每次刷新重算,落盘交给 assoc_auto)
4245
+
4188
4246
  # 倒排索引:实体/标签 -> 记忆 id 集合。两两组合只发生在同一桶内,
4189
4247
  # 复杂度从 O(P×(E+T)) 降到 Σ(桶内两两),记忆多了不再卡面板。
4190
4248
  by_ent, by_tag = {}, {}
@@ -4193,30 +4251,90 @@ def assoc_graph(limit: int = 300) -> dict:
4193
4251
  by_ent.setdefault(e, set()).add(m["id"])
4194
4252
  for t in m.get("tags", []):
4195
4253
  by_tag.setdefault(t, set()).add(m["id"])
4196
- buckets = list(by_ent.values()) + list(by_tag.values())
4197
- auto_pairs = set()
4198
- for bucket in buckets:
4254
+
4255
+ n_nodes = max(1, len(nodes))
4256
+ generic_buckets = [] # 被判为元数据的标签/实体(附覆盖数,便于排错)
4257
+ buckets = [] # (bucket_key, id_set)
4258
+ for kind, table in (("标签", by_tag), ("实体", by_ent)):
4259
+ for name, bucket in table.items():
4260
+ if len(bucket) < 2:
4261
+ continue
4262
+ if len(bucket) / n_nodes > ratio:
4263
+ generic_buckets.append({"kind": kind, "name": name,
4264
+ "count": len(bucket),
4265
+ "ratio": round(len(bucket) / n_nodes, 3)})
4266
+ continue
4267
+ buckets.append(bucket)
4268
+ generic_buckets.sort(key=lambda x: -x["count"])
4269
+
4270
+ # 每条候选边的权重 = 两端共享的桶数(共享的标签/实体越多越相关)
4271
+ pair_weight: dict[tuple, int] = {}
4272
+ owner: dict[str, set] = {} # id -> 命中的桶下标集合(算共享数用)
4273
+ for bi, bucket in enumerate(buckets):
4199
4274
  bl = sorted(bucket)
4200
4275
  for i, a in enumerate(bl):
4276
+ owner.setdefault(a, set()).add(bi)
4201
4277
  for b in bl[i + 1:]:
4278
+ owner.setdefault(b, set()).add(bi)
4202
4279
  key = (a, b) if a < b else (b, a)
4203
- if key not in seen_edges:
4204
- auto_pairs.add(key)
4205
- for a, b in auto_pairs:
4206
- # 共享的实体/标签越多边越粗(权重 = 共享桶数,封顶 3)
4207
- w = sum(1 for bucket in buckets if a in bucket and b in bucket)
4280
+ if key in seen_edges:
4281
+ continue
4282
+ pair_weight[key] = pair_weight.get(key, 0) + 1
4283
+
4284
+ # 度数闸:优先保留"共享桶多(更相关)+ 两端总度数低(更稀缺)"的边,
4285
+ # 贪心填到每个节点 maxdeg 为止——避免大节点吃掉所有名额。
4286
+ degree_seen: dict[str, int] = {}
4287
+ kept = []
4288
+ for (a, b), w in sorted(pair_weight.items(),
4289
+ key=lambda kv: (-kv[1], kv[0])):
4290
+ if maxdeg and (degree_seen.get(a, 0) >= maxdeg or degree_seen.get(b, 0) >= maxdeg):
4291
+ continue
4292
+ kept.append((a, b, w))
4293
+ degree_seen[a] = degree_seen.get(a, 0) + 1
4294
+ degree_seen[b] = degree_seen.get(b, 0) + 1
4295
+ for a, b, w in kept:
4208
4296
  edges.append({"src": a, "dst": b, "relation": "相关",
4209
- "weight": min(3.0, 0.8 * w), "auto": True})
4210
- # 人格中心节点:星核,连向所有展示的记忆(权重随重要度,重要的连线更亮)
4297
+ "weight": min(3.0, 0.8 * max(1, w)),
4298
+ "auto": True, "shared": w})
4299
+
4300
+ # 人格中心节点:星核。**不连全部记忆**——那是另一条"必成毛球"的路:
4301
+ # 300 个节点各连一根,中心点的视觉权重会盖过一切,且弹簧把全图拽向一点。
4302
+ # 改为只连"重要度高 + 自身已出现在联想里"的那一小撮(最多 GRAPH_MAX_DEGREE×2),
4303
+ # 星核仍然是视觉中心,但不再主导力学。
4211
4304
  persona_id = "__persona__"
4212
4305
  import persona as _persona_mod # 延迟导入避免循环依赖
4213
4306
  p = _persona_mod.load_persona()
4307
+
4308
+ # 孤立记忆闸(v3.48):没有真实关联的记忆只留一个点,但它的**斥力还在**——
4309
+ # 137 个孤立节点会把 32 个有结构的节点挤成一坨,视觉上还是那个毛球。
4310
+ # 所以默认把它们整批排除出图(前端可一键「显示全部」重新拉)。
4311
+ isolated_hidden = 0
4312
+ if hide_isolated:
4313
+ linked = set()
4314
+ for a, b, _w in kept:
4315
+ linked.add(a)
4316
+ linked.add(b)
4317
+ for e in edges:
4318
+ if not e.get("auto"):
4319
+ linked.add(e["src"])
4320
+ linked.add(e["dst"])
4321
+ before = len(nodes)
4322
+ nodes = [m for m in nodes if m["id"] in linked]
4323
+ isolated_hidden = before - len(nodes)
4324
+
4214
4325
  nodes.insert(0, {"id": persona_id, "gist": "人格 · " + (p.get("name") or "砚"),
4215
4326
  "kind": "persona", "layer": "persona",
4216
4327
  "importance": 1.0, "emotion": "", "recency": 1.0})
4217
- for m in nodes[1:]:
4328
+ hub_cap = max(4, maxdeg * 2) if maxdeg else len(nodes)
4329
+ hub_ids = {i for pair in kept for i in pair[:2]}
4330
+ hub_targets = sorted(nodes[1:], key=lambda m: -_num(m.get("importance"), 0.5))
4331
+ # 优先连"已经在联想网里"的高重要度记忆,补足到 hub_cap
4332
+ hub_targets.sort(key=lambda m: (m["id"] not in hub_ids, -_num(m.get("importance"), 0.5)))
4333
+ for m in hub_targets[:hub_cap]:
4218
4334
  edges.append({"src": persona_id, "dst": m["id"], "relation": "自我",
4219
4335
  "weight": 0.4 + _num(m.get("importance"), 0.5), "auto": True})
4336
+ kept_ids = {n["id"] for n in nodes}
4337
+ edges = [e for e in edges if e["src"] in kept_ids and e["dst"] in kept_ids]
4220
4338
  return {
4221
4339
  "nodes": [{"id": m["id"], "gist": m.get("gist") or heuristic_gist(m.get("text", "")),
4222
4340
  "kind": m.get("kind", ""), "layer": m.get("layer", "hippo"),
@@ -4226,6 +4344,20 @@ def assoc_graph(limit: int = 300) -> dict:
4226
4344
  "edges": edges,
4227
4345
  "connected": len({e["src"] for e in edges} - {persona_id}
4228
4346
  | {e["dst"] for e in edges} - {persona_id}),
4347
+ # 闸门透明化:面板要能说"为什么这么少",而不是让人以为丢数据了
4348
+ "stats": {
4349
+ "nodes": len(nodes),
4350
+ "edges": len(edges),
4351
+ "manual": manual_edges,
4352
+ "auto_candidates": len(pair_weight),
4353
+ "auto_kept": len(kept),
4354
+ "generic_ratio": ratio,
4355
+ "max_degree": maxdeg,
4356
+ "generic_buckets": generic_buckets[:12],
4357
+ "generic_bucket_count": len(generic_buckets),
4358
+ "hide_isolated": bool(hide_isolated),
4359
+ "isolated_hidden": isolated_hidden,
4360
+ },
4229
4361
  }
4230
4362
 
4231
4363
  # ---------------------------------------------------------------- 上下文注入
@@ -551,6 +551,19 @@ def _migrate_home(target_raw: str) -> dict:
551
551
  raise ValueError("目标目录不能为空")
552
552
  if target == brain.HOME.resolve():
553
553
  raise ValueError("目标目录与当前数据目录相同")
554
+ # ★ 目标不能落在数据目录**内部**(审计 panel_server.py:559):
555
+ # `copytree(HOME, target)` 时目标若在 HOME 底下,copytree 边复制边把刚创建的
556
+ # 目标目录自己也扫进去 → 递归膨胀,或中途 OSError 留下一份半截副本,
557
+ # 而且此时指针文件还没写,用户会得到一个"看起来迁好了、其实不完整"的目录。
558
+ # CLI 的 `home move` 有这道检查(relative_to 直接拒),这里漏了。
559
+ try:
560
+ target.relative_to(brain.HOME.resolve())
561
+ except ValueError:
562
+ pass # 不在内部,正常
563
+ else:
564
+ raise ValueError(
565
+ "目标目录在数据目录内部——复制时会把目标自己也扫进去(递归膨胀)。"
566
+ f"请选数据目录之外的路径(当前数据目录:{brain.HOME})")
554
567
  if target.exists() and any(target.iterdir()):
555
568
  raise ValueError("目标目录已存在且非空——请选一个空目录(或先手动清理)")
556
569
  # 计划写指针的位置必须可写:指针文件永远在默认位置 ~/.brain-memory/ 下
@@ -909,7 +922,26 @@ class Handler(BaseHTTPRequestHandler):
909
922
  return
910
923
  if path == "/api/graph":
911
924
  limit = _int_param(url, "limit", 300, 10, 800)
912
- self._json(brain.assoc_graph(limit))
925
+ # v3.48 联想图密度闸门:把"元数据标签不算关联""单节点边数上限"
926
+ # "孤立记忆是否入图"三个开关暴露出来,面板可调、也可用它自查边爆炸。
927
+ qs = parse_qs(url.query)
928
+ def _flag(name: str, default: bool) -> bool:
929
+ v = (qs.get(name) or [""])[0].strip().lower()
930
+ if not v:
931
+ return default
932
+ return v not in ("0", "false", "no", "off")
933
+ def _num(name: str, default):
934
+ v = (qs.get(name) or [""])[0].strip()
935
+ try:
936
+ return float(v)
937
+ except (TypeError, ValueError):
938
+ return default
939
+ self._json(brain.assoc_graph(
940
+ limit,
941
+ generic_ratio=_num("generic_ratio", None),
942
+ max_degree=_num("max_degree", None),
943
+ hide_isolated=_flag("hide_isolated", True),
944
+ ))
913
945
  return
914
946
  if path == "/api/diagnostics":
915
947
  # 自诊断:死链 / 冲突未裁决 / 数据膨胀 / 淡忘可逆状态 / 来源归属完整率
@@ -2578,6 +2610,28 @@ def ollama_status() -> dict:
2578
2610
  return st
2579
2611
 
2580
2612
 
2613
+ def _ollama_write_embed_cfg() -> None:
2614
+ """在 `config.json` 写锁内把 Ollama 的 embed 配置写进去。
2615
+
2616
+ 审计 panel_server.py:2599:Ollama 的 enable / setup / install / auto_probe
2617
+ 原来都是 `brain.load_config()` → 改 `embed` → `brain.atomic_json(config.json)`
2618
+ **整份回写**,绕开了 `config_set` / `_set_cfg_path` 用的
2619
+ `_locked(HOME / "config.json")`。与设置页保存或 CLI `config set` 并发时,
2620
+ 后写者会把对方刚设的 token / 阈值 / 档位静默覆盖掉——用户改完设置发现又变回去,
2621
+ 却找不到原因。
2622
+
2623
+ 统一走这里:读-改-写在同一个锁内完成,和 `_set_cfg_path` 同一互斥口径。
2624
+ `_locked` 可重入,所以外层若已持锁也不会死锁。
2625
+ """
2626
+ with brain._locked(brain.HOME / "config.json"):
2627
+ cfg = brain.load_config()
2628
+ embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
2629
+ embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
2630
+ embed["model"] = _OLLAMA_MODEL
2631
+ cfg["embed"] = embed
2632
+ brain.atomic_json(brain.HOME / "config.json", cfg)
2633
+
2634
+
2581
2635
  def _api_ollama_enable(self, path, data):
2582
2636
  """自动探测接管:Ollama 已在跑但没接入灵枢时,一键写好 embed 配置。
2583
2637
  模型没拉则先拉(同步,拉模型耗时可观但属于用户显式点按钮)。"""
@@ -2591,12 +2645,7 @@ def _api_ollama_enable(self, path, data):
2591
2645
  if not _ollama_pull_model():
2592
2646
  self._json({"ok": False, "error": f"模型 {_OLLAMA_MODEL} 拉取失败"}, 502)
2593
2647
  return
2594
- cfg = brain.load_config()
2595
- embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
2596
- embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
2597
- embed["model"] = _OLLAMA_MODEL
2598
- cfg["embed"] = embed
2599
- brain.atomic_json(brain.HOME / "config.json", cfg)
2648
+ _ollama_write_embed_cfg()
2600
2649
  self._json({"ok": True, "stage": "done"})
2601
2650
  except Exception as exc:
2602
2651
  self._log_write_failure("ollama enable", exc, 500)
@@ -2652,12 +2701,7 @@ def _ollama_setup_async() -> None:
2652
2701
  _ollama_state_write("error", detail=f"模型 {_OLLAMA_MODEL} 拉取失败(网络或磁盘问题)")
2653
2702
  return
2654
2703
  # ④ 写 embed 配置启用向量(与 enable/install 同款读-改-写)
2655
- cfg = brain.load_config()
2656
- embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
2657
- embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
2658
- embed["model"] = _OLLAMA_MODEL
2659
- cfg["embed"] = embed
2660
- brain.atomic_json(brain.HOME / "config.json", cfg)
2704
+ _ollama_write_embed_cfg()
2661
2705
  _ollama_state_write("done", percent=100, detail="语义召回已就绪(真模型向量)")
2662
2706
  except Exception as exc:
2663
2707
  _ollama_state_write("error", detail=f"一键流程失败:{exc}")
@@ -2742,24 +2786,14 @@ def _ollama_auto_probe() -> None:
2742
2786
  # 服务在跑但灵枢还没接入 → 接管写配置
2743
2787
  if not _ollama_embed_configured():
2744
2788
  if _OLLAMA_MODEL in _ollama_model_names():
2745
- cfg = brain.load_config()
2746
- embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
2747
- embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
2748
- embed["model"] = _OLLAMA_MODEL
2749
- cfg["embed"] = embed
2750
- brain.atomic_json(brain.HOME / "config.json", cfg)
2789
+ _ollama_write_embed_cfg()
2751
2790
  return
2752
2791
  # 模型没拉:整个生命周期只自动 pull 一次(避免反复打扰/重复下载)
2753
2792
  if _AUTO_PROBE_STATE["pulled"]:
2754
2793
  return
2755
2794
  _AUTO_PROBE_STATE["pulled"] = True
2756
2795
  if _ollama_pull_model():
2757
- cfg = brain.load_config()
2758
- embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
2759
- embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
2760
- embed["model"] = _OLLAMA_MODEL
2761
- cfg["embed"] = embed
2762
- brain.atomic_json(brain.HOME / "config.json", cfg)
2796
+ _ollama_write_embed_cfg()
2763
2797
  except Exception:
2764
2798
  pass # 探测接管是锦上添花:任何失败都静默,降级兜底照常
2765
2799
  finally:
@@ -2832,12 +2866,7 @@ def _ollama_install_async() -> None:
2832
2866
  _ollama_state_write("error", detail=f"模型 {_OLLAMA_MODEL} 拉取失败(网络或磁盘问题)")
2833
2867
  return
2834
2868
  # 写 embed 配置:config_set 是扁平键,embed 是嵌套对象,读-改-写整段 config.json
2835
- cfg = brain.load_config()
2836
- embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
2837
- embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
2838
- embed["model"] = _OLLAMA_MODEL
2839
- cfg["embed"] = embed
2840
- brain.atomic_json(brain.HOME / "config.json", cfg)
2869
+ _ollama_write_embed_cfg()
2841
2870
  _ollama_state_write("done", percent=100, detail="语义召回已就绪")
2842
2871
  except Exception as exc:
2843
2872
  _ollama_state_write("error", detail=f"安装失败:{exc}")