lingshu-skill 0.0.0-stage → 3.79.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 (135) hide show
  1. package/CHANGELOG.md +2571 -0
  2. package/LICENSE +21 -0
  3. package/README.md +698 -3
  4. package/SKILL-lite.md +45 -0
  5. package/SKILL-tiny.md +37 -0
  6. package/SKILL.md +379 -0
  7. package/assets/panel.html +5616 -0
  8. package/cordis-plugin/lingshu-cron/cordis.patch.yml +3 -0
  9. package/cordis-plugin/lingshu-cron/index.js +4 -0
  10. package/cordis-plugin/lingshu-cron/package.json +34 -0
  11. package/cordis-plugin/lingshu-cron/plugin.js +1040 -0
  12. package/cordis-plugin/lingshu-guard/plugin.js +473 -0
  13. package/cordis-plugin/lingshu-im/plugin.js +635 -0
  14. package/cordis-plugin/lingshu-startup/README.md +123 -0
  15. package/cordis-plugin/lingshu-startup/cordis.patch.yml +3 -0
  16. package/cordis-plugin/lingshu-startup/index.js +4 -0
  17. package/cordis-plugin/lingshu-startup/package.json +25 -0
  18. package/cordis-plugin/lingshu-startup/plugin.js +352 -0
  19. package/cordis.patch.yml +3 -0
  20. package/docs/commands.md +243 -0
  21. package/docs/mechanics.md +610 -0
  22. package/docs/models.md +52 -0
  23. package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +49 -0
  24. package/docs/panel-api.md +198 -0
  25. package/docs/recovery.md +90 -0
  26. package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +53 -0
  27. package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +802 -0
  28. package/index.js +102 -0
  29. package/package.json +52 -6
  30. package/scripts/_panel_smoke_v299.py +27 -0
  31. package/scripts/_smoke_v299.py +31 -0
  32. package/scripts/_sync_trae_cn.py +34 -0
  33. package/scripts/assembler.py +197 -0
  34. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +53 -0
  35. package/scripts/astrbot_plugin_lingshu/PATCH_NOTES.md +28 -0
  36. package/scripts/astrbot_plugin_lingshu/README.md +58 -0
  37. package/scripts/astrbot_plugin_lingshu/_conf_schema.json +92 -0
  38. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +2571 -0
  39. package/scripts/astrbot_plugin_lingshu/engine/README.md +698 -0
  40. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +45 -0
  41. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +37 -0
  42. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +379 -0
  43. package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +5616 -0
  44. package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +243 -0
  45. package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -0
  46. package/scripts/astrbot_plugin_lingshu/engine/docs/models.md +52 -0
  47. package/scripts/astrbot_plugin_lingshu/engine/docs/panel-api.md +198 -0
  48. package/scripts/astrbot_plugin_lingshu/engine/docs/recovery.md +90 -0
  49. package/scripts/astrbot_plugin_lingshu/engine/scripts/_panel_smoke_v299.py +27 -0
  50. package/scripts/astrbot_plugin_lingshu/engine/scripts/_smoke_v299.py +31 -0
  51. package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +34 -0
  52. package/scripts/astrbot_plugin_lingshu/engine/scripts/assembler.py +197 -0
  53. package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +280 -0
  54. package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +192 -0
  55. package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +46 -0
  56. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +55 -0
  57. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +215 -0
  58. package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +165 -0
  59. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +4850 -0
  60. package/scripts/astrbot_plugin_lingshu/engine/scripts/context_ab.py +260 -0
  61. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2025 -0
  62. package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +1137 -0
  63. package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +1180 -0
  64. package/scripts/astrbot_plugin_lingshu/engine/scripts/failures.py +107 -0
  65. package/scripts/astrbot_plugin_lingshu/engine/scripts/fallback_embed.py +114 -0
  66. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +4745 -0
  67. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth_parts.py +263 -0
  68. package/scripts/astrbot_plugin_lingshu/engine/scripts/insights.py +131 -0
  69. package/scripts/astrbot_plugin_lingshu/engine/scripts/make_dsh_tgz.py +92 -0
  70. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +242 -0
  71. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +159 -0
  72. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_lesson.py +160 -0
  73. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +210 -0
  74. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_topic.py +177 -0
  75. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +4352 -0
  76. package/scripts/astrbot_plugin_lingshu/engine/scripts/npm_prepack.py +31 -0
  77. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +115 -0
  78. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +609 -0
  79. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +2703 -0
  80. package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +591 -0
  81. package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2309 -0
  82. package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +195 -0
  83. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +368 -0
  84. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +736 -0
  85. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +228 -0
  86. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +123 -0
  87. package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +252 -0
  88. package/scripts/astrbot_plugin_lingshu/main.py +703 -0
  89. package/scripts/astrbot_plugin_lingshu/make_checksums.py +87 -0
  90. package/scripts/astrbot_plugin_lingshu/metadata.yaml +7 -0
  91. package/scripts/behavior_baseline.py +280 -0
  92. package/scripts/bench.py +192 -0
  93. package/scripts/brain.py +46 -0
  94. package/scripts/check_pressure_sync.py +55 -0
  95. package/scripts/check_tag.py +215 -0
  96. package/scripts/check_version.py +265 -0
  97. package/scripts/checkpoint.py +165 -0
  98. package/scripts/cli.py +4850 -0
  99. package/scripts/context_ab.py +260 -0
  100. package/scripts/core.py +2025 -0
  101. package/scripts/dream.py +1137 -0
  102. package/scripts/emotion.py +1180 -0
  103. package/scripts/failures.py +107 -0
  104. package/scripts/fallback_embed.py +114 -0
  105. package/scripts/growth.py +4745 -0
  106. package/scripts/growth_parts.py +263 -0
  107. package/scripts/hooks/pre-commit +18 -0
  108. package/scripts/hooks/pre-push +20 -0
  109. package/scripts/insights.py +131 -0
  110. package/scripts/make_dsh_tgz.py +92 -0
  111. package/scripts/make_manifest.py +254 -0
  112. package/scripts/make_plugin_zip.py +88 -0
  113. package/scripts/mem_dialogue.py +242 -0
  114. package/scripts/mem_embed.py +159 -0
  115. package/scripts/mem_lesson.py +160 -0
  116. package/scripts/mem_score.py +210 -0
  117. package/scripts/mem_topic.py +177 -0
  118. package/scripts/memory.py +4352 -0
  119. package/scripts/npm_prepack.py +31 -0
  120. package/scripts/panel_build.py +115 -0
  121. package/scripts/panel_cloud.py +609 -0
  122. package/scripts/panel_server.py +2703 -0
  123. package/scripts/panels.py +591 -0
  124. package/scripts/persona.py +2309 -0
  125. package/scripts/recreate_push.ps1 +117 -0
  126. package/scripts/retriever.py +195 -0
  127. package/scripts/run_tests.py +91 -0
  128. package/scripts/safety.py +368 -0
  129. package/scripts/session_import.py +736 -0
  130. package/scripts/session_rag.py +228 -0
  131. package/scripts/session_summary.py +123 -0
  132. package/scripts/summarizer.py +252 -0
  133. package/scripts/sync_engine.py +139 -0
  134. package/scripts/update_dsh_copy.ps1 +107 -0
  135. package/start-panel.bat +60 -0
