lingshu-skill 5.41.0 → 5.43.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.
@@ -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
@@ -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": "向量请求超时(秒)",
@@ -341,6 +341,24 @@ def load_persona() -> dict:
341
341
 
342
342
 
343
343
  def save_persona(p: dict) -> None:
344
+ # 空人格写盘守卫(2026-12-03 两次清空事故加固):
345
+ # 盘上已有完整人格(有名字)时,拒绝用 identity+traits 双空的默认态覆盖——
346
+ # 除非是 init --force 的显式重置(调用方传 _allow_empty=True 绕过)。
347
+ # 竞态窗口(测试进程写空态、后台做梦并发 save)由此被彻底堵死。
348
+ try:
349
+ _path = HOME / "persona.json"
350
+ if _path.exists():
351
+ _disk = _slurp_json(_path) or {}
352
+ _disk_named = bool(((_disk.get("identity") or {}).get("名字") or "").strip())
353
+ _incoming_named = bool(((p.get("identity") or {}).get("名字") or "").strip())
354
+ if _disk_named and not _incoming_named and not p.get("_allow_empty"):
355
+ log_event("persona",
356
+ "拒绝保存:盘上人格有名字而待写入人格为空态——疑似竞态覆盖,已拦下。"
357
+ "若确要重置请用 brain.py init --force(自带备份)。",
358
+ level="error")
359
+ return
360
+ except Exception:
361
+ pass # 守卫自身绝不阻塞正常保存
344
362
  with _locked(HOME / "persona.json"):
345
363
  atomic_json(HOME / "persona.json", p)
346
364