lingshu-skill 3.93.0 → 3.95.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,34 +1,34 @@
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 是按批推进的)。
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
32
  _MAX_CLUSTER_POOL = 400
33
33
 
34
34
  # 孤儿梦任务时效:pending 生成后超过这么久还没被 apply,视为孤儿任务。
@@ -173,106 +173,106 @@ def latest_handoff() -> dict | None:
173
173
  h = _slurp_json(files[-1])
174
174
  return h if isinstance(h, dict) and h.get("要点") is not None else None
175
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
-
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
276
  _FLUFF_WORDS = ("本轮", "综上", "总结", "摘要", "回顾一下", "已完成", "以上是",
277
277
  "以上为", "本次", "小结")
278
278
  _ACTION_WORDS = ("别", "不要", "应该", "务必", "必须", "记得", "下次", "避免",
@@ -345,9 +345,15 @@ def _mine_lessons(records: list, max_lessons: int = 3) -> list:
345
345
  return True
346
346
  return False
347
347
 
348
+ def _agg(m: dict) -> bool:
349
+ """聚合摘要(aggregate 标记或「最近关于X的一组事情」形态)不当教训素材——
350
+ 正文是 N 条原文的拼接,抽不出可执行教训(P9 #64)。"""
351
+ return bool(m.get("aggregate")) or mem_mod._is_dream_aggregate(m.get("text", ""))
352
+
348
353
  # 1) correction 改口记录:从改口原文里抽可执行的一句
349
354
  corrections = [m for m in records
350
- if m.get("correction") and m.get("id") and m.get("text", "").strip()]
355
+ if m.get("correction") and m.get("id") and m.get("text", "").strip()
356
+ and not _agg(m)]
351
357
  for m in corrections[:max_lessons]:
352
358
  text = _lesson_sentence(str(m.get("text", "")))
353
359
  if not text or _dup(text):
@@ -364,10 +370,10 @@ def _mine_lessons(records: list, max_lessons: int = 3) -> list:
364
370
  if len(created) >= max_lessons:
365
371
  break
366
372
  new_id = m.get("superseded_by")
367
- if not new_id or m.get("layer") == "dust":
373
+ if not new_id or m.get("layer") == "dust" or _agg(m):
368
374
  continue
369
375
  newer = by_id.get(new_id)
370
- if not newer or not str(newer.get("text", "")).strip():
376
+ if not newer or not str(newer.get("text", "")).strip() or _agg(newer):
371
377
  continue
372
378
  core = str(newer.get("text", "")).strip()
373
379
  text = f"「{core[:120]}」已取代旧结论——别再按旧的说。"
@@ -525,117 +531,117 @@ def _bounded_growth(records: list, now: int) -> list:
525
531
  return [m for m in records if m.get("id") in picked_ids]
526
532
 