@@ -0,0 +1,1137 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """灵枢 —— 灵枢 · 做梦:聚类巩固、梦境应用与报告。"""
4
+
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import hashlib
9
+ import json
10
+ import math
11
+ import os
12
+ import re
13
+ import shutil
14
+ import sys
15
+ import threading
16
+ import time
17
+ import zipfile
18
+ from contextlib import contextmanager, nullcontext
19
+ from datetime import datetime
20
+ from pathlib import Path
21
+
22
+ from core import *
23
+
24
+ import core # 可变路径(WORKING_FILE 等)必须走 core.X:import * 是快照,切 HOME 后会过期
25
+
26
+ import memory as _mem # load_all / save_all / retention / 归档等(模块级延迟引用避免循环)
27
+
28
+ # ---------------------------------------------------------------- 做梦 / 巩固
29
+
30
+ # 聚类池上限:记忆多了之后 O(n²) 两两比对会拖垮每晚的巩固,
31
+ # 超过就按重要度取前 N 条,剩下的留到下轮(反正 consolidate 是按批推进的)。
32
+ _MAX_CLUSTER_POOL = 400
33
+
34
+ # 孤儿梦任务时效:pending 生成后超过这么久还没被 apply,视为孤儿任务。
35
+ # 未到期前重复触发不覆盖(沿用旧任务),到期后归档再开新任务。
36
+ _DREAM_ORPHAN_TTL = 48 * 3600
37
+
38
+ # 重放池上限:上次做梦之后的新记忆 + 未完成工作记忆,太多就取最近的
39
+ _REPLAY_MAX = 30
40
+
41
+ # 交接摘要目录:做梦时把重放线索压成结构化交接(借鉴 dsh-handoff-compaction:
42
+ # 老上下文→结构化摘要,最近细节原样保留在记忆库里,可 recall 追溯,不破坏原始数据)
43
+ # 保留最近 10 份,旧的自动清理。
44
+
45
+ # 分模式压缩策略(联动面板 AI/工程/拟人/自动模式):
46
+ # work(工程模式)——骨架压缩:少淡化、少淡忘,代码/报错/路径类细节保真;
47
+ # human(拟人模式)——摘要压缩:细节可放心淡化,人设与情绪要点保住即可;
48
+ # auto 按当前话题判定落到上面两档。
49
+ _COMPACTION_POLICY = {
50
+ "work": {
51
+ "detail_floor": 0.55, # detail 淡化下限:骨架信息不打太薄
52
+ "dust_retention_shift": 0.10, # 淡忘判据加严:R 要再低 0.10 才进淡忘区
53
+ "desc": "工程模式:骨架压缩——代码/报错/路径类细节保真,淡忘加严",
54
+ },
55
+ "human": {
56
+ "detail_floor": 0.0,
57
+ "dust_retention_shift": 0.0,
58
+ "desc": "拟人模式:摘要压缩——细节可淡化,要点与人设保住即可",
59
+ },
60
+ }
61
+
62
+
63
+ def _num(v, default: float = 0.0) -> float:
64
+ """把 None/字符串/坏值安全转成 float(与 memory._num 同语义,避免环形 import)。"""
65
+ if v is None or isinstance(v, bool):
66
+ return float(default)
67
+ try:
68
+ f = float(v)
69
+ return default if (f != f) else f # NaN 检查
70
+ except (TypeError, ValueError):
71
+ return float(default)
72
+
73
+
74
+ def compaction_policy(mode: str = "") -> dict:
75
+ """按会话模式取压缩策略(auto 时按话题判定,拿不到就当 human)。"""
76
+ try:
77
+ if not mode:
78
+ mode = resolve_mode("")
79
+ except Exception:
80
+ mode = "human"
81
+ pol = _COMPACTION_POLICY.get(mode)
82
+ if not pol:
83
+ mode = "human"
84
+ pol = _COMPACTION_POLICY["human"]
85
+ out = dict(pol)
86
+ out["mode"] = mode
87
+ return out
88
+
89
+
90
+ def replay_recent(limit: int = _REPLAY_MAX) -> list:
91
+ """重放:把「上次做梦之后」的经历线索按时间倒序拼出来(做梦前的快速眼动)。
92
+
93
+ 来源:新写入的记忆(hippo/cortex,跳过 dust)+ 工作记忆里还没做完的事。
94
+ 只读不改库——重放是做梦的输入,不是对记忆的修改。
95
+ """
96
+ last = _num(load_dream_state().get("last_dream"), 0)
97
+ now = now_ts()
98
+ items = []
99
+ for m in load_all():
100
+ if not m.get("id") or m.get("layer") == "dust":
101
+ continue
102
+ if last and _num(m.get("created"), 0) < last:
103
+ continue
104
+ items.append({"id": m["id"], "kind": m.get("kind", ""),
105
+ "text": (m.get("text") or "")[:200],
106
+ "ts": _num(m.get("created"), 0), "from": "memory"})
107
+ try:
108
+ for r in read_jsonl(core.WORKING_FILE):
109
+ if not r.get("open", True):
110
+ continue
111
+ ts = _num(r.get("ts"), 0)
112
+ if now - ts > 12 * HOUR:
113
+ continue
114
+ items.append({"id": "", "kind": "working",
115
+ "text": (r.get("text") or "")[:200],
116
+ "ts": ts, "from": "working"})
117
+ except Exception:
118
+ pass
119
+ items.sort(key=lambda x: x["ts"], reverse=True)
120
+ return items[:max(1, int(limit))]
121
+
122
+
123
+ def build_handoff(items: list, mode: str = "") -> dict:
124
+ """压缩:重放线索 → 结构化交接摘要(状态 / 要点 / 未决 / 下一步)。
125
+
126
+ 只生成摘要、不动原始数据:原文仍在记忆库里,下个会话可以 recall 追溯。
127
+ 工程模式保「未决/下一步」优先(干活导向),拟人模式保「要点」优先(陪伴导向)。
128
+ """
129
+ pol = compaction_policy(mode)
130
+ memories = [x for x in items if x.get("from") == "memory"]
131
+ workings = [x for x in items if x.get("from") == "working"]
132
+ # 要点:按 kind 分组取代表,工程模式优先 fact/insight/mistake,拟人模式优先 emotion/relationship
133
+ priority = ("fact", "insight", "mistake", "preference") if pol["mode"] == "work" \
134
+ else ("emotion", "relationship", "preference", "insight")
135
+ ranked = sorted(memories, key=lambda x: (priority.index(x["kind"]) if x["kind"] in priority else 99,
136
+ -x["ts"]))
137
+ points = [x["text"] for x in ranked[:6]]
138
+ todo = [x["text"] for x in workings[:5]]
139
+ summary = {
140
+ "at": now_ts(),
141
+ "mode": pol["mode"],
142
+ "replayed": len(items),
143
+ "状态": f"上次做梦后新增 {len(memories)} 条记忆、{len(workings)} 件未完成的事",
144
+ "要点": points,
145
+ "未决": todo,
146
+ "下一步": "下个会话开始时先处理「未决」事项;细节用 recall <关键词> 追原文",
147
+ }
148
+ return summary
149
+
150
+
151
+ def save_handoff(summary: dict) -> Path:
152
+ """交接摘要落盘(JSON,可检索),只保留最近 10 份。"""
153
+ d = HOME / "handoffs"
154
+ d.mkdir(parents=True, exist_ok=True)
155
+ path = d / f"handoff_{int(summary.get('at', now_ts()))}.json"
156
+ atomic_json(path, summary)
157
+ olds = sorted(d.glob("handoff_*.json"))
158
+ for old in olds[:-10]:
159
+ try:
160
+ old.unlink()
161
+ except OSError:
162
+ pass
163
+ return path
164
+
165
+
166
+ def latest_handoff() -> dict | None:
167
+ """最近一份交接摘要(注入用)。"""
168
+ d = HOME / "handoffs"
169
+ files = sorted(d.glob("handoff_*.json")) if d.exists() else []
170
+ if not files:
171
+ return None
172
+ try:
173
+ h = _slurp_json(files[-1])
174
+ return h if isinstance(h, dict) and h.get("要点") is not None else None
175
+ except Exception:
176
+ return None
177
+
178
+
179
+ def cluster_memories(records: list, max_clusters: int = 6, include_ids: set | None = None) -> list:
180
+ include_ids = include_ids or set()
181
+ # 无 id 的畸形记录没法做并查集/parent 映射,直接跳过。
182
+ # 这些记录会原样保留在库,不会被 save_all 丢掉。
183
+ # #41:correction 改口记录也不进聚类——合并成摘要=改口语境丢失,教训提炼读不到证据。
184
+ pool = [m for m in records if m.get("id") and m.get("layer") != "dust"
185
+ and not m.get("correction")
186
+ and (not m.get("consolidated") or m["id"] in include_ids)]
187
+ if not pool:
188
+ return []
189
+ if len(pool) > _MAX_CLUSTER_POOL:
190
+ pool = sorted(pool, key=lambda m: _num(m.get("importance"), 0), reverse=True)[:_MAX_CLUSTER_POOL]
191
+ parent = {m["id"]: m["id"] for m in pool}
192
+
193
+ def find(x):
194
+ while parent[x] != x:
195
+ parent[x] = parent[parent[x]]
196
+ x = parent[x]
197
+ return x
198
+
199
+ def union(a, b):
200
+ ra, rb = find(a), find(b)
201
+ if ra != rb:
202
+ parent[rb] = ra
203
+
204
+ term_map = {m["id"]: terms(m.get("text", "")) for m in pool}
205
+ for i, a in enumerate(pool):
206
+ for b in pool[i + 1:]:
207
+ shared = (set(a.get("entities", [])) & set(b.get("entities", [])) |
208
+ set(a.get("tags", [])) & set(b.get("tags", [])))
209
+ if shared or jaccard(term_map[a["id"]], term_map[b["id"]]) > 0.34:
210
+ union(a["id"], b["id"])
211
+
212
+ groups = {}
213
+ for m in pool:
214
+ groups.setdefault(find(m["id"]), []).append(m)
215
+
216
+ clusters = []
217
+ for gid, members in groups.items():
218
+ if len(members) < 2 and max(_num(m.get("importance")) for m in members) < 0.7:
219
+ continue
220
+ clusters.append(members)
221
+ clusters.sort(key=lambda g: (len(g) * max(_num(m.get("importance")) for m in g)), reverse=True)
222
+
223
+ out = []
224
+ now = now_ts()
225
+ for g in clusters[:max_clusters]:
226
+ out.append({
227
+ "ids": [m["id"] for m in g],
228
+ "texts": [{"id": m["id"], "kind": m.get("kind", "fact"),
229
+ "text": m.get("text", ""), "importance": m.get("importance", 0.5),
230
+ "age_days": round((now - _num(m.get("created"), now)) / DAY, 1)} for m in g],
231
+ "tags": _dedupe([t for m in g for t in m.get("tags", [])]),
232
+ "entities": _dedupe([e for m in g for e in m.get("entities", [])]),
233
+ })
234
+ return out
235
+
236
+
237
+ def _dream_snapshot() -> str:
238
+ """做梦改库前的自动快照(借鉴 sage-mem:整理前强制建回滚点)。
239
+
240
+ 只打包记忆相关的核心文件(hippocampus/assoc/archive 等),比全库 backup
241
+ 轻量得多;存在 ~/.brain-memory/dream-snapshots/ 下,保留最近 10 份。
242
+ 失败返回 "" 并记事件日志;调用方(dream)fail-closed:拿不到快照就拒绝整理。
243
+ """
244
+ snap_dir = HOME / "dream-snapshots"
245
+ try:
246
+ snap_dir.mkdir(parents=True, exist_ok=True)
247
+ base = f"dream-snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.zip"
248
+ path = snap_dir / base
249
+ k = 1
250
+ while path.exists():
251
+ k += 1
252
+ 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",
254
+ "knowledge.jsonl", "persona.json", "dream_state.json"]
255
+ with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as zf:
256
+ for name in core_files:
257
+ f = HOME / name
258
+ if f.is_file():
259
+ zf.write(f, name)
260
+ # 保留最近 10 份,旧的删掉
261
+ snaps = sorted(snap_dir.glob("dream-snap_*.zip"))
262
+ for p in snaps[:-10]:
263
+ try:
264
+ p.unlink()
265
+ except OSError:
266
+ pass
267
+ return str(path)
268
+ except Exception as exc:
269
+ try:
270
+ log_event("dream", f"做梦前自动快照失败:{exc}")
271
+ except Exception:
272
+ pass
273
+ return ""
274
+
275
+
276
+ _FLUFF_WORDS = ("本轮", "综上", "总结", "摘要", "回顾一下", "已完成", "以上是",
277
+ "以上为", "本次", "小结")
278
+ _ACTION_WORDS = ("别", "不要", "应该", "务必", "必须", "记得", "下次", "避免",
279
+ "改成", "改为", "注意", "优先", "禁止", "只能", "要用", "先", "再")
280
+
281
+
282
+ def _lesson_sentence(text: str, limit: int = 140) -> str:
283
+ """从自由文本里抽"可执行的一句"当教训;抽不出(纯摘要/套话)返回 ""。
284
+
285
+ 教训的价值在"下次能照着做",所以:
286
+ * 按句切分,优先挑带动作词(别/应该/务必/记得/改成…)的句子;
287
+ * 跳过摘要与收尾套话(本轮/综上/总结/已完成…)——它们不是教训;
288
+ * 到句号就停,不把一个完整结论拦腰截断;
289
+ * 一句都挑不出且原文够短(≤limit)才整句收下,否则放弃。
290
+ """
291
+ raw = re.sub(r"\s+", " ", (text or "").strip())
292
+ if not raw:
293
+ return ""
294
+ parts = [p.strip() for p in re.split(r"[。!?!?;;\n]+", raw) if p.strip()]
295
+ best, best_score = "", -1.0
296
+ for p in parts:
297
+ if len(p) < 8:
298
+ continue
299
+ score = sum(2.0 for w in _ACTION_WORDS if w in p)
300
+ score -= sum(3.0 for w in _FLUFF_WORDS if w in p)
301
+ # 太长的句子多半是叙事而不是结论,轻微降权
302
+ if len(p) > limit:
303
+ score -= 1.0
304
+ if score > best_score:
305
+ best, best_score = p, score
306
+ if best and best_score > 0:
307
+ return best[:limit].rstrip(",,、 ") + ("…" if len(best) > limit else "")
308
+ # 没有动作句:只有短文本才整条收下(长文本通常是摘要,不该进教训库)
309
+ if len(raw) <= 80 and not any(w in raw for w in _FLUFF_WORDS):
310
+ return raw
311
+ return ""
312
+
313
+
314
+ def _lesson_conf(base: float, evidence: int) -> float:
315
+ """置信度按证据条数分级:1 条=base,每多一条 +0.10,封顶 0.6。
316
+
317
+ 梦提炼的教训都还没被验证(validate 才会上调到 0.95),证据越多先验越强;
318
+ 固定 0.4 会让"3 条证据"和"孤证"一样不可信,审核时看不出优先级。
319
+ """
320
+ return round(min(0.6, base + 0.10 * max(0, int(evidence) - 1)), 2)
321
+
322
+
323
+ def _mine_lessons(records: list, max_lessons: int = 3) -> list:
324
+ """教训提炼(#36):扫描失败闭环证据源 → 生成待审教训候选。
325
+
326
+ 证据源(按优先级):
327
+ 1. correction=true 改口记录——用户亲手纠正,证据最强;
328
+ 2. 被 superseded_by 的旧记忆——结论错过一次被新事实取代;
329
+ 3. detect_conflicts 冲突对——两条记忆互相打架,其中带改口信号的当教训素材。
330
+ 每条教训 status="pending"(与 knowledge/persona 同一审核闸),
331
+ evidence 存证据记忆 id;confidence 走 _lesson_conf 按证据条数分级
332
+ (0.4 起步、封顶 0.6,梦提炼的先验:像,但没验证过)。
333
+ 文本一律经 _lesson_sentence 抽可执行句——摘要在教训库里没有可复用价值。
334
+ 返回本轮新建的教训(已入库,供梦报告引用)。
335
+ """
336
+ import memory as mem_mod
337
+ created = []
338
+ # 已有教训按词面近似去重:同一坑不反复提炼(confidence/文本近似即认为已记下)
339
+ existing = mem_mod.load_lessons()
340
+
341
+ def _dup(text: str) -> bool:
342
+ t = terms(text)
343
+ for l in existing + created:
344
+ if jaccard(t, terms(l.get("text", ""))) >= 0.55:
345
+ return True
346
+ return False
347
+
348
+ # 1) correction 改口记录:从改口原文里抽可执行的一句
349
+ corrections = [m for m in records
350
+ if m.get("correction") and m.get("id") and m.get("text", "").strip()]
351
+ for m in corrections[:max_lessons]:
352
+ text = _lesson_sentence(str(m.get("text", "")))
353
+ if not text or _dup(text):
354
+ continue
355
+ ev = [m["id"]]
356
+ created.append(mem_mod.add_lesson(
357
+ text, evidence=ev, confidence=_lesson_conf(0.4, len(ev)), status="pending"))
358
+ if len(created) >= max_lessons:
359
+ return created
360
+
361
+ # 2) 被 supersede 的旧记忆:旧结论被新事实取代 → 教训=新结论可信、旧的不可信
362
+ by_id = {m.get("id"): m for m in records if m.get("id")}
363
+ for m in records:
364
+ if len(created) >= max_lessons:
365
+ break
366
+ new_id = m.get("superseded_by")
367
+ if not new_id or m.get("layer") == "dust":
368
+ continue
369
+ newer = by_id.get(new_id)
370
+ if not newer or not str(newer.get("text", "")).strip():
371
+ continue
372
+ core = str(newer.get("text", "")).strip()
373
+ text = f"「{core[:120]}」已取代旧结论——别再按旧的说。"
374
+ if _dup(text):
375
+ continue
376
+ ev = [m["id"], new_id]
377
+ created.append(mem_mod.add_lesson(
378
+ text, evidence=ev, confidence=_lesson_conf(0.4, len(ev)), status="pending"))
379
+
380
+ # 3) 冲突对:带改口信号的那一侧是更新的事实,提炼成教训
381
+ try:
382
+ conflicts = mem_mod.detect_conflicts(limit=10)
383
+ except Exception as e:
384
+ log_event("dream", f"冲突扫描失败(跳过冲突类教训):{e}", level="warn")
385
+ conflicts = []
386
+ for c in conflicts:
387
+ if len(created) >= max_lessons:
388
+ break
389
+ # 时间新的那侧通常代表最新状态
390
+ pair = sorted((c.get("a") or {}, c.get("b") or {}),
391
+ key=lambda x: _num(x.get("ts"), 0), reverse=True)
392
+ newest = pair[0]
393
+ newest_rec = by_id.get(newest.get("id"))
394
+ text_src = (newest_rec or newest).get("text", "")
395
+ if not str(text_src).strip():
396
+ continue
397
+ text = f"关于矛盾信息:以最新的说法为准——{str(text_src).strip()[:120]}"
398
+ if _dup(text):
399
+ continue
400
+ ev = [x.get("id") for x in (c.get("a"), c.get("b")) if x.get("id")]
401
+ created.append(mem_mod.add_lesson(
402
+ text, evidence=ev, confidence=_lesson_conf(0.35, len(ev)), status="pending"))
403
+ return created
404
+
405
+
406
+ def dream_priority() -> dict:
407
+ """#47 按需做梦(SSGM 3.5):不用固定闹钟,而是每次做梦前先量一遍"记忆库健康度",
408
+ 决定今晚要重点做什么(巩固/淡忘/蒸馏/都不用做)。
409
+
410
+ 指标(全部只读,缺啥降啥):
411
+ - 未巩固新记忆数:hippo 里 consolidated 为假的 → 该巩固;
412
+ - 待整理梦任务是否已悬着 → 该先消费旧任务而不是生成新的;
413
+ - 工作记忆未完成件 → 该重放交接;
414
+ - 召回使用率(#17 指标):rate 明显偏低(<0.15 且 recalled≥20)说明召回
415
+ 塞了一堆没用的 → 该蒸馏/清理而不是继续囤;
416
+ - 距上次做梦时长 → 太久强制至少走一遍淡忘/归档。
417
+ 返回 {"score": 0-1 健康分, "actions": [按优先级排序的行动], "reasons": {...}}
418
+ """
419
+ actions: list[str] = []
420
+ reasons: dict = {}
421
+ score = 1.0
422
+
423
+ # 1) 未巩固的新记忆
424
+ recs = _mem.load_all()
425
+ now = now_ts()
426
+ uncons = [m for m in recs if m.get("layer") == "hippo" and not m.get("consolidated")
427
+ and not m.get("correction")]
428
+ reasons["unconsolidated"] = len(uncons)
429
+ if len(uncons) >= 5:
430
+ actions.append("consolidate")
431
+ score -= min(0.4, 0.05 * len(uncons))
432
+
433
+ # 2) 旧梦任务悬置
434
+ pending = load_dream_pending()
435
+ if pending and pending.get("task_id"):
436
+ age_h = (now - _num(pending.get("created"), now)) / 3600
437
+ reasons["pending_task_hours"] = round(age_h, 1)
438
+ if age_h >= 6:
439
+ actions.append("consume_pending")
440
+ score -= 0.2
441
+
442
+ # 3) 工作记忆堆积
443
+ try:
444
+ # 五-E:做梦顺带把做完超过一天的暂存条目物理归档(原文进 working-archive.jsonl)
445
+ try:
446
+ _mem.work_sweep()
447
+ except Exception:
448
+ pass
449
+ ws = _mem.work_status()
450
+ reasons["working_open"] = ws["open_count"]
451
+ if ws["open_count"] >= 3:
452
+ actions.append("replay_handoff")
453
+ score -= 0.15
454
+ except Exception:
455
+ pass
456
+
457
+ # 4) 召回使用率偏低 → 该蒸馏而非继续囤
458
+ try:
459
+ um = _mem.usage_metrics()
460
+ reasons["recall_rate"] = um.get("rate", 0.0)
461
+ if um.get("recalled", 0) >= 20 and um.get("rate", 1.0) < 0.15:
462
+ actions.append("distill")
463
+ score -= 0.25
464
+ except Exception:
465
+ pass
466
+
467
+ # 5) 距上次做梦太久——淡忘/归档例行公事不能停
468
+ last = _num(load_dream_state().get("last_dream"), 0)
469
+ gap_h = (now - last) / 3600 if last else 9999
470
+ reasons["hours_since_dream"] = round(gap_h, 1) if last else None
471
+ if last and gap_h >= 24 * 3:
472
+ actions.append("routine_forget")
473
+ score -= 0.15
474
+
475
+ # 6) 健康分还很高、也没攒够活 → 今晚可以不做
476
+ if not actions and score >= 0.9:
477
+ actions.append("skip")
478
+ reasons["verdict"] = "记忆库健康,无需做梦"
479
+
480
+ return {"score": round(max(0.0, min(1.0, score)), 2),
481
+ "actions": actions or ["consolidate"], "reasons": reasons}
482
+
483
+
484
+ def _bounded_growth(records: list, now: int) -> list:
485
+ """#40 记忆有界增长:非 dust 非归档条目超软上限(默认 3000)时,做梦流程里
486
+ 把超额部分按"低保留度 → 低重要度 → 越旧越先"排序雪藏进 archive 层
487
+ (原文保真、永不删,可 archive restore 回热)——总量近似恒定,只压缩不删。
488
+
489
+ 软上限可用 config `dream.capacity_cap` 覆盖。返回本次被归档的记录列表。
490
+ 保护名单与 _is_archivable 一致:pinned / verbatim / identity / correction / pending。
491
+ """
492
+ try:
493
+ cap = int(_num(load_config().get("dream.capacity_cap"), 3000))
494
+ except Exception:
495
+ cap = 3000
496
+ cap = max(cap, 100) # 防呆:设得太小也不至于清空热层
497
+ hot = [m for m in records if m.get("layer") in ("hippo", "cortex")]
498
+ over = len(hot) - cap
499
+ if over <= 0:
500
+ return []
501
+ # 排序依据:保留度低(快忘了)> 重要度低 > 更旧。protection 复用 _is_archivable 的名单。
502
+ def _rank(m):
503
+ return (retention(m, now),
504
+ -_num(m.get("importance"), 0.5),
505
+ -_num(m.get("created"), 0))
506
+ protected = {m.get("id") for m in hot
507
+ if m.get("pinned") or m.get("verbatim") or m.get("kind") == "identity"
508
+ or m.get("correction") or m.get("review") == "pending"}
509
+ cands = sorted((m for m in hot if m.get("id") not in protected), key=_rank)
510
+ picked = []
511
+ for m in cands:
512
+ if over <= 0:
513
+ break
514
+ if m.get("layer") == ARCHIVE_LAYER:
515
+ continue
516
+ picked.append(m)
517
+ over -= 1
518
+ if not picked:
519
+ return []
520
+ picked_ids = {m.get("id") for m in picked}
521
+ for m in picked:
522
+ m["layer"] = ARCHIVE_LAYER
523
+ m["archived_at"] = now
524
+ log_event("dream", f"#40 有界增长:热层超软上限,归档 {len(picked)} 条(cap={cap})")
525
+ return [m for m in records if m.get("id") in picked_ids]
526
+
527
+
528
+ def dream(trigger: str = "manual", dry_run: bool = False) -> dict:
529
+ ensure_home()
530
+ now = now_ts()
531
+ report = {"trigger": trigger, "at": now, "forgotten": [], "promoted": [], "faded": 0,
532
+ "archived": [], "clusters": []}
533
+
534
+ # #47 按需做梦:先量健康度。分数高且没活可干时自动做梦触发直接跳过
535
+ # (省 nightly 空转),手动触发照跑(人点了就要给个交代)。
536
+ try:
537
+ prio = dream_priority()
538
+ except Exception as e:
539
+ prio = None
540
+ log_event("dream", f"健康度评估失败(照常做梦):{e}", level="warn")
541
+ if prio:
542
+ report["priority"] = prio
543
+ if trigger == "auto" and prio["actions"] == ["skip"]:
544
+ report["skipped"] = True
545
+ report["skip_reason"] = prio["reasons"].get("verdict", "无需做梦")
546
+ log_event("dream", f"按需做梦跳过:{report['skip_reason']}")
547
+ return report
548
+
549
+ # 读-改-写整体加锁:dream 用 save_all 整库快照覆写,
550
+ # 不加锁会把锁外并发写入的新记忆用旧快照整库覆盖丢。
551
+ # dry_run 纯预览不写盘,就别去抢锁——只读记忆库(HOME 不可写)下抢锁会直接报错。
552
+ lock_ctx = (nullcontext() if dry_run else _locked(HOME / "hippocampus.jsonl"))
553
+ with lock_ctx:
554
+ # 改库前先打快照(回滚点):梦错了可以用 restore 还原,做梦本身不背"压错找不回"的锅。
555
+ # fail-closed:快照失败(磁盘满/权限等)拿不到回滚点,宁可拒绝整理也不裸奔。
556
+ if not dry_run:
557
+ snap = _dream_snapshot()
558
+ if not snap:
559
+ raise RuntimeError(
560
+ "做梦前自动快照失败(没有回滚点),已中止整理;"
561
+ "请检查 dream-snapshots 目录可写、磁盘未满后再试")
562
+ report["snapshot"] = snap
563
+ records = load_all()
564
+
565
+ # 重放→压缩:先快速眼动重放上次做梦后的经历,压成交接摘要落盘
566
+ # (借鉴 dsh-handoff-compaction:结构化摘要 + 原文可 recall 追溯 + 不动原始数据)。
567
+ # 失败不挡巩固——交接只是加分项,聚类/淡忘/晋升照常走。
568
+ try:
569
+ replay = replay_recent()
570
+ report["replayed"] = len(replay)
571
+ pol = compaction_policy()
572
+ report["policy"] = pol["mode"]
573
+ detail_floor = _num(pol.get("detail_floor"), 0.0)
574
+ dust_shift = _num(pol.get("dust_retention_shift"), 0.0)
575
+ if not dry_run and replay:
576
+ hp = save_handoff(build_handoff(replay))
577
+ report["handoff"] = hp.name
578
+ except Exception as e:
579
+ log_event("dream", f"重放/交接失败(不影响巩固):{e}", level="warn")
580
+ detail_floor, dust_shift = 0.0, 0.0
581
+
582
+ archived_recs = []
583
+
584
+ for m in records:
585
+ if not m.get("id"): # 缺 id 的畸形记录不参与巩固/遗忘(但仍原样保留在库)
586
+ continue
587
+ if m.get("layer") == "dust" or m.get("pinned"):
588
+ continue
589
+ # #41 correction 语义:改口记录永不自动淡忘/归档——它是教训提炼的第一手证据
590
+ if m.get("correction"):
591
+ continue
592
+ text = m.get("text", "") or ""
593
+ # 封存的原文不做细节淡化、不进淡忘区:它的价值就是"一个字都没丢"
594
+ verbatim = bool(m.get("verbatim"))
595
+ R = retention(m, now)
596
+ # 冷热归档:久到想不起的沉眠记忆优先雪藏(原文保真、永不删、可 archive restore 回热),
597
+ # 而不是直接模糊淡忘。放在淡忘判断之前,避免低重要沉眠记忆先被 dust 吃掉。
598
+ if not verbatim and _is_archivable(m, now):
599
+ m["layer"] = ARCHIVE_LAYER
600
+ m["archived_at"] = now
601
+ archived_recs.append(m)
602
+ report["archived"].append({"id": m["id"], "gist": m.get("gist") or heuristic_gist(text)})
603
+ continue
604
+ if (not verbatim and m.get("layer") == "hippo" and R < RETENTION_FLOOR - dust_shift
605
+ and _num(m.get("importance"), 0.5) < 0.6 and now - _num(m.get("created"), now) > 5 * DAY):
606
+ # 淡忘判据曾经是"2 天 + 重要度<0.75":做梦触发得勤了之后(daily 自动
607
+ # 做梦、面板一键做梦),同一批记忆第一次被巩固处理就会大片进淡忘区,
608
+ # 看起来像"新版算得严了"。放宽到"满 5 天 + 重要度<0.6"——普通闲聊
609
+ # 碎片多留几天被想起的机会,真沉眠的才淡忘;想抓回来的仍有轮廓在 dust。
610
+ m["layer"] = "dust"
611
+ m["forgotten_at"] = now
612
+ m["detail"] = round(max(0.12, _num(m.get("detail"), 1) * 0.4), 2)
613
+ report["forgotten"].append({"id": m["id"], "gist": m.get("gist") or heuristic_gist(text)})
614
+ continue
615
+ if (m.get("layer") == "hippo" and R >= 0.45
616
+ and (_num(m.get("access_count"), 0) >= 2 or _num(m.get("importance"), 0) >= 0.78)):
617
+ m["layer"] = "cortex"
618
+ m["consolidated"] = True
619
+ report["promoted"].append({"id": m["id"], "gist": m.get("gist") or heuristic_gist(text)})
620
+ if verbatim:
621
+ m["detail"] = 1.0 # 封存件永不模糊
622
+ else:
623
+ target = round(0.35 + 0.65 * R, 2)
624
+ # 工程模式骨架压缩:detail 有下限,代码/报错类细节不被淡忘打得太薄
625
+ target = max(target, detail_floor)
626
+ if _num(m.get("detail"), 1) > target:
627
+ m["detail"] = target
628
+ report["faded"] += 1
629
+ if not m.get("gist"):
630
+ m["gist"] = heuristic_gist(text)
631
+
632
+ # 冷热归档:长期没被想起、保留度极低的沉眠记忆雪藏进 archive 层
633
+ # (原文保真、永不删,只是移出 recall 的热遍历集合)。顺带归档几乎零额外成本。
634
+ if archived_recs:
635
+ records = [m for m in records if m.get("layer") != ARCHIVE_LAYER]
636
+ if not dry_run:
637
+ _append_archive(archived_recs)
638
+
639
+ # #43 唤醒值遗忘:对 hippo/cortex 里 activation 低于阈值的记忆做软处理
640
+ # (降层 dust + 切关联 + 清 embedding;pinned/correction/identity 等保护名单
641
+ # 在 activation_forget 内部把关)。失败不挡巩固——软遗忘是加分工序。
642
+ try:
643
+ act_forgotten = _mem.activation_forget(records, now)
644
+ if act_forgotten:
645
+ report["activation_forgotten"] = [
646
+ {"id": x["id"], "activation": round(_num(x.get("activation"), 0.0), 3),
647
+ "gist": x.get("gist") or heuristic_gist(x.get("text", "") or "")}
648
+ for x in act_forgotten]
649
+ except Exception as e:
650
+ log_event("dream", f"唤醒值遗忘失败(不影响巩固):{e}", level="warn")
651
+
652
+ # #40 有界增长:热层超软上限时把超额沉眠记忆雪藏进 archive(只压缩不删)。
653
+ # 放在常规归档之后,用最新的层分布算超额;与 archived_recs 合并一次落盘。
654
+ try:
655
+ bounded = _bounded_growth(records, now)
656
+ except Exception as e:
657
+ bounded = []
658
+ log_event("dream", f"#40 有界增长失败(不影响巩固):{e}", level="warn")
659
+ if bounded:
660
+ report["bounded_archived"] = [
661
+ {"id": m["id"], "gist": m.get("gist") or heuristic_gist(m.get("text", "") or "")}
662
+ for m in bounded]
663
+ if not dry_run:
664
+ _append_archive(bounded)
665
+ records = [m for m in records if m.get("layer") != ARCHIVE_LAYER]
666
+
667
+ clusters = cluster_memories(records, include_ids={x["id"] for x in report["promoted"]})
668
+ if not dry_run:
669
+ save_all(records)
670
+
671
+ report["clusters"] = clusters
672
+ task_id = f"dream_{now}"
673
+ report["task_id"] = task_id
674
+
675
+ # —— 教训提炼(#36):从失败闭环的证据源里挖教训候选 ——
676
+ # 证据源三类:被 supersede 的旧记忆(说法变了=旧结论错过一次)、conflict 冲突记录
677
+ # (detect_conflicts 启发式发现的矛盾对)、correction 改口记录(用户亲手纠正)。
678
+ # 生成的教训全部 status="pending" 待审(与 knowledge/persona 同一审核闸),
679
+ # review confirm 后转 active 才注入;绝不直接生效——梦是建议,不是判决。
680
+ if not dry_run:
681
+ try:
682
+ mined = _mine_lessons(records)
683
+ report["lessons_mined"] = len(mined)
684
+ except Exception as e:
685
+ log_event("dream", f"教训提炼失败(不影响巩固):{e}", level="warn")
686
+ mined = []
687
+
688
+ # —— #44 月度漂移自检:做梦时顺手自省——人格基准冻结满 30 天就对比一次。
689
+ # 失败不挡做梦(自检是加分工序)。
690
+ if not dry_run:
691
+ try:
692
+ import persona as _persona
693
+ ps = _persona.load_persona()
694
+ last_check = _num(ps.get("drift_selfcheck", [{}])[-1].get("at"), 0) \
695
+ if ps.get("drift_selfcheck") else 0
696
+ if now - last_check >= 30 * 86400:
697
+ report["drift_selfcheck"] = _persona.monthly_drift_selfcheck()
698
+ except Exception as e:
699
+ log_event("dream", f"月度漂移自检失败(不影响做梦):{e}", level="warn")
700
+
701
+ if not dry_run:
702
+ if clusters:
703
+ new_pending = {
704
+ "task_id": task_id,
705
+ "created": now,
706
+ "trigger": trigger,
707
+ "instructions": "把 clusters 里的碎片压缩成更抽象、更持久的长期记忆;提取人格变化;输出 apply.json 后执行 --apply。",
708
+ "clusters": clusters,
709
+ "report": {k: report[k] for k in ("forgotten", "promoted", "faded", "archived")},
710
+ "apply_schema": {
711
+ "task_id": task_id,
712
+ "memories": [{"kind": "fact|preference|insight|habit|emotion",
713
+ "text": "抽象后的长期记忆", "gist": "一句话要点",
714
+ "importance": "0-1 或 0-10", "tags": [], "entities": [],
715
+ "source_ids": ["m_..."]}],
716
+ "persona_updates": {"mood": {"value": "这次聊完的情绪", "reason": "..."},
717
+ "traits": {"幽默": 2},
718
+ "habits": [{"name": "深夜更容易说真话", "evidence": "..."}],
719
+ "likes": [], "dislikes": [], "insights": []},
720
+ "forget": ["m_..."],
721
+ "narrative": "这次梦的叙述(可选)",
722
+ },
723
+ }
724
+ # 幂等抢占:已有未消费的 pending 时不覆盖——旧任务的 task_id 已发给
725
+ # AI(面板/注入都读 pending.json),静默顶掉会让旧 apply 全部对不上号,
726
+ # 新任务也可能被晾着(借鉴 Mnemosyne 幂等键防重复情节、租约验证)。
727
+ # 未超时 → 沿用旧任务;超时太久(孤儿)→ 归档后接新任务。
728
+ old = load_dream_pending()
729
+ if old and old.get("task_id"):
730
+ age = now - _num(old.get("created"), now)
731
+ if age < _DREAM_ORPHAN_TTL:
732
+ report["superseded_task_id"] = task_id
733
+ task_id = old["task_id"]
734
+ report["task_id"] = task_id
735
+ report["pending_kept"] = True
736
+ log_event("dream", f"已有未整理的梦(task_id={old['task_id']},"
737
+ f"{age / 3600:.1f}h 前触发),本次不重复生成新任务", level="warn")
738
+ else:
739
+ orphan_path = HOME / "dreams" / f"orphaned_{old['task_id']}.json"
740
+ atomic_json(orphan_path, old)
741
+ pending_path = HOME / "dreams" / "pending.json"
742
+ if pending_path.exists():
743
+ pending_path.unlink()
744
+ log_event("dream", f"过期梦任务已归档(task_id={old['task_id']},"
745
+ f"悬置 {age / 3600:.1f}h > {_DREAM_ORPHAN_TTL / 3600:.0f}h),"
746
+ "生成新任务", level="warn")
747
+ report["orphaned_task_id"] = old["task_id"]
748
+ atomic_json(HOME / "dreams" / "pending.json", new_pending)
749
+ # 没有可整理的碎片就不写 pending.json,免得让 AI 对着一份空任务空转
750
+ write_dream_report(report)
751
+ st = load_dream_state()
752
+ st["last_dream"] = now
753
+ st["last_task"] = task_id if clusters else None
754
+ atomic_json(HOME / "dream_state.json", st)
755
+
756
+ return report
757
+
758
+
759
+ def write_dream_report(report: dict) -> Path:
760
+ now = report["at"]
761
+ base = f"{datetime.fromtimestamp(now).strftime('%Y%m%d_%H%M%S')}"
762
+ path = HOME / "dreams" / f"{base}.md"
763
+ n = 1
764
+ while path.exists(): # 同秒多次做梦时不要覆盖上一份
765
+ n += 1
766
+ path = HOME / "dreams" / f"{base}_{n}.md"
767
+ lines = [f"# 梦境整理 · {fmt_time(now)}", "", f"触发:{report['trigger']}", ""]
768
+ lines.append(f"- 重放片段:{sum(len(c['texts']) for c in report['clusters'])} 条 / {len(report['clusters'])} 组")
769
+ lines.append(f"- 巩固入长期:{len(report['promoted'])} 条")
770
+ lines.append(f"- 淡忘归档:{len(report['forgotten'])} 条")
771
+ lines.append(f"- 雪藏冷档:{len(report.get('archived', []))} 条(原文保留,可 archive search / restore)")
772
+ lines.append(f"- 模糊化细节:{report['faded']} 条")
773
+ mined = report.get("lessons_mined", 0)
774
+ if mined:
775
+ lines.append(f"- 教训提炼:{mined} 条新教训候选(pending 待审,review 里确认后生效)")
776
+ if report.get("snapshot"):
777
+ lines.append(f"- 回滚点:{report['snapshot']}(梦错了可用 restore 还原)")
778
+ if report["clusters"]:
779
+ lines += ["", "## 重放的主题"]
780
+ for c in report["clusters"]:
781
+ tags = "、".join(c["tags"][:4]) or "、".join(c["entities"][:4]) or "无标签"
782
+ lines.append(f"- {tags}({len(c['texts'])} 条)")
783
+ if report["forgotten"]:
784
+ lines += ["", "## 淡忘的轮廓"]
785
+ for f in report["forgotten"][:10]:
786
+ lines.append(f"- {f['gist']}")
787
+ write_text_atomic(path, "\n".join(lines) + "\n")
788
+ return path
789
+
790
+
791
+ def load_dream_pending() -> dict | None:
792
+ """当前待整理的梦任务(pending.json);不存在/损坏返回 None。"""
793
+ return _slurp_json(HOME / "dreams" / "pending.json", None)
794
+
795
+
796
+ def dream_draft_path() -> Path:
797
+ return HOME / "dreams" / "apply_draft.json"
798
+
799
+
800
+ def load_dream_draft() -> dict | None:
801
+ """上次在面板里编辑、还没应用的 apply.json 草稿。"""
802
+ return _slurp_json(dream_draft_path(), None)
803
+
804
+
805
+ def save_dream_draft(obj) -> dict:
806
+ """把 apply.json 草稿存盘(面板网页编辑→保存,避免模型合并出错时只能命令行改文件)。"""
807
+ if READONLY:
808
+ raise PermissionError("记忆库当前只读,无法保存草稿。")
809
+ ensure_home()
810
+ if not isinstance(obj, dict):
811
+ raise ValueError("草稿必须是 JSON 对象")
812
+ atomic_json(dream_draft_path(), obj)
813
+ return {"ok": True, "path": str(dream_draft_path())}
814
+
815
+
816
+ def clear_dream_draft() -> None:
817
+ try:
818
+ dream_draft_path().unlink()
819
+ except (FileNotFoundError, OSError):
820
+ pass
821
+
822
+
823
+ def load_dream_state() -> dict:
824
+ path = HOME / "dream_state.json"
825
+ if path.exists():
826
+ d = _slurp_json(path)
827
+ if isinstance(d, dict):
828
+ return d
829
+ return {"last_dream": 0, "last_task": None}
830
+
831
+
832
+ VERIFY_SAMPLE_FILE = "verify-sample.json"
833
+
834
+
835
+ def write_verify_sample(pairs: list, task_id: str = "") -> dict | None:
836
+ """#19 梦抽检:把本次合并的「合并前 → 合并后」抽 3 组落盘。
837
+
838
+ AI 整理最容易在"把两条记忆揉成一条"时悄悄改掉原意,而合并结果默认是
839
+ 待审核状态——抽检就是给人一个**看差别**的短清单,不必翻整场梦的报告。
840
+ 写 dreams/verify-sample.json,`dream verify` 查看,`dream verify --done` 标记已看过。
841
+ """
842
+ if not pairs:
843
+ return None
844
+ # 均匀抽 3 组(首/中/尾),不引入随机数:同一场梦重复写入结果稳定
845
+ n = len(pairs)
846
+ picks = sorted({0, n // 2, n - 1})[:3]
847
+ items = [pairs[i] for i in picks if i < n]
848
+ data = {
849
+ "task_id": task_id,
850
+ "at": now_ts(),
851
+ "reviewed": False,
852
+ "reviewed_at": None,
853
+ "total_merges": n,
854
+ "items": items,
855
+ }
856
+ path = HOME / "dreams" / VERIFY_SAMPLE_FILE
857
+ path.parent.mkdir(parents=True, exist_ok=True)
858
+ atomic_json(path, data)
859
+ return data
860
+
861
+
862
+ def load_verify_sample() -> dict | None:
863
+ """读取最近一次梦抽检样本;没有/坏文件返回 None。"""
864
+ path = HOME / "dreams" / VERIFY_SAMPLE_FILE
865
+ if not path.exists():
866
+ return None
867
+ try:
868
+ data = json.loads(path.read_text("utf-8"))
869
+ return data if isinstance(data, dict) else None
870
+ except Exception:
871
+ return None
872
+
873
+
874
+ def mark_verify_reviewed() -> dict | None:
875
+ """标记抽检样本已看过(不删文件,保留对照供以后回看)。"""
876
+ data = load_verify_sample()
877
+ if not data:
878
+ return None
879
+ data["reviewed"] = True
880
+ data["reviewed_at"] = now_ts()
881
+ atomic_json(HOME / "dreams" / VERIFY_SAMPLE_FILE, data)
882
+ return data
883
+
884
+
885
+ def apply_dream(result: dict) -> dict:
886
+ ensure_home()
887
+ pending_path = HOME / "dreams" / "pending.json"
888
+ task_id = result.get("task_id")
889
+ applied = {"memories": 0, "forgotten": 0, "persona": [], "rejected": []}
890
+
891
+ # 读-校验-改-写-消费 pending 整体在一把锁里:
892
+ # 1) 两个 apply 并发时,第二个进锁后 pending 已被删,直接拒绝,不会把同一份结果套两遍;
893
+ # 2) 整库 save_all 不会把锁外并发写入的新记忆覆盖丢。
894
+ with _locked(HOME / "hippocampus.jsonl"):
895
+ # 先对任务号:apply 必须对着当前这场的 pending.json,防止把上一场的结果
896
+ # 或乱写的 task_id 应用到现在的记忆上。不对就直接拒绝,不碰任何数据。
897
+ pending_id = None
898
+ if pending_path.exists():
899
+ try:
900
+ pending_id = (json.loads(pending_path.read_text("utf-8")) or {}).get("task_id")
901
+ except Exception:
902
+ pending_id = None
903
+ if pending_id is None:
904
+ raise ValueError("没有待应用的任务:dreams/pending.json 不存在")
905
+ if not task_id:
906
+ # 以前这里 fallback 到 pending_id,等于"缺 task_id 但也放行"——
907
+ # 上一场漏写 task_id 的 apply.json 会静默套用到这一场。改为必须显式带上。
908
+ raise ValueError(
909
+ f"apply 里没有 task_id:为防止把上一场的整理结果套用到这一场,拒绝应用。"
910
+ f"请在 apply.json 里带上 \"task_id\": \"{pending_id}\"。"
911
+ )
912
+ if task_id != pending_id:
913
+ raise ValueError(
914
+ f"任务对不上:apply 里的 task_id={task_id!r},与 pending.json 的 {pending_id!r} 不一致,拒绝应用。"
915
+ )
916
+ records = load_all()
917
+ by_id = {m["id"]: m for m in records if m.get("id")}
918
+ _old_terms_cache = {} # id → terms:锁内缓存旧记忆分词,多条新记忆不重复算
919
+ _verify_pairs = [] # #19 合并前后对照:写入 dreams/verify-sample.json 供抽检
920
+
921
+ # 写入时校验引用(借鉴图数据库 dangling edge 防线):
922
+ # AI 填的 source_ids 可能编造/抄错 id,老版本直接写进 links 就成了死链。
923
+ # 现在落库前先对一遍现库,不存在的 id 丢弃并留痕。
924
+ _known_ids = set(by_id)
925
+ for item in result.get("memories") or []:
926
+ if isinstance(item, dict) and item.get("source_ids"):
927
+ bad = [sid for sid in item["source_ids"]
928
+ if isinstance(sid, str) and sid not in _known_ids]
929
+ if bad:
930
+ applied["rejected"].append(
931
+ f"忽略 source_ids 中不存在的引用:{', '.join(bad)}")
932
+ item["source_ids"] = [s for s in item["source_ids"]
933
+ if not (isinstance(s, str) and s in bad)]
934
+
935
+ for item in result.get("memories") or []:
936
+ if not isinstance(item, dict):
937
+ continue
938
+ text = (item.get("text") or "").strip()
939
+ if not text:
940
+ continue
941
+ rec = make_record(
942
+ text,
943
+ kind=item.get("kind", "fact"),
944
+ importance=_num(item.get("importance"), 0.7),
945
+ tags=item.get("tags"),
946
+ entities=item.get("entities"),
947
+ source="dream",
948
+ layer="cortex",
949
+ links=[x for x in (item.get("source_ids") or []) if isinstance(x, str)],
950
+ )
951
+ rec["gist"] = item.get("gist") or heuristic_gist(text)
952
+ rec["consolidated"] = True
953
+ rec["detail"] = 1.0
954
+ # AI 整理出来的记忆先标"待审核":防止做梦合并/编造的内容直接当事实沉淀。
955
+ rec["review"] = "pending"
956
+ rec["review_source"] = "dream"
957
+ # #46 Memex 索引解引用:合并/蒸馏产物带 evidence_ids 指针(指向原始证据记忆),
958
+ # 召回命中摘要时按需解引用取原文,"概括"与"细节"两级可导航。
959
+ # 证据 = AI 声明的 source_ids + 确实被本条取代的旧记忆,宁可多指针不丢证据。
960
+ _ev = [s for s in rec.get("links", []) if isinstance(s, str)]
961
+ _ev += [old["id"] for old in records
962
+ if old.get("superseded_by") == rec["id"] and old.get("id")]
963
+ if _ev:
964
+ rec["evidence_ids"] = _dedupe(_ev)
965
+ # #45 影响评估(SSGM):合并/蒸馏决议附轻量 impact——这条记忆一旦确认,
966
+ # 会改变多少召回注入文本、波及哪些实体,让用户优先审"影响大"的改动。
967
+ rec["impact"] = {
968
+ "chars": len(text), # 确认后进入注入文本的字数
969
+ "entities": list(rec.get("entities", []) or []),
970
+ "superseded": sum(1 for old in records
971
+ if old.get("superseded_by") == rec["id"]),
972
+ }
973
+ # —— 矛盾记忆不覆盖,留链路 ——
974
+ # 新记忆与旧记忆高度相似但内容不同(说法变了/事实更新)时,旧的不删,
975
+ # 打上 superseded_by 指向新的:回忆默认跳过被取代者,需要时仍可回溯
976
+ # "我以前是怎么想的"——像人一样,观念变了但旧观念还在记忆深处。
977
+ # 大库时锁内 O(n²) 比对会堵死其他写进程:先用词交集粗筛出候选
978
+ # (jaccard ≥0.55 必有足够交集),再只对候选做精比对。
979
+ new_terms = terms(text)
980
+ _cand_threshold = len(new_terms) * 0.55
981
+ for old in records:
982
+ # rec 是本函数刚新建的记录,不在 records 里,无需 is 判断
983
+ if old.get("layer") == "dust" or old.get("superseded_by"):
984
+ continue
985
+ # #28 冻结的记忆不许被做梦改写:用户明确要求"这条别动"
986
+ if old.get("frozen"):
987
+ continue
988
+ # #41:correction 改口记录不许被做梦产出 supersede——它是最新的用户更正,
989
+ # 被取代等于把刚纠正过的事实又改回去
990
+ if old.get("correction"):
991
+ continue
992
+ old_terms = _old_terms_cache.get(old["id"])
993
+ if old_terms is None:
994
+ old_terms = terms(str(old.get("text", "")))
995
+ _old_terms_cache[old["id"]] = old_terms
996
+ if not old_terms:
997
+ continue
998
+ # 粗筛:交集元素数 < 0.55×|new| 时 jaccard 必然 < 0.55,直接跳过
999
+ if len(new_terms & old_terms) < _cand_threshold:
1000
+ continue
1001
+ if jaccard(new_terms, old_terms) >= 0.55 and str(old.get("text", "")).strip() != text:
1002
+ old["superseded_by"] = rec["id"]
1003
+ rec.setdefault("links", [])
1004
+ if old["id"] not in rec["links"]:
1005
+ rec["links"].append(old["id"])
1006
+ applied.setdefault("superseded", []).append(old["id"])
1007
+ # #19 留一组"合并前 → 合并后"对照,供事后抽检 AI 有没有改坏原意
1008
+ _verify_pairs.append({
1009
+ "new_id": rec["id"],
1010
+ "after": text,
1011
+ "before": [{"id": old["id"], "text": str(old.get("text", ""))}],
1012
+ })
1013
+ records.append(rec)
1014
+ applied["memories"] += 1
1015
+ for sid in rec["links"]:
1016
+ src = by_id.get(sid)
1017
+ if src:
1018
+ src["consolidated"] = True
1019
+ src["links"] = _dedupe(src.get("links", []) + [rec["id"]])
1020
+ if src.get("layer") == "hippo" and src.get("importance", 0.5) >= 0.5:
1021
+ src["layer"] = "cortex"
1022
+
1023
+ _forget_n = 0
1024
+ for sid in result.get("forget") or []:
1025
+ m = by_id.get(sid)
1026
+ if m and m.get("layer") != "dust":
1027
+ # pinned 与 dream 主循环同一待遇:用户置顶的不许 AI 梦里淡忘——
1028
+ # 否则 apply.json 里给个 pinned id 就能绕过防线
1029
+ if m.get("pinned"):
1030
+ applied["rejected"].append(f"拒绝淡忘 {sid}:用户置顶的记忆不参与做梦淡忘")
1031
+ continue
1032
+ # #28 冻结的记忆同样不参与淡忘
1033
+ if m.get("frozen"):
1034
+ applied["rejected"].append(f"拒绝淡忘 {sid}:已冻结的记忆不参与做梦淡忘")
1035
+ continue
1036
+ # #41:correction 改口记录不许梦淡忘——教训提炼的证据链不能断
1037
+ if m.get("correction"):
1038
+ applied["rejected"].append(f"拒绝淡忘 {sid}:改口(correction)记录永不自动淡忘")
1039
+ continue
1040
+ m["layer"] = "dust"
1041
+ m["forgotten_at"] = now_ts()
1042
+ applied["forgotten"] += 1
1043
+ _forget_n += 1
1044
+ if _forget_n:
1045
+ # 留痕:淡忘是"移入 dust 层"而非删除,但日志记一笔数量,方便审计核对没丢数据
1046
+ log_event("dream", f"本次做梦淡忘 {_forget_n} 条记忆(已移入 dust 淡忘区,可 revive 找回)")
1047
+
1048
+ save_all(records)
1049
+ # #19 抽检样本:落盘 3 组合并前后对照(失败不影响做梦主流程)
1050
+ try:
1051
+ write_verify_sample(_verify_pairs, task_id)
1052
+ except Exception as exc:
1053
+ log_event("dream", f"写抽检样本失败(不影响巩固):{exc}", level="warn")
1054
+ # 人格更新也放在锁内、且必须在"删 pending"之前:AI 产的 persona_updates 可能带 NaN
1055
+ # 等坏值,若先删 pending 再更新人格,人格段一崩这批整理就永远无法重试(pending 已丢)。
1056
+ upd = result.get("persona_updates")
1057
+ upd = upd if isinstance(upd, dict) else {}
1058
+ if upd:
1059
+ evid = [sid for it in (result.get("memories") or [])
1060
+ if isinstance(it, dict) for sid in (it.get("source_ids") or [])
1061
+ if isinstance(sid, str)][:10]
1062
+ # 成形时刻检测:近 14 天内若有峰值情绪(formative=True)事件,本场梦的
1063
+ # traits 漂移走旁路(×2.5 封顶 ±25,绕过双门限)——一次真正的峰值情绪
1064
+ # 本来就足以重塑人,不该被"攒账"机制压制。事件按 ts 倒序,取第一条。
1065
+ formative_ev = None
1066
+ try:
1067
+ import emotion as _emo
1068
+ fe = _emo.formative_events(days=14)
1069
+ formative_ev = fe[0] if fe else None
1070
+ except Exception as exc:
1071
+ log_event("dream", f"读取成形时刻事件失败,按普通漂移处理:{exc}", level="warn")
1072
+ if formative_ev and upd.get("traits"):
1073
+ boosted = {}
1074
+ for k, v in upd["traits"].items():
1075
+ try:
1076
+ boosted[k] = max(-10, min(10, float(v) * 2.5))
1077
+ except (TypeError, ValueError):
1078
+ log_event("dream", f"成形旁路时 traits.{k} 值非法 {v!r},跳过", level="warn")
1079
+ if boosted:
1080
+ upd = {**upd, "traits": boosted}
1081
+ fwhy = (formative_ev.get("why") or formative_ev.get("about") or "").strip()
1082
+ fdesc = f"{formative_ev.get('emotion') or '强烈的情绪'}" + (f"({fwhy})" if fwhy else "")
1083
+ try:
1084
+ applied["rejected"] = update_persona(
1085
+ upd, why="做梦整理", source="dream_formative", evidence=evid,
1086
+ bypass_gate=True, formative_event=fdesc)
1087
+ except Exception as exc:
1088
+ log_event("dream", f"做梦应用时人格更新失败,pending 已保留可重试:{exc}", level="error")
1089
+ raise
1090
+ else:
1091
+ try:
1092
+ applied["rejected"] = update_persona(upd, why="做梦整理", source="dream", evidence=evid)
1093
+ except Exception as exc:
1094
+ log_event("dream", f"做梦应用时人格更新失败,pending 已保留可重试:{exc}", level="error")
1095
+ raise
1096
+ else:
1097
+ try:
1098
+ applied["rejected"] = update_persona(upd, why="做梦整理", source="dream", evidence=evid)
1099
+ except Exception as exc:
1100
+ # 人格更新失败:保留 pending apply 文件让整场可重试(persona 层有锁与校验,
1101
+ # 正常情况下不该崩,这里兜底防 NaN 之外的意外把数据搞丢)
1102
+ log_event("dream", f"做梦应用时人格更新失败,pending 已保留可重试:{exc}", level="error")
1103
+ raise
1104
+ # 在锁内消费 pending:写入与"这场梦已应用"必须同时成立,
1105
+ # 否则并发 apply / 崩溃重试会把这批记忆再套一遍(重复沉淀)。
1106
+ try:
1107
+ pending_path.unlink()
1108
+ except FileNotFoundError:
1109
+ pass
1110
+
1111
+ narrative = (result.get("narrative") or "").strip()
1112
+ if narrative or applied["memories"]:
1113
+ path = HOME / "dreams" / f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_apply.md"
1114
+ body = [f"# 梦的沉淀 · {fmt_time(now_ts())}", f"任务:{task_id}", "",
1115
+ f"新增长期记忆 {applied['memories']} 条,遗忘 {applied['forgotten']} 条。"]
1116
+ if narrative:
1117
+ body += ["", "## 梦里的叙述", narrative]
1118
+ if upd.get("insights"):
1119
+ body += ["", "## 洞见"] + [f"- {x}" for x in upd["insights"]]
1120
+ rej = applied.get("rejected") or []
1121
+ if rej:
1122
+ # 被双门限/锁定/不存在拦下的改动留痕在梦报告里——AI 与人都能看到
1123
+ # "梦想改什么、防线拦了什么",而不是只看到悄悄没生效
1124
+ body += ["", "## 被防线拦下的改动"] + [f"- {x}" for x in rej]
1125
+ try:
1126
+ write_text_atomic(path, "\n".join(body) + "\n")
1127
+ except OSError:
1128
+ pass # 梦境笔记写不进去不影响记忆已落盘,别把成功报成失败
1129
+ # 自认识沉淀:放在 _locked 块之外(autosink 自己加 persona.json 锁,
1130
+ # 嵌套调用同一文件锁会死锁);失败只记日志,不影响梦已落盘。
1131
+ try:
1132
+ applied["self_model"] = self_model_autosink()
1133
+ except Exception as exc:
1134
+ log_event("dream", f"做梦后自认识沉淀失败(不影响梦):{exc}", level="warn")
1135
+ applied["self_model"] = {"ok": False, "error": str(exc)}
1136
+ clear_dream_draft() # 应用成功后,网页里编辑过的那份草稿也一并清掉
1137
+ return applied