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