527
533
 
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
-
534
+ def dream(trigger: str = "manual", dry_run: bool = False) -> dict:
535
+ ensure_home()
536
+ now = now_ts()
537
+ report = {"trigger": trigger, "at": now, "forgotten": [], "promoted": [], "faded": 0,
538
+ "archived": [], "clusters": []}
539
+
540
+ # #47 按需做梦:先量健康度。分数高且没活可干时自动做梦触发直接跳过
541
+ # (省 nightly 空转),手动触发照跑(人点了就要给个交代)。
542
+ try:
543
+ prio = dream_priority()
544
+ except Exception as e:
545
+ prio = None
546
+ log_event("dream", f"健康度评估失败(照常做梦):{e}", level="warn")
547
+ if prio:
548
+ report["priority"] = prio
549
+ if trigger == "auto" and prio["actions"] == ["skip"]:
550
+ report["skipped"] = True
551
+ report["skip_reason"] = prio["reasons"].get("verdict", "无需做梦")
552
+ log_event("dream", f"按需做梦跳过:{report['skip_reason']}")
553
+ return report
554
+
555
+ # 读-改-写整体加锁:dream 用 save_all 整库快照覆写,
556
+ # 不加锁会把锁外并发写入的新记忆用旧快照整库覆盖丢。
557
+ # dry_run 纯预览不写盘,就别去抢锁——只读记忆库(HOME 不可写)下抢锁会直接报错。
558
+ lock_ctx = (nullcontext() if dry_run else _locked(HOME / "hippocampus.jsonl"))
559
+ with lock_ctx:
560
+ # 改库前先打快照(回滚点):梦错了可以用 restore 还原,做梦本身不背"压错找不回"的锅。
561
+ # fail-closed:快照失败(磁盘满/权限等)拿不到回滚点,宁可拒绝整理也不裸奔。
562
+ if not dry_run:
563
+ snap = _dream_snapshot()
564
+ if not snap:
565
+ raise RuntimeError(
566
+ "做梦前自动快照失败(没有回滚点),已中止整理;"
567
+ "请检查 dream-snapshots 目录可写、磁盘未满后再试")
568
+ report["snapshot"] = snap
569
+ records = load_all()
570
+
571
+ # 重放→压缩:先快速眼动重放上次做梦后的经历,压成交接摘要落盘
572
+ # (借鉴 dsh-handoff-compaction:结构化摘要 + 原文可 recall 追溯 + 不动原始数据)。
573
+ # 失败不挡巩固——交接只是加分项,聚类/淡忘/晋升照常走。
574
+ try:
575
+ replay = replay_recent()
576
+ report["replayed"] = len(replay)
577
+ pol = compaction_policy()
578
+ report["policy"] = pol["mode"]
579
+ detail_floor = _num(pol.get("detail_floor"), 0.0)
580
+ dust_shift = _num(pol.get("dust_retention_shift"), 0.0)
581
+ if not dry_run and replay:
582
+ hp = save_handoff(build_handoff(replay))
583
+ report["handoff"] = hp.name
584
+ except Exception as e:
585
+ log_event("dream", f"重放/交接失败(不影响巩固):{e}", level="warn")
586
+ detail_floor, dust_shift = 0.0, 0.0
587
+
588
+ archived_recs = []
589
+
590
+ for m in records:
591
+ if not m.get("id"): # 缺 id 的畸形记录不参与巩固/遗忘(但仍原样保留在库)
592
+ continue
593
+ if m.get("layer") == "dust" or m.get("pinned"):
594
+ continue
595
+ # #41 correction 语义:改口记录永不自动淡忘/归档——它是教训提炼的第一手证据
596
+ if m.get("correction"):
597
+ continue
598
+ text = m.get("text", "") or ""
599
+ # 封存的原文不做细节淡化、不进淡忘区:它的价值就是"一个字都没丢"
600
+ verbatim = bool(m.get("verbatim"))
601
+ R = retention(m, now)
602
+ # 冷热归档:久到想不起的沉眠记忆优先雪藏(原文保真、永不删、可 archive restore 回热),
603
+ # 而不是直接模糊淡忘。放在淡忘判断之前,避免低重要沉眠记忆先被 dust 吃掉。
604
+ if not verbatim and _is_archivable(m, now):
605
+ m["layer"] = ARCHIVE_LAYER
606
+ m["archived_at"] = now
607
+ archived_recs.append(m)
608
+ report["archived"].append({"id": m["id"], "gist": m.get("gist") or heuristic_gist(text)})
609
+ continue
610
+ if (not verbatim and m.get("layer") == "hippo" and R < RETENTION_FLOOR - dust_shift
611
+ and _num(m.get("importance"), 0.5) < 0.6 and now - _num(m.get("created"), now) > 5 * DAY):
612
+ # 淡忘判据曾经是"2 天 + 重要度<0.75":做梦触发得勤了之后(daily 自动
613
+ # 做梦、面板一键做梦),同一批记忆第一次被巩固处理就会大片进淡忘区,
614
+ # 看起来像"新版算得严了"。放宽到"满 5 天 + 重要度<0.6"——普通闲聊
615
+ # 碎片多留几天被想起的机会,真沉眠的才淡忘;想抓回来的仍有轮廓在 dust。
616
+ m["layer"] = "dust"
617
+ m["forgotten_at"] = now
618
+ m["detail"] = round(max(0.12, _num(m.get("detail"), 1) * 0.4), 2)
619
+ report["forgotten"].append({"id": m["id"], "gist": m.get("gist") or heuristic_gist(text)})
620
+ continue
621
+ if (m.get("layer") == "hippo" and R >= 0.45
622
+ and (_num(m.get("access_count"), 0) >= 2 or _num(m.get("importance"), 0) >= 0.78)):
623
+ m["layer"] = "cortex"
624
+ m["consolidated"] = True
625
+ report["promoted"].append({"id": m["id"], "gist": m.get("gist") or heuristic_gist(text)})
626
+ if verbatim:
627
+ m["detail"] = 1.0 # 封存件永不模糊
628
+ else:
629
+ target = round(0.35 + 0.65 * R, 2)
630
+ # 工程模式骨架压缩:detail 有下限,代码/报错类细节不被淡忘打得太薄
631
+ target = max(target, detail_floor)
632
+ if _num(m.get("detail"), 1) > target:
633
+ m["detail"] = target
634
+ report["faded"] += 1
635
+ if not m.get("gist"):
636
+ m["gist"] = heuristic_gist(text)
637
+
638
+ # 冷热归档:长期没被想起、保留度极低的沉眠记忆雪藏进 archive 层
639
+ # (原文保真、永不删,只是移出 recall 的热遍历集合)。顺带归档几乎零额外成本。
640
+ if archived_recs:
641
+ records = [m for m in records if m.get("layer") != ARCHIVE_LAYER]
642
+ if not dry_run:
643
+ _append_archive(archived_recs)
644
+
639
645
  # #43 唤醒值遗忘:对 hippo/cortex 里 activation 低于阈值的记忆做软处理
640
646
  # (降层 dust + 切关联 + 清 embedding;pinned/correction/identity 等保护名单
641
647
  # 在 activation_forget 内部把关)。失败不挡巩固——软遗忘是加分工序。
@@ -664,63 +670,63 @@ def dream(trigger: str = "manual", dry_run: bool = False) -> dict:
664
670
  _append_archive(bounded)
665
671
  records = [m for m in records if m.get("layer") != ARCHIVE_LAYER]
666
672
 
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
- }
673
+ clusters = cluster_memories(records, include_ids={x["id"] for x in report["promoted"]})
674
+ if not dry_run:
675
+ save_all(records)
676
+
677
+ report["clusters"] = clusters
678
+ task_id = f"dream_{now}"
679
+ report["task_id"] = task_id
680
+
681
+ # —— 教训提炼(#36):从失败闭环的证据源里挖教训候选 ——
682
+ # 证据源三类:被 supersede 的旧记忆(说法变了=旧结论错过一次)、conflict 冲突记录
683
+ # (detect_conflicts 启发式发现的矛盾对)、correction 改口记录(用户亲手纠正)。
684
+ # 生成的教训全部 status="pending" 待审(与 knowledge/persona 同一审核闸),
685
+ # review confirm 后转 active 才注入;绝不直接生效——梦是建议,不是判决。
686
+ if not dry_run:
687
+ try:
688
+ mined = _mine_lessons(records)
689
+ report["lessons_mined"] = len(mined)
690
+ except Exception as e:
691
+ log_event("dream", f"教训提炼失败(不影响巩固):{e}", level="warn")
692
+ mined = []
693
+
694
+ # —— #44 月度漂移自检:做梦时顺手自省——人格基准冻结满 30 天就对比一次。
695
+ # 失败不挡做梦(自检是加分工序)。
696
+ if not dry_run:
697
+ try:
698
+ import persona as _persona
699
+ ps = _persona.load_persona()
700
+ last_check = _num(ps.get("drift_selfcheck", [{}])[-1].get("at"), 0) \
701
+ if ps.get("drift_selfcheck") else 0
702
+ if now - last_check >= 30 * 86400:
703
+ report["drift_selfcheck"] = _persona.monthly_drift_selfcheck()
704
+ except Exception as e:
705
+ log_event("dream", f"月度漂移自检失败(不影响做梦):{e}", level="warn")
706
+
707
+ if not dry_run:
708
+ if clusters:
709
+ new_pending = {
710
+ "task_id": task_id,
711
+ "created": now,
712
+ "trigger": trigger,
713
+ "instructions": "把 clusters 里的碎片压缩成更抽象、更持久的长期记忆;提取人格变化;输出 apply.json 后执行 --apply。",
714
+ "clusters": clusters,
715
+ "report": {k: report[k] for k in ("forgotten", "promoted", "faded", "archived")},
716
+ "apply_schema": {
717
+ "task_id": task_id,
718
+ "memories": [{"kind": "fact|preference|insight|habit|emotion",
719
+ "text": "抽象后的长期记忆", "gist": "一句话要点",
720
+ "importance": "0-1 或 0-10", "tags": [], "entities": [],
721
+ "source_ids": ["m_..."]}],
722
+ "persona_updates": {"mood": {"value": "这次聊完的情绪", "reason": "..."},
723
+ "traits": {"幽默": 2},
724
+ "habits": [{"name": "深夜更容易说真话", "evidence": "..."}],
725
+ "likes": [], "dislikes": [], "insights": []},
726
+ "forget": ["m_..."],
727
+ "narrative": "这次梦的叙述(可选)",
728
+ },
729
+ }
724
730
  # 幂等抢占:已有未消费的 pending 时不覆盖——旧任务的 task_id 已发给
725
731
  # AI(面板/注入都读 pending.json),静默顶掉会让旧 apply 全部对不上号,
726
732
  # 新任务也可能被晾着(借鉴 Mnemosyne 幂等键防重复情节、租约验证)。
@@ -745,90 +751,90 @@ def dream(trigger: str = "manual", dry_run: bool = False) -> dict:
745
751
  f"悬置 {age / 3600:.1f}h > {_DREAM_ORPHAN_TTL / 3600:.0f}h),"
746
752
  "生成新任务", level="warn")
747
753
  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
754
+ atomic_json(HOME / "dreams" / "pending.json", new_pending)
755
+ # 没有可整理的碎片就不写 pending.json,免得让 AI 对着一份空任务空转
756
+ write_dream_report(report)
757
+ st = load_dream_state()
758
+ st["last_dream"] = now
753
759
  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
-
760
+ atomic_json(HOME / "dream_state.json", st)
761
+
762
+ return report
763
+
764
+
765
+ def write_dream_report(report: dict) -> Path:
766
+ now = report["at"]
767
+ base = f"{datetime.fromtimestamp(now).strftime('%Y%m%d_%H%M%S')}"
768
+ path = HOME / "dreams" / f"{base}.md"
769
+ n = 1
770
+ while path.exists(): # 同秒多次做梦时不要覆盖上一份
771
+ n += 1
772
+ path = HOME / "dreams" / f"{base}_{n}.md"
773
+ lines = [f"# 梦境整理 · {fmt_time(now)}", "", f"触发:{report['trigger']}", ""]
774
+ lines.append(f"- 重放片段:{sum(len(c['texts']) for c in report['clusters'])} 条 / {len(report['clusters'])} 组")
775
+ lines.append(f"- 巩固入长期:{len(report['promoted'])} 条")
776
+ lines.append(f"- 淡忘归档:{len(report['forgotten'])} 条")
777
+ lines.append(f"- 雪藏冷档:{len(report.get('archived', []))} 条(原文保留,可 archive search / restore)")
778
+ lines.append(f"- 模糊化细节:{report['faded']} 条")
779
+ mined = report.get("lessons_mined", 0)
780
+ if mined:
781
+ lines.append(f"- 教训提炼:{mined} 条新教训候选(pending 待审,review 里确认后生效)")
782
+ if report.get("snapshot"):
783
+ lines.append(f"- 回滚点:{report['snapshot']}(梦错了可用 restore 还原)")
784
+ if report["clusters"]:
785
+ lines += ["", "## 重放的主题"]
786
+ for c in report["clusters"]:
787
+ tags = "、".join(c["tags"][:4]) or "、".join(c["entities"][:4]) or "无标签"
788
+ lines.append(f"- {tags}({len(c['texts'])} 条)")
789
+ if report["forgotten"]:
790
+ lines += ["", "## 淡忘的轮廓"]
791
+ for f in report["forgotten"][:10]:
792
+ lines.append(f"- {f['gist']}")
793
+ write_text_atomic(path, "\n".join(lines) + "\n")
794
+ return path
795
+
796
+
797
+ def load_dream_pending() -> dict | None:
798
+ """当前待整理的梦任务(pending.json);不存在/损坏返回 None。"""
799
+ return _slurp_json(HOME / "dreams" / "pending.json", None)
800
+
801
+
802
+ def dream_draft_path() -> Path:
803
+ return HOME / "dreams" / "apply_draft.json"
804
+
805
+
806
+ def load_dream_draft() -> dict | None:
807
+ """上次在面板里编辑、还没应用的 apply.json 草稿。"""
808
+ return _slurp_json(dream_draft_path(), None)
809
+
810
+
811
+ def save_dream_draft(obj) -> dict:
812
+ """把 apply.json 草稿存盘(面板网页编辑→保存,避免模型合并出错时只能命令行改文件)。"""
813
+ if READONLY:
814
+ raise PermissionError("记忆库当前只读,无法保存草稿。")
815
+ ensure_home()
816
+ if not isinstance(obj, dict):
817
+ raise ValueError("草稿必须是 JSON 对象")
818
+ atomic_json(dream_draft_path(), obj)
819
+ return {"ok": True, "path": str(dream_draft_path())}
820
+
821
+
822
+ def clear_dream_draft() -> None:
823
+ try:
824
+ dream_draft_path().unlink()
825
+ except (FileNotFoundError, OSError):
826
+ pass
827
+
828
+
829
+ def load_dream_state() -> dict:
830
+ path = HOME / "dream_state.json"
831
+ if path.exists():
832
+ d = _slurp_json(path)
833
+ if isinstance(d, dict):
834
+ return d
835
+ return {"last_dream": 0, "last_task": None}
836
+
837
+
832
838
  VERIFY_SAMPLE_FILE = "verify-sample.json"
833
839
 
834
840
 
@@ -882,256 +888,261 @@ def mark_verify_reviewed() -> dict | None:
882
888
  return data
883
889
 
884
890
 
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:
891
+ def apply_dream(result: dict) -> dict:
892
+ ensure_home()
893
+ pending_path = HOME / "dreams" / "pending.json"
894
+ task_id = result.get("task_id")
895
+ applied = {"memories": 0, "forgotten": 0, "persona": [], "rejected": []}
896
+
897
+ # 读-校验-改-写-消费 pending 整体在一把锁里:
898
+ # 1) 两个 apply 并发时,第二个进锁后 pending 已被删,直接拒绝,不会把同一份结果套两遍;
899
+ # 2) 整库 save_all 不会把锁外并发写入的新记忆覆盖丢。
900
+ with _locked(HOME / "hippocampus.jsonl"):
901
+ # 先对任务号:apply 必须对着当前这场的 pending.json,防止把上一场的结果
902
+ # 或乱写的 task_id 应用到现在的记忆上。不对就直接拒绝,不碰任何数据。
903
+ pending_id = None
904
+ if pending_path.exists():
905
+ try:
906
+ pending_id = (json.loads(pending_path.read_text("utf-8")) or {}).get("task_id")
907
+ except Exception:
908
+ pending_id = None
909
+ if pending_id is None:
910
+ raise ValueError("没有待应用的任务:dreams/pending.json 不存在")
911
+ if not task_id:
912
+ # 以前这里 fallback 到 pending_id,等于"缺 task_id 但也放行"——
913
+ # 上一场漏写 task_id 的 apply.json 会静默套用到这一场。改为必须显式带上。
914
+ raise ValueError(
915
+ f"apply 里没有 task_id:为防止把上一场的整理结果套用到这一场,拒绝应用。"
916
+ f"请在 apply.json 里带上 \"task_id\": \"{pending_id}\"。"
917
+ )
918
+ if task_id != pending_id:
919
+ raise ValueError(
920
+ f"任务对不上:apply 里的 task_id={task_id!r},与 pending.json 的 {pending_id!r} 不一致,拒绝应用。"
921
+ )
922
+ records = load_all()
923
+ by_id = {m["id"]: m for m in records if m.get("id")}
924
+ _old_terms_cache = {} # id → terms:锁内缓存旧记忆分词,多条新记忆不重复算
925
+ _verify_pairs = [] # #19 合并前后对照:写入 dreams/verify-sample.json 供抽检
926
+
927
+ # 写入时校验引用(借鉴图数据库 dangling edge 防线):
928
+ # AI 填的 source_ids 可能编造/抄错 id,老版本直接写进 links 就成了死链。
929
+ # 现在落库前先对一遍现库,不存在的 id 丢弃并留痕。
930
+ _known_ids = set(by_id)
931
+ for item in result.get("memories") or []:
932
+ if isinstance(item, dict) and item.get("source_ids"):
933
+ bad = [sid for sid in item["source_ids"]
934
+ if isinstance(sid, str) and sid not in _known_ids]
935
+ if bad:
936
+ applied["rejected"].append(
937
+ f"忽略 source_ids 中不存在的引用:{', '.join(bad)}")
938
+ item["source_ids"] = [s for s in item["source_ids"]
939
+ if not (isinstance(s, str) and s in bad)]
940
+
941
+ for item in result.get("memories") or []:
942
+ if not isinstance(item, dict):
943
+ continue
944
+ text = (item.get("text") or "").strip()
945
+ if not text:
946
+ continue
947
+ rec = make_record(
948
+ text,
949
+ kind=item.get("kind", "fact"),
950
+ importance=_num(item.get("importance"), 0.7),
951
+ tags=item.get("tags"),
952
+ entities=item.get("entities"),
953
+ source="dream",
954
+ layer="cortex",
955
+ links=[x for x in (item.get("source_ids") or []) if isinstance(x, str)],
956
+ )
957
+ rec["gist"] = item.get("gist") or heuristic_gist(text)
958
+ rec["consolidated"] = True
959
+ rec["detail"] = 1.0
960
+ # AI 整理出来的记忆先标"待审核":防止做梦合并/编造的内容直接当事实沉淀。
961
+ # 例外:机械聚合摘要(aggregate=True)只是把 N 条原文用「;」连起来的派生视图,
962
+ # 没有可审的"新事实",进待审只会每天占住"待审核1条"(P9 #64)。
963
+ if item.get("aggregate"):
964
+ rec["aggregate"] = True
965
+ else:
966
+ rec["review"] = "pending"
967
+ rec["review_source"] = "dream"
968
+ # #46 Memex 索引解引用:合并/蒸馏产物带 evidence_ids 指针(指向原始证据记忆),
969
+ # 召回命中摘要时按需解引用取原文,"概括"与"细节"两级可导航。
970
+ # 证据 = AI 声明的 source_ids + 确实被本条取代的旧记忆,宁可多指针不丢证据。
971
+ _ev = [s for s in rec.get("links", []) if isinstance(s, str)]
972
+ _ev += [old["id"] for old in records
973
+ if old.get("superseded_by") == rec["id"] and old.get("id")]
974
+ if _ev:
975
+ rec["evidence_ids"] = _dedupe(_ev)
976
+ # #45 影响评估(SSGM):合并/蒸馏决议附轻量 impact——这条记忆一旦确认,
977
+ # 会改变多少召回注入文本、波及哪些实体,让用户优先审"影响大"的改动。
978
+ rec["impact"] = {
979
+ "chars": len(text), # 确认后进入注入文本的字数
980
+ "entities": list(rec.get("entities", []) or []),
981
+ "superseded": sum(1 for old in records
982
+ if old.get("superseded_by") == rec["id"]),
983
+ }
984
+ # —— 矛盾记忆不覆盖,留链路 ——
985
+ # 新记忆与旧记忆高度相似但内容不同(说法变了/事实更新)时,旧的不删,
986
+ # 打上 superseded_by 指向新的:回忆默认跳过被取代者,需要时仍可回溯
987
+ # "我以前是怎么想的"——像人一样,观念变了但旧观念还在记忆深处。
988
+ # 大库时锁内 O(n²) 比对会堵死其他写进程:先用词交集粗筛出候选
989
+ # (jaccard ≥0.55 必有足够交集),再只对候选做精比对。
990
+ new_terms = terms(text)
991
+ _cand_threshold = len(new_terms) * 0.55
992
+ for old in records:
982
993
  # 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
994
+ if old.get("layer") == "dust" or old.get("superseded_by"):
995
+ continue
996
+ # #28 冻结的记忆不许被做梦改写:用户明确要求"这条别动"
997
+ if old.get("frozen"):
998
+ continue
999
+ # #41:correction 改口记录不许被做梦产出 supersede——它是最新的用户更正,
1000
+ # 被取代等于把刚纠正过的事实又改回去
1001
+ if old.get("correction"):
1002
+ continue
1003
+ old_terms = _old_terms_cache.get(old["id"])
1004
+ if old_terms is None:
1005
+ old_terms = terms(str(old.get("text", "")))
1006
+ _old_terms_cache[old["id"]] = old_terms
1007
+ if not old_terms:
1008
+ continue
1009
+ # 粗筛:交集元素数 < 0.55×|new| 时 jaccard 必然 < 0.55,直接跳过
1010
+ if len(new_terms & old_terms) < _cand_threshold:
1011
+ continue
1012
+ if jaccard(new_terms, old_terms) >= 0.55 and str(old.get("text", "")).strip() != text:
1013
+ old["superseded_by"] = rec["id"]
1014
+ rec.setdefault("links", [])
1015
+ if old["id"] not in rec["links"]:
1016
+ rec["links"].append(old["id"])
1017
+ applied.setdefault("superseded", []).append(old["id"])
1018
+ # #19 留一组"合并前 → 合并后"对照,供事后抽检 AI 有没有改坏原意
1019
+ _verify_pairs.append({
1020
+ "new_id": rec["id"],
1021
+ "after": text,
1022
+ "before": [{"id": old["id"], "text": str(old.get("text", ""))}],
1023
+ })
1024
+ records.append(rec)
1025
+ applied["memories"] += 1
1026
+ for sid in rec["links"]:
1027
+ src = by_id.get(sid)
1028
+ if src:
1029
+ src["consolidated"] = True
1030
+ src["links"] = _dedupe(src.get("links", []) + [rec["id"]])
1031
+ if src.get("layer") == "hippo" and src.get("importance", 0.5) >= 0.5:
1032
+ src["layer"] = "cortex"
1033
+
1034
+ _forget_n = 0
1035
+ for sid in result.get("forget") or []:
1036
+ m = by_id.get(sid)
1037
+ if m and m.get("layer") != "dust":
1038
+ # pinned 与 dream 主循环同一待遇:用户置顶的不许 AI 梦里淡忘——
1039
+ # 否则 apply.json 里给个 pinned id 就能绕过防线
1040
+ if m.get("pinned"):
1041
+ applied["rejected"].append(f"拒绝淡忘 {sid}:用户置顶的记忆不参与做梦淡忘")
1042
+ continue
1043
+ # #28 冻结的记忆同样不参与淡忘
1044
+ if m.get("frozen"):
1045
+ applied["rejected"].append(f"拒绝淡忘 {sid}:已冻结的记忆不参与做梦淡忘")
1046
+ continue
1047
+ # #41:correction 改口记录不许梦淡忘——教训提炼的证据链不能断
1048
+ if m.get("correction"):
1049
+ applied["rejected"].append(f"拒绝淡忘 {sid}:改口(correction)记录永不自动淡忘")
1050
+ continue
1051
+ m["layer"] = "dust"
1052
+ m["forgotten_at"] = now_ts()
1053
+ applied["forgotten"] += 1
1054
+ _forget_n += 1
1055
+ if _forget_n:
1056
+ # 留痕:淡忘是"移入 dust 层"而非删除,但日志记一笔数量,方便审计核对没丢数据
1057
+ log_event("dream", f"本次做梦淡忘 {_forget_n} 条记忆(已移入 dust 淡忘区,可 revive 找回)")
1058
+
1059
+ save_all(records)
1060
+ # #19 抽检样本:落盘 3 组合并前后对照(失败不影响做梦主流程)
1061
+ try:
1062
+ write_verify_sample(_verify_pairs, task_id)
1063
+ except Exception as exc:
1064
+ log_event("dream", f"写抽检样本失败(不影响巩固):{exc}", level="warn")
1065
+ # 人格更新也放在锁内、且必须在"删 pending"之前:AI 产的 persona_updates 可能带 NaN
1066
+ # 等坏值,若先删 pending 再更新人格,人格段一崩这批整理就永远无法重试(pending 已丢)。
1067
+ upd = result.get("persona_updates")
1068
+ upd = upd if isinstance(upd, dict) else {}
1069
+ if upd:
1070
+ evid = [sid for it in (result.get("memories") or [])
1071
+ if isinstance(it, dict) for sid in (it.get("source_ids") or [])
1072
+ if isinstance(sid, str)][:10]
1073
+ # 成形时刻检测:近 14 天内若有峰值情绪(formative=True)事件,本场梦的
1074
+ # traits 漂移走旁路(×2.5 封顶 ±25,绕过双门限)——一次真正的峰值情绪
1075
+ # 本来就足以重塑人,不该被"攒账"机制压制。事件按 ts 倒序,取第一条。
1076
+ formative_ev = None
1077
+ try:
1078
+ import emotion as _emo
1079
+ fe = _emo.formative_events(days=14)
1080
+ formative_ev = fe[0] if fe else None
1081
+ except Exception as exc:
1082
+ log_event("dream", f"读取成形时刻事件失败,按普通漂移处理:{exc}", level="warn")
1083
+ if formative_ev and upd.get("traits"):
1084
+ boosted = {}
1085
+ for k, v in upd["traits"].items():
1086
+ try:
1087
+ boosted[k] = max(-10, min(10, float(v) * 2.5))
1088
+ except (TypeError, ValueError):
1089
+ log_event("dream", f"成形旁路时 traits.{k} 值非法 {v!r},跳过", level="warn")
1090
+ if boosted:
1091
+ upd = {**upd, "traits": boosted}
1092
+ fwhy = (formative_ev.get("why") or formative_ev.get("about") or "").strip()
1093
+ fdesc = f"{formative_ev.get('emotion') or '强烈的情绪'}" + (f"({fwhy})" if fwhy else "")
1094
+ try:
1095
+ applied["rejected"] = update_persona(
1096
+ upd, why="做梦整理", source="dream_formative", evidence=evid,
1097
+ bypass_gate=True, formative_event=fdesc)
1098
+ except Exception as exc:
1099
+ log_event("dream", f"做梦应用时人格更新失败,pending 已保留可重试:{exc}", level="error")
1100
+ raise
1101
+ else:
1102
+ try:
1103
+ applied["rejected"] = update_persona(upd, why="做梦整理", source="dream", evidence=evid)
1104
+ except Exception as exc:
1105
+ log_event("dream", f"做梦应用时人格更新失败,pending 已保留可重试:{exc}", level="error")
1106
+ raise
1107
+ else:
1108
+ try:
1109
+ applied["rejected"] = update_persona(upd, why="做梦整理", source="dream", evidence=evid)
1110
+ except Exception as exc:
1111
+ # 人格更新失败:保留 pending apply 文件让整场可重试(persona 层有锁与校验,
1112
+ # 正常情况下不该崩,这里兜底防 NaN 之外的意外把数据搞丢)
1113
+ log_event("dream", f"做梦应用时人格更新失败,pending 已保留可重试:{exc}", level="error")
1114
+ raise
1115
+ # 在锁内消费 pending:写入与"这场梦已应用"必须同时成立,
1116
+ # 否则并发 apply / 崩溃重试会把这批记忆再套一遍(重复沉淀)。
1117
+ try:
1118
+ pending_path.unlink()
1119
+ except FileNotFoundError:
1120
+ pass
1121
+
1122
+ narrative = (result.get("narrative") or "").strip()
1123
+ if narrative or applied["memories"]:
1124
+ path = HOME / "dreams" / f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_apply.md"
1125
+ body = [f"# 梦的沉淀 · {fmt_time(now_ts())}", f"任务:{task_id}", "",
1126
+ f"新增长期记忆 {applied['memories']} 条,遗忘 {applied['forgotten']} 条。"]
1127
+ if narrative:
1128
+ body += ["", "## 梦里的叙述", narrative]
1129
+ if upd.get("insights"):
1130
+ body += ["", "## 洞见"] + [f"- {x}" for x in upd["insights"]]
1131
+ rej = applied.get("rejected") or []
1132
+ if rej:
1133
+ # 被双门限/锁定/不存在拦下的改动留痕在梦报告里——AI 与人都能看到
1134
+ # "梦想改什么、防线拦了什么",而不是只看到悄悄没生效
1135
+ body += ["", "## 被防线拦下的改动"] + [f"- {x}" for x in rej]
1136
+ try:
1137
+ write_text_atomic(path, "\n".join(body) + "\n")
1138
+ except OSError:
1139
+ pass # 梦境笔记写不进去不影响记忆已落盘,别把成功报成失败
1140
+ # 自认识沉淀:放在 _locked 块之外(autosink 自己加 persona.json 锁,
1141
+ # 嵌套调用同一文件锁会死锁);失败只记日志,不影响梦已落盘。
1142
+ try:
1143
+ applied["self_model"] = self_model_autosink()
1144
+ except Exception as exc:
1145
+ log_event("dream", f"做梦后自认识沉淀失败(不影响梦):{exc}", level="warn")
1146
+ applied["self_model"] = {"ok": False, "error": str(exc)}
1147
+ clear_dream_draft() # 应用成功后,网页里编辑过的那份草稿也一并清掉
1148
+ return applied