lingshu-skill 0.0.0-stage → 3.82.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.
- package/CHANGELOG.md +2605 -0
- package/LICENSE +21 -0
- package/README.md +698 -3
- package/SKILL-lite.md +45 -0
- package/SKILL-tiny.md +37 -0
- package/SKILL.md +379 -0
- package/assets/panel.html +5616 -0
- package/cordis-plugin/lingshu-cron/cordis.patch.yml +3 -0
- package/cordis-plugin/lingshu-cron/index.js +4 -0
- package/cordis-plugin/lingshu-cron/package.json +34 -0
- package/cordis-plugin/lingshu-cron/plugin.js +1040 -0
- package/cordis-plugin/lingshu-guard/plugin.js +473 -0
- package/cordis-plugin/lingshu-im/plugin.js +635 -0
- package/cordis-plugin/lingshu-startup/README.md +123 -0
- package/cordis-plugin/lingshu-startup/cordis.patch.yml +3 -0
- package/cordis-plugin/lingshu-startup/index.js +4 -0
- package/cordis-plugin/lingshu-startup/package.json +25 -0
- package/cordis-plugin/lingshu-startup/plugin.js +352 -0
- package/cordis.patch.yml +3 -0
- package/docs/commands.md +243 -0
- package/docs/mechanics.md +610 -0
- package/docs/models.md +52 -0
- package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +49 -0
- package/docs/panel-api.md +198 -0
- package/docs/recovery.md +90 -0
- package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +53 -0
- package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +804 -0
- package/index.js +102 -0
- package/package.json +52 -6
- package/scripts/_panel_smoke_v299.py +27 -0
- package/scripts/_smoke_v299.py +31 -0
- package/scripts/_sync_trae_cn.py +34 -0
- package/scripts/assembler.py +197 -0
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +53 -0
- package/scripts/astrbot_plugin_lingshu/PATCH_NOTES.md +28 -0
- package/scripts/astrbot_plugin_lingshu/README.md +58 -0
- package/scripts/astrbot_plugin_lingshu/_conf_schema.json +92 -0
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +2605 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +698 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +45 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +37 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +379 -0
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +5616 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +243 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/models.md +52 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/panel-api.md +198 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/recovery.md +90 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_panel_smoke_v299.py +27 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_smoke_v299.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +34 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/assembler.py +197 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +280 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +192 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +46 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +55 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +215 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +165 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +4867 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/context_ab.py +260 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2028 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +1137 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +1180 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/failures.py +107 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/fallback_embed.py +114 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +4745 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth_parts.py +263 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/insights.py +131 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/make_dsh_tgz.py +92 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +242 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +159 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_lesson.py +160 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +210 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_topic.py +177 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +4417 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/npm_prepack.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +115 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +609 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +2703 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +591 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2309 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +195 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +368 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +736 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +228 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +123 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +252 -0
- package/scripts/astrbot_plugin_lingshu/main.py +703 -0
- package/scripts/astrbot_plugin_lingshu/make_checksums.py +87 -0
- package/scripts/astrbot_plugin_lingshu/metadata.yaml +7 -0
- package/scripts/behavior_baseline.py +280 -0
- package/scripts/bench.py +192 -0
- package/scripts/brain.py +46 -0
- package/scripts/check_pressure_sync.py +55 -0
- package/scripts/check_tag.py +215 -0
- package/scripts/check_version.py +265 -0
- package/scripts/checkpoint.py +165 -0
- package/scripts/cli.py +4867 -0
- package/scripts/context_ab.py +260 -0
- package/scripts/core.py +2028 -0
- package/scripts/dream.py +1137 -0
- package/scripts/emotion.py +1180 -0
- package/scripts/failures.py +107 -0
- package/scripts/fallback_embed.py +114 -0
- package/scripts/growth.py +4745 -0
- package/scripts/growth_parts.py +263 -0
- package/scripts/hooks/pre-commit +18 -0
- package/scripts/hooks/pre-push +20 -0
- package/scripts/insights.py +131 -0
- package/scripts/make_dsh_tgz.py +92 -0
- package/scripts/make_manifest.py +254 -0
- package/scripts/make_plugin_zip.py +88 -0
- package/scripts/mem_dialogue.py +242 -0
- package/scripts/mem_embed.py +159 -0
- package/scripts/mem_lesson.py +160 -0
- package/scripts/mem_score.py +210 -0
- package/scripts/mem_topic.py +177 -0
- package/scripts/memory.py +4417 -0
- package/scripts/npm_prepack.py +31 -0
- package/scripts/panel_build.py +115 -0
- package/scripts/panel_cloud.py +609 -0
- package/scripts/panel_server.py +2703 -0
- package/scripts/panels.py +591 -0
- package/scripts/persona.py +2309 -0
- package/scripts/recreate_push.ps1 +117 -0
- package/scripts/retriever.py +195 -0
- package/scripts/run_tests.py +91 -0
- package/scripts/safety.py +368 -0
- package/scripts/session_import.py +736 -0
- package/scripts/session_rag.py +228 -0
- package/scripts/session_summary.py +123 -0
- package/scripts/summarizer.py +252 -0
- package/scripts/sync_engine.py +139 -0
- package/scripts/update_dsh_copy.ps1 +107 -0
- package/start-panel.bat +60 -0
|
@@ -0,0 +1,4417 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""灵枢 —— 灵枢 · 记忆:分层存储、编码/回忆、归档、工作记忆、capture、关联、注入与统计。"""
|
|
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
|
+
import core # noqa: E402 # 教训库 lessons_file() 动态取 core.HOME,--home 切换后指向新目录
|
|
24
|
+
|
|
25
|
+
def detect_conflicts(limit: int = 50) -> list:
|
|
26
|
+
"""启发式扫描"可能矛盾的记忆"(如「我用 Windows」vs「我改用 Linux」)。
|
|
27
|
+
|
|
28
|
+
按实体分组,组内两两比较:词面有交集、且一条带改口/否定信号、另一条不带,
|
|
29
|
+
就列为候选。只做提醒、不下结论——到底矛不矛盾由人来判。
|
|
30
|
+
"""
|
|
31
|
+
records = load_all()
|
|
32
|
+
by_entity: dict[str, list] = {}
|
|
33
|
+
for m in records:
|
|
34
|
+
for ent in (m.get("entities") or []):
|
|
35
|
+
by_entity.setdefault(str(ent), []).append(m)
|
|
36
|
+
|
|
37
|
+
change_cues = ("改用", "换成", "改成", "改为", "不再", "已经不用", "换了", "现在用",
|
|
38
|
+
"现在不用", "不喝", "不吃", "不用", "戒了", "停了", "放弃", "移除", "删了")
|
|
39
|
+
# 否定线索:短语级(去掉单字 "不"/"没"/"别"/"反" 后,"不知道"vs"知道"/"没问题"vs"问题"
|
|
40
|
+
# 这类自然组合就不会再被误判成矛盾候选了)。
|
|
41
|
+
neg_cues = ("不是", "不再", "没有", "没再", "别再", "反而", "不再说", "不再有")
|
|
42
|
+
found, seen = [], set()
|
|
43
|
+
|
|
44
|
+
def flag(a, b, reason):
|
|
45
|
+
key = tuple(sorted((a["id"], b["id"])))
|
|
46
|
+
if key in seen:
|
|
47
|
+
return
|
|
48
|
+
seen.add(key)
|
|
49
|
+
found.append({
|
|
50
|
+
"a": {"id": a["id"], "text": a["text"], "ts": a.get("created")},
|
|
51
|
+
"b": {"id": b["id"], "text": b["text"], "ts": b.get("created")},
|
|
52
|
+
"reason": reason,
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
for ent, members in by_entity.items():
|
|
56
|
+
if len(members) < 2:
|
|
57
|
+
continue
|
|
58
|
+
# 实体聚合时限定同 (channel, user) 作用域内比较:跨 channel 或陌生人的记忆不会互相比矛盾
|
|
59
|
+
_last_scope = None
|
|
60
|
+
_scope_members = []
|
|
61
|
+
|
|
62
|
+
def _in_scope(m1, m2):
|
|
63
|
+
return str(m1.get("channel") or "") == str(m2.get("channel") or "") and str(m1.get("user") or "") == str(m2.get("user") or "")
|
|
64
|
+
|
|
65
|
+
for i in range(len(members)):
|
|
66
|
+
for j in range(i + 1, len(members)):
|
|
67
|
+
a, b = members[i], members[j]
|
|
68
|
+
if a["id"] == b["id"] or not _in_scope(a, b):
|
|
69
|
+
continue
|
|
70
|
+
inter = set(terms(a.get("text", ""))) & set(terms(b.get("text", "")))
|
|
71
|
+
if len(inter) < 1:
|
|
72
|
+
continue
|
|
73
|
+
ca = any(c in a.get("text", "") for c in change_cues)
|
|
74
|
+
cb = any(c in b.get("text", "") for c in change_cues)
|
|
75
|
+
if ca != cb:
|
|
76
|
+
flag(a, b, f"关于「{ent}」的两条记忆词面相近,但其中一条带改口信号"
|
|
77
|
+
"(改用/不再/换成…),可能已经过时或更新了")
|
|
78
|
+
continue
|
|
79
|
+
na = any(c in a.get("text", "") for c in neg_cues)
|
|
80
|
+
nb = any(c in b.get("text", "") for c in neg_cues)
|
|
81
|
+
if na != nb:
|
|
82
|
+
flag(a, b, f"关于「{ent}」的两条记忆一条肯定一条否定,可能互相矛盾")
|
|
83
|
+
|
|
84
|
+
found.sort(key=lambda x: min(x["a"]["ts"] or 0, x["b"]["ts"] or 0), reverse=True)
|
|
85
|
+
return found[:limit]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# ---------------------------------------------------------------- 审核闸
|
|
89
|
+
|
|
90
|
+
def pending_memory_reviews(brief: bool = False) -> list:
|
|
91
|
+
"""AI(做梦等)整理出来、还没人工确认的记忆。
|
|
92
|
+
|
|
93
|
+
brief=True 时 text 只留前 40 个字符(超出加省略号),其余字段不变——
|
|
94
|
+
注入层用它省 token(10 条全文≈+750 token,40 字摘要≈+200 token);
|
|
95
|
+
review / audit 等给人看的路径保持默认全文。
|
|
96
|
+
"""
|
|
97
|
+
out = [m for m in load_all()
|
|
98
|
+
if m.get("review") == "pending" and m.get("layer") != "dust"]
|
|
99
|
+
if not brief:
|
|
100
|
+
return out
|
|
101
|
+
res = []
|
|
102
|
+
for m in out:
|
|
103
|
+
m = dict(m) # 派生摘要副本:绝不改原记录(调用方可能拿去落盘)
|
|
104
|
+
text = str(m.get("text") or "")
|
|
105
|
+
if len(text) > 40: # 按字符截断(中文一字算一字符),不是按字节
|
|
106
|
+
m["text"] = text[:40] + "…"
|
|
107
|
+
res.append(m)
|
|
108
|
+
return res
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def mark_auto_review_pending(mem_ids, review_source: str = "auto") -> int:
|
|
112
|
+
"""AI 自动整理写出的记忆默认进待审池:没有 review 字段的补 review="pending"。
|
|
113
|
+
|
|
114
|
+
只给自动写入路径(work flush / daily 自动做梦沉淀)调用:这是审核闭环的
|
|
115
|
+
"自动写入必待审"兜底。已有 review 的记录一律不覆盖(confirmed/discarded
|
|
116
|
+
不会被降级,用户手动 remember 也不经过这里,完全不受影响)。
|
|
117
|
+
review_source 仅在缺失时补一个来源约定值,已有来源照旧。
|
|
118
|
+
返回本次补标条数。
|
|
119
|
+
"""
|
|
120
|
+
if READONLY:
|
|
121
|
+
return 0
|
|
122
|
+
want = {str(x) for x in (mem_ids or []) if x}
|
|
123
|
+
if not want:
|
|
124
|
+
return 0
|
|
125
|
+
marked = 0
|
|
126
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
127
|
+
records = load_all()
|
|
128
|
+
for m in records:
|
|
129
|
+
if m.get("id") in want and not m.get("review"):
|
|
130
|
+
m["review"] = "pending"
|
|
131
|
+
if not m.get("review_source"):
|
|
132
|
+
m["review_source"] = review_source
|
|
133
|
+
marked += 1
|
|
134
|
+
if marked:
|
|
135
|
+
save_all(records)
|
|
136
|
+
return marked
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def ai_persona_changes(days: int = 7) -> list:
|
|
140
|
+
"""最近 N 天里由 AI(非手动)发起的人格变更,用于溯源与漂移告警。
|
|
141
|
+
|
|
142
|
+
只返回用户尚未查看过的改动(ts > persona._ai_changes_viewed_at),
|
|
143
|
+
这样用户点通知查看后通知就会消失,不会挂着烦 7 天。
|
|
144
|
+
注意:做梦 traits 微调没过漂移门限也会写 history(field 带 "(漂移累积)"
|
|
145
|
+
后缀、to 写"未过门限/未变")——那些行什么都没改,不算 AI 改动,
|
|
146
|
+
否则审核清单和漂移告警会被一堆"没生效的记账"撑得动不动就偏大。
|
|
147
|
+
"""
|
|
148
|
+
p = load_persona()
|
|
149
|
+
cutoff = now_ts() - days * 86400
|
|
150
|
+
viewed = float(p.get("_ai_changes_viewed_at") or 0)
|
|
151
|
+
out = []
|
|
152
|
+
for h in p.get("history", []):
|
|
153
|
+
if float(h.get("ts", 0)) < cutoff:
|
|
154
|
+
continue
|
|
155
|
+
if float(h.get("ts", 0)) <= viewed:
|
|
156
|
+
continue # 已查看过的 AI 改动不再计入通知
|
|
157
|
+
src = str(h.get("source", ""))
|
|
158
|
+
why = str(h.get("why", ""))
|
|
159
|
+
field = str(h.get("field", ""))
|
|
160
|
+
to = h.get("to")
|
|
161
|
+
# 没真正改的记账行:字段带括号注记(如 "traits.幽默(漂移累积)"),
|
|
162
|
+
# 或 to 是"未过门限/未变/撞在边界上"这类说明文字而非实际新值
|
|
163
|
+
if "(" in field:
|
|
164
|
+
continue
|
|
165
|
+
if isinstance(to, str) and ("未过门限" in to or "未变" in to or "边界" in to):
|
|
166
|
+
continue
|
|
167
|
+
# 优先看 source 字段(比 why 可靠);用户自己说的(初识回答、手动编辑、
|
|
168
|
+
# 回滚、面板保存)不算 AI 私改
|
|
169
|
+
if src:
|
|
170
|
+
if src in ("面板", "用户", "手动编辑", "回滚", "restore", "persona restore"):
|
|
171
|
+
continue
|
|
172
|
+
if "初识" in src and "我自己" not in src:
|
|
173
|
+
continue
|
|
174
|
+
out.append(h)
|
|
175
|
+
continue
|
|
176
|
+
if ("用户" in why) or why in ("手动编辑", "回滚", "persona restore") or "初识" in why:
|
|
177
|
+
continue
|
|
178
|
+
out.append(h)
|
|
179
|
+
return out
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def mark_persona_changes_viewed() -> dict:
|
|
183
|
+
"""用户查看了 AI 人格改动通知:记下时间戳,之后这些改动不再计入通知。"""
|
|
184
|
+
if READONLY:
|
|
185
|
+
return {"ok": True}
|
|
186
|
+
# 持 persona.json 写锁内"重新读再写":load_persona() 返回的可能是旧快照,
|
|
187
|
+
# 直接拿去 save 会把并发期间其他进程写入的人格改动覆盖丢。
|
|
188
|
+
with _locked(HOME / "persona.json"):
|
|
189
|
+
p = load_persona()
|
|
190
|
+
p["_ai_changes_viewed_at"] = now_ts()
|
|
191
|
+
save_persona(p)
|
|
192
|
+
return {"ok": True}
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def set_memory_review(mid: str, status: str) -> dict:
|
|
196
|
+
"""确认 / 废弃一条 AI 整理的记忆(confirm → 转正;discard → 移入淡忘区)。"""
|
|
197
|
+
if READONLY:
|
|
198
|
+
raise PermissionError("记忆库当前只读,无法审核。")
|
|
199
|
+
status = str(status or "").strip().lower()
|
|
200
|
+
if status not in ("confirm", "discard"):
|
|
201
|
+
raise ValueError(f"非法 review 状态 {status!r}:只支持 confirm / discard")
|
|
202
|
+
# 读-改-写整体放在写锁里:否则并发的 remember/dream 可能在我们读完之后插入新记忆,
|
|
203
|
+
# 被这里的 save_all 用旧快照整库覆盖而丢失。
|
|
204
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
205
|
+
records = load_all()
|
|
206
|
+
target = next((m for m in records if m.get("id") == mid), None)
|
|
207
|
+
if not target:
|
|
208
|
+
raise ValueError(f"没有这条记忆:{mid}")
|
|
209
|
+
if status == "confirm":
|
|
210
|
+
target["review"] = "confirmed"
|
|
211
|
+
target["review_at"] = now_ts()
|
|
212
|
+
# 冲突裁决落地:这条转正了,它 conflicts 里指向的旧说法正式被取代
|
|
213
|
+
# (superseded_by → 回忆默认跳过旧说法;同时清掉双方的冲突标记)
|
|
214
|
+
for oid in target.get("conflicts") or []:
|
|
215
|
+
old = next((m for m in records if m.get("id") == oid), None)
|
|
216
|
+
if old is not None:
|
|
217
|
+
old["superseded_by"] = mid
|
|
218
|
+
old["conflict_flag"] = False
|
|
219
|
+
old["conflicts"] = [x for x in old.get("conflicts", []) if x != mid]
|
|
220
|
+
if not old.get("conflicts"):
|
|
221
|
+
old.pop("conflicts", None)
|
|
222
|
+
if target.get("conflicts"):
|
|
223
|
+
target.setdefault("links", [])
|
|
224
|
+
target["links"] = list(dict.fromkeys(target["links"] + target["conflicts"]))
|
|
225
|
+
target.pop("conflicts", None)
|
|
226
|
+
target["conflict_flag"] = False
|
|
227
|
+
elif status == "discard":
|
|
228
|
+
# pinned 不许 discard:与 apply_dream 的 forget 同一道防线
|
|
229
|
+
if target.get("pinned"):
|
|
230
|
+
raise ValueError("这条记忆是用户置顶的,不能 discard,请直接 confirm 或手动处理")
|
|
231
|
+
target["layer"] = "dust"
|
|
232
|
+
target["forgotten_at"] = now_ts()
|
|
233
|
+
target["review"] = "discarded"
|
|
234
|
+
# 冲突裁决落地:新说法废弃 → 旧说法继续有效,清掉双方冲突标记
|
|
235
|
+
for oid in target.get("conflicts") or []:
|
|
236
|
+
old = next((m for m in records if m.get("id") == oid), None)
|
|
237
|
+
if old is not None:
|
|
238
|
+
old["conflict_flag"] = False
|
|
239
|
+
old["conflicts"] = [x for x in old.get("conflicts", []) if x != mid]
|
|
240
|
+
target.pop("conflicts", None)
|
|
241
|
+
else:
|
|
242
|
+
raise ValueError("状态只能是 confirm / discard")
|
|
243
|
+
save_all(records)
|
|
244
|
+
return target
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def review_report() -> dict:
|
|
248
|
+
"""待审核清单:AI 记忆 / AI 知识 / AI 人格变更。
|
|
249
|
+
|
|
250
|
+
记忆按影响分(#45:注入字数 + 取代条数加权)降序——影响大的改动排前面,
|
|
251
|
+
用户优先审"合并两条记忆、改写注入文本"这种大动作,而不是一条小补记。
|
|
252
|
+
"""
|
|
253
|
+
mems = []
|
|
254
|
+
# 旧 pending 记录没有 impact.superseded 字段:先扫一遍库建 superseded_by 反查表,
|
|
255
|
+
# 避免 N 条待审记忆 × 整库扫描的 O(n²)
|
|
256
|
+
_sup_count: dict = {}
|
|
257
|
+
for _x in load_all():
|
|
258
|
+
sb = _x.get("superseded_by")
|
|
259
|
+
if sb:
|
|
260
|
+
_sup_count[sb] = _sup_count.get(sb, 0) + 1
|
|
261
|
+
for m in pending_memory_reviews():
|
|
262
|
+
mid = m.get("id")
|
|
263
|
+
if not mid:
|
|
264
|
+
continue # 畸形记录(缺 id)没法在报告里给定位,直接跳过
|
|
265
|
+
imp = m.get("impact") if isinstance(m.get("impact"), dict) else {}
|
|
266
|
+
n_sup = int(imp.get("superseded") or _sup_count.get(mid, 0))
|
|
267
|
+
item = {"id": mid, "text": m.get("text", ""), "created": m.get("created"),
|
|
268
|
+
"source": m.get("review_source", "dream"),
|
|
269
|
+
"impact": {"chars": int(imp.get("chars") or len(m.get("text") or "")),
|
|
270
|
+
"entities": imp.get("entities") or m.get("entities") or [],
|
|
271
|
+
"superseded": n_sup}}
|
|
272
|
+
# 影响分:注入字数为主,每取代一条旧记忆 +50 字当量(改写旧结论影响更大)
|
|
273
|
+
item["_impact_score"] = item["impact"]["chars"] + 50 * item["impact"]["superseded"]
|
|
274
|
+
mems.append(item)
|
|
275
|
+
mems.sort(key=lambda x: x["_impact_score"], reverse=True)
|
|
276
|
+
for x in mems:
|
|
277
|
+
x.pop("_impact_score", None)
|
|
278
|
+
try:
|
|
279
|
+
import growth
|
|
280
|
+
kn = [{"id": k.get("id"), "title": k.get("title", ""), "topic": k.get("topic", "")}
|
|
281
|
+
for k in growth.knowledge_pending()]
|
|
282
|
+
except Exception as e:
|
|
283
|
+
log_event("review", f"待审核知识加载失败(growth 模块):{e}", level="warn")
|
|
284
|
+
kn = []
|
|
285
|
+
return {"memories": mems, "knowledge": kn,
|
|
286
|
+
"lessons": [{"id": l.get("id"), "text": l.get("text", ""),
|
|
287
|
+
"confidence": l.get("confidence", 0.5),
|
|
288
|
+
"evidence": l.get("evidence", [])}
|
|
289
|
+
for l in lessons_for_review()],
|
|
290
|
+
"persona": [{"ts": h.get("ts"), "field": h.get("field"),
|
|
291
|
+
"from": h.get("from"), "to": h.get("to"), "why": h.get("why")}
|
|
292
|
+
for h in ai_persona_changes(7)]}
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def review_counts() -> dict:
|
|
296
|
+
rep = review_report()
|
|
297
|
+
return {"memories": len(rep["memories"]), "knowledge": len(rep["knowledge"]),
|
|
298
|
+
"lessons": len(rep.get("lessons", [])),
|
|
299
|
+
"persona": len(rep["persona"])}
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def bulk_memory_action(ids: list, action: str, value=None) -> dict:
|
|
303
|
+
"""面板批量操作:一次写锁内完成,避免 N 条逐条读-改-写整库。
|
|
304
|
+
|
|
305
|
+
action:
|
|
306
|
+
confirm / discard —— 审核转正 / 废弃(移入淡忘区)
|
|
307
|
+
importance —— 批量设置重要性(value: 0-1 或 0-10)
|
|
308
|
+
add_tags / remove_tags —— 批量加 / 删标签(value: list[str])
|
|
309
|
+
pin / unpin —— 批量置顶 / 取消置顶
|
|
310
|
+
delete —— 批量移入淡忘区(同 forget,不真删,可回捞)
|
|
311
|
+
"""
|
|
312
|
+
if READONLY:
|
|
313
|
+
raise PermissionError("记忆库当前只读,无法批量修改。")
|
|
314
|
+
ids = [str(x) for x in (ids or []) if str(x).strip()]
|
|
315
|
+
if not ids:
|
|
316
|
+
raise ValueError("没有选中任何记忆")
|
|
317
|
+
if action not in ("confirm", "discard", "importance", "add_tags", "remove_tags",
|
|
318
|
+
"pin", "unpin", "freeze", "unfreeze", "delete"):
|
|
319
|
+
raise ValueError("不支持的批量操作")
|
|
320
|
+
# 预校验参数:坏值在动库之前就报清楚,别让 float(None) 之类变成 500
|
|
321
|
+
imp_val = None
|
|
322
|
+
tag_list = None
|
|
323
|
+
if action == "importance":
|
|
324
|
+
try:
|
|
325
|
+
imp_val = float(value)
|
|
326
|
+
except (TypeError, ValueError):
|
|
327
|
+
raise ValueError("重要性必须是数字(1-10)")
|
|
328
|
+
if imp_val < 0 or imp_val > 10:
|
|
329
|
+
raise ValueError("重要性要在 0-10 之间")
|
|
330
|
+
elif action in ("add_tags", "remove_tags"):
|
|
331
|
+
if isinstance(value, str):
|
|
332
|
+
tag_list = [t.strip() for t in re.split(r"[,,;;、\n]+", value) if t.strip()]
|
|
333
|
+
elif isinstance(value, (list, tuple)):
|
|
334
|
+
tag_list = [str(t).strip() for t in value if str(t).strip()]
|
|
335
|
+
else:
|
|
336
|
+
raise ValueError("标签必须是数组,或逗号分隔的文本")
|
|
337
|
+
if not tag_list:
|
|
338
|
+
raise ValueError("没有可用的标签")
|
|
339
|
+
want = set(ids)
|
|
340
|
+
updated = 0
|
|
341
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
342
|
+
records = load_all()
|
|
343
|
+
for m in records:
|
|
344
|
+
if m.get("id") not in want:
|
|
345
|
+
continue
|
|
346
|
+
if action == "confirm":
|
|
347
|
+
m["review"] = "confirmed"
|
|
348
|
+
m["review_at"] = now_ts()
|
|
349
|
+
elif action == "discard":
|
|
350
|
+
m["layer"] = "dust"
|
|
351
|
+
m["forgotten_at"] = now_ts()
|
|
352
|
+
m["review"] = "discarded"
|
|
353
|
+
elif action == "importance":
|
|
354
|
+
# 刻度约定:>1 视为 10 分制(如 8 → 0.8),≤1 视为 0-1 小数。
|
|
355
|
+
# 0.1~1 之间是合法小数;正好 1 当作满分 1.0(10 分制不会写 1)
|
|
356
|
+
m["importance"] = round(max(0.0, min(1.0, imp_val / 10 if imp_val > 1 else imp_val)), 3)
|
|
357
|
+
elif action == "pin":
|
|
358
|
+
m["pinned"] = True
|
|
359
|
+
elif action == "unpin":
|
|
360
|
+
m["pinned"] = False
|
|
361
|
+
elif action == "freeze":
|
|
362
|
+
# #28 冻结 = 保留但不主动出现:召回/注入/做梦都不碰,show 仍可查
|
|
363
|
+
m["frozen"] = True
|
|
364
|
+
m["frozen_at"] = now_ts()
|
|
365
|
+
elif action == "unfreeze":
|
|
366
|
+
m["frozen"] = False
|
|
367
|
+
m.pop("frozen_at", None)
|
|
368
|
+
elif action == "delete":
|
|
369
|
+
if m.get("layer") != "dust":
|
|
370
|
+
m["layer"] = "dust"
|
|
371
|
+
m["forgotten_at"] = now_ts()
|
|
372
|
+
m["detail"] = round(max(0.15, _num(m.get("detail"), 1.0) * 0.5), 2)
|
|
373
|
+
elif action == "add_tags":
|
|
374
|
+
cur = [str(t) for t in (m.get("tags") or [])]
|
|
375
|
+
for t in tag_list:
|
|
376
|
+
if t not in cur:
|
|
377
|
+
cur.append(t)
|
|
378
|
+
m["tags"] = cur
|
|
379
|
+
elif action == "remove_tags":
|
|
380
|
+
drop = set(tag_list)
|
|
381
|
+
m["tags"] = [str(t) for t in (m.get("tags") or []) if str(t) not in drop]
|
|
382
|
+
updated += 1
|
|
383
|
+
if updated:
|
|
384
|
+
save_all(records)
|
|
385
|
+
# v4 #32:批量操作审计(含批量 delete/importance 等)
|
|
386
|
+
audit_log("panel", f"bulk_{action}", f"{len(ids)}条", f"成功 {updated} 条")
|
|
387
|
+
return {"updated": updated, "requested": len(ids), "action": action,
|
|
388
|
+
"review_counts": review_counts()}
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def audit() -> dict:
|
|
392
|
+
"""一次自查:待审核项 + 冲突记忆 + 该做什么。"""
|
|
393
|
+
rep = review_report()
|
|
394
|
+
conf = detect_conflicts(20)
|
|
395
|
+
tips = []
|
|
396
|
+
if rep["memories"]:
|
|
397
|
+
tips.append(f"有 {len(rep['memories'])} 条 AI 整理的记忆待审核:"
|
|
398
|
+
"`review` 看全文 → `review confirm <id>` 或 `review discard <id>`。")
|
|
399
|
+
if rep["knowledge"]:
|
|
400
|
+
tips.append(f"有 {len(rep['knowledge'])} 条知识待审核:`knowledge review` → confirm/discard。")
|
|
401
|
+
if rep.get("lessons"):
|
|
402
|
+
tips.append(f"有 {len(rep['lessons'])} 条做梦提炼的教训待审核(#36):"
|
|
403
|
+
"`review` 看清单 → `review confirm <les_id>` 转正开始注入。")
|
|
404
|
+
if rep["persona"]:
|
|
405
|
+
tips.append(f"最近 7 天 AI 改了 {len(rep['persona'])} 次人格:"
|
|
406
|
+
"`persona history` 看来源,跑偏就 `persona rollback <序号>`。")
|
|
407
|
+
if conf:
|
|
408
|
+
tips.append(f"有 {len(conf)} 组疑似冲突记忆:`detect-conflicts` 查看,别让旧记忆继续误导。")
|
|
409
|
+
n_arch = len(load_archive())
|
|
410
|
+
if n_arch:
|
|
411
|
+
tips.append(f"归档层有 {n_arch} 条冷记忆(默认不参与回忆,原文保留):"
|
|
412
|
+
"`archive search <词>` 找、`archive restore <id>` 回捞。")
|
|
413
|
+
if not tips:
|
|
414
|
+
tips.append("干净:没有待审核项、没有明显冲突。")
|
|
415
|
+
return {"counts": {"memories": len(rep["memories"]),
|
|
416
|
+
"knowledge": len(rep["knowledge"]),
|
|
417
|
+
"lessons": len(rep.get("lessons", [])),
|
|
418
|
+
"persona": len(rep["persona"]),
|
|
419
|
+
"conflicts": len(conf),
|
|
420
|
+
"archive": n_arch},
|
|
421
|
+
"review": rep, "conflicts": conf, "tips": tips}
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def diagnose() -> dict:
|
|
425
|
+
"""自诊断(doctor 思路):不只展示记忆,还归因异常。
|
|
426
|
+
|
|
427
|
+
检查项:
|
|
428
|
+
- dead_links 死链:links/conflicts/superseded_by 指向不存在的 id(多来自手删/迁移丢数据)
|
|
429
|
+
- open_conflicts 冲突未裁决:conflict_flag=True 的记忆对
|
|
430
|
+
- bloat 数据膨胀:各层条数/单条超长/总体积异常,给出行数与阈值判断
|
|
431
|
+
- folded/dust 淡忘区状态:折叠了多少、可还原通道是否健康
|
|
432
|
+
- origin 来源归属完整率:project/session 字段缺失比例(老数据兼容性)
|
|
433
|
+
"""
|
|
434
|
+
records = load_all()
|
|
435
|
+
arch = load_archive()
|
|
436
|
+
all_ids = {m.get("id") for m in records + arch if m.get("id")}
|
|
437
|
+
|
|
438
|
+
# 死链:每条记忆的 links / conflicts / superseded_by 指向的 id 必须存在
|
|
439
|
+
dead = []
|
|
440
|
+
for m in records + arch:
|
|
441
|
+
mid = m.get("id")
|
|
442
|
+
refs = list(m.get("links") or [])
|
|
443
|
+
refs += list(m.get("conflicts") or [])
|
|
444
|
+
if m.get("superseded_by"):
|
|
445
|
+
refs.append(m["superseded_by"])
|
|
446
|
+
missing = [r for r in refs if r and r not in all_ids]
|
|
447
|
+
if missing:
|
|
448
|
+
dead.append({"id": mid, "missing": missing,
|
|
449
|
+
"text": (m.get("gist") or m.get("text", ""))[:60]})
|
|
450
|
+
|
|
451
|
+
# 冲突未裁决
|
|
452
|
+
open_conf = [{"id": m.get("id"), "text": (m.get("gist") or m.get("text", ""))[:60],
|
|
453
|
+
"conflicts": list(m.get("conflicts") or [])}
|
|
454
|
+
for m in records if m.get("conflict_flag")]
|
|
455
|
+
|
|
456
|
+
# 数据膨胀:条数 / 超长条 / 文件体积
|
|
457
|
+
sizes = {}
|
|
458
|
+
total_bytes = 0
|
|
459
|
+
for fname in ("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl", "archive.jsonl"):
|
|
460
|
+
f = HOME / fname
|
|
461
|
+
if f.exists():
|
|
462
|
+
b = f.stat().st_size
|
|
463
|
+
sizes[fname] = b
|
|
464
|
+
total_bytes += b
|
|
465
|
+
long_rows = [{"id": m.get("id"), "len": len(m.get("text", ""))}
|
|
466
|
+
for m in records if len(str(m.get("text", ""))) > 4000]
|
|
467
|
+
layer_counts = {"hippo": 0, "cortex": 0, "dust": 0, "archive": 0}
|
|
468
|
+
for m in records:
|
|
469
|
+
lc = m.get("layer", "hippo")
|
|
470
|
+
layer_counts[lc if lc in layer_counts else "hippo"] += 1
|
|
471
|
+
layer_counts["archive"] = len(arch)
|
|
472
|
+
bloat_warn = []
|
|
473
|
+
if layer_counts["dust"] > layer_counts["hippo"] + layer_counts["cortex"] and layer_counts["dust"] > 200:
|
|
474
|
+
bloat_warn.append(f"淡忘区 {layer_counts['dust']} 条已超过活跃层总和——考虑 fold 折叠或 archive 归档")
|
|
475
|
+
if total_bytes > 50 * 1024 * 1024:
|
|
476
|
+
bloat_warn.append(f"数据总体积 {total_bytes // 1024 // 1024}MB 偏大,检查是否有超长记忆条")
|
|
477
|
+
if long_rows:
|
|
478
|
+
bloat_warn.append(f"{len(long_rows)} 条记忆正文超过 4000 字,回忆注入会浪费上下文")
|
|
479
|
+
|
|
480
|
+
# 淡忘可逆通道
|
|
481
|
+
dust_rows = [m for m in records if m.get("layer") == "dust"]
|
|
482
|
+
folded_n = sum(1 for m in dust_rows if m.get("folded"))
|
|
483
|
+
|
|
484
|
+
# 来源归属完整率(新写入强制带,老数据可能缺 → 统计提示)
|
|
485
|
+
with_origin = sum(1 for m in records if m.get("project"))
|
|
486
|
+
origin_pct = round(with_origin * 100 / len(records), 1) if records else 100.0
|
|
487
|
+
|
|
488
|
+
problems = []
|
|
489
|
+
if dead:
|
|
490
|
+
problems.append(f"{len(dead)} 条记忆带死链(指向不存在的 id)——多是做梦 apply 时 source_ids "
|
|
491
|
+
f"填了库里没有的 id(老版本写入时不校验);不影响数据本身,"
|
|
492
|
+
f"可在面板点「清理死链」或跑 `memory fix-links` 一键清掉断链")
|
|
493
|
+
if open_conf:
|
|
494
|
+
problems.append(f"{len(open_conf)} 条冲突未裁决,旧说法仍在生效——去「记忆」页裁决")
|
|
495
|
+
for w in bloat_warn:
|
|
496
|
+
problems.append(w)
|
|
497
|
+
|
|
498
|
+
return {"ok": not problems,
|
|
499
|
+
"problems": problems,
|
|
500
|
+
"dead_links": dead[:50],
|
|
501
|
+
"open_conflicts": open_conf[:50],
|
|
502
|
+
"bloat": {"layer_counts": layer_counts, "file_sizes": sizes,
|
|
503
|
+
"total_bytes": total_bytes, "long_rows": long_rows[:20]},
|
|
504
|
+
"dust": {"count": len(dust_rows), "folded": folded_n},
|
|
505
|
+
"origin": {"with_project": with_origin, "total": len(records), "pct": origin_pct}}
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def fix_dead_links() -> dict:
|
|
509
|
+
"""一键清理死链(图数据库 dangling edge 的惰性 GC 思路):
|
|
510
|
+
|
|
511
|
+
扫描全部记忆(含归档层)的 links / conflicts / superseded_by,
|
|
512
|
+
把指向不存在 id 的引用摘除,保留合法引用与记忆本身——只清链、不删记忆,
|
|
513
|
+
数据零损失。superseded_by 被清掉的旧说法恢复"可被回忆看到"(本来指向的
|
|
514
|
+
新说法不存在,取代关系不成立)。清理前自动打快照备份。
|
|
515
|
+
"""
|
|
516
|
+
if READONLY:
|
|
517
|
+
raise PermissionError("记忆库当前只读,无法清理死链。")
|
|
518
|
+
ensure_home()
|
|
519
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
520
|
+
records = load_all()
|
|
521
|
+
arch = load_archive()
|
|
522
|
+
all_ids = {m.get("id") for m in records + arch if m.get("id")}
|
|
523
|
+
changed, removed = 0, 0
|
|
524
|
+
for m in records + arch:
|
|
525
|
+
fixed = False
|
|
526
|
+
links = [x for x in (m.get("links") or []) if x in all_ids]
|
|
527
|
+
if links != (m.get("links") or []):
|
|
528
|
+
removed += len((m.get("links") or [])) - len(links)
|
|
529
|
+
m["links"] = links
|
|
530
|
+
fixed = True
|
|
531
|
+
if m.get("conflicts"):
|
|
532
|
+
conf = [x for x in m["conflicts"] if x in all_ids]
|
|
533
|
+
if conf != m["conflicts"]:
|
|
534
|
+
removed += len(m["conflicts"]) - len(conf)
|
|
535
|
+
if conf:
|
|
536
|
+
m["conflicts"] = conf
|
|
537
|
+
else:
|
|
538
|
+
m.pop("conflicts", None)
|
|
539
|
+
m.pop("conflict_flag", None) # 双方都没了,冲突标记自然解除
|
|
540
|
+
fixed = True
|
|
541
|
+
if m.get("superseded_by") and m["superseded_by"] not in all_ids:
|
|
542
|
+
m.pop("superseded_by")
|
|
543
|
+
removed += 1
|
|
544
|
+
fixed = True
|
|
545
|
+
if fixed:
|
|
546
|
+
changed += 1
|
|
547
|
+
if changed:
|
|
548
|
+
# records(三个热层)与 arch(归档层)都已在原对象上就地修好,分别写回:
|
|
549
|
+
# 归档层走专用通道覆写,不能混进 save_all(否则可能把归档文件清空)
|
|
550
|
+
if arch:
|
|
551
|
+
write_jsonl(HOME / "archive.jsonl", arch)
|
|
552
|
+
save_all(records)
|
|
553
|
+
log_event("diagnose", f"清理死链:修正 {changed} 条记忆、摘除 {removed} 个断链引用")
|
|
554
|
+
return {"fixed_records": changed, "removed_refs": removed}
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def _mem_hash(m: dict) -> str:
|
|
558
|
+
"""记忆哈希链节点:sha256(text + created + id 规范拼接)。
|
|
559
|
+
|
|
560
|
+
v3.02 #25:每条记忆带 h(自身哈希)与 p_h(前一条的 h),构成校验链。
|
|
561
|
+
只在新写入路径调用,recall 热路径绝不碰——不为校验拖慢回忆。
|
|
562
|
+
"""
|
|
563
|
+
raw = f"{m.get('text', '')}\x1f{m.get('created', 0)}\x1f{m.get('id', '')}"
|
|
564
|
+
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def _seal_chain(records: list) -> None:
|
|
568
|
+
"""写盘前统一封链:给每条记忆重算 h、按顺序串 p_h(前一条的 h)。
|
|
569
|
+
|
|
570
|
+
v3.02 #25:只在合法写入路径调用(remember 新增/合并都会改文本,统一重算
|
|
571
|
+
才不会把自家写入误判成篡改)。历史存量记忆没有 h:首次写入时按当前顺序
|
|
572
|
+
静默补齐——verify 对无 h 的条目跳过不算断裂,老库不报错,新写入续链。
|
|
573
|
+
"""
|
|
574
|
+
prev = ""
|
|
575
|
+
for m in records:
|
|
576
|
+
if not isinstance(m, dict) or not m.get("id"):
|
|
577
|
+
continue
|
|
578
|
+
m["h"] = _mem_hash(m)
|
|
579
|
+
m["p_h"] = prev
|
|
580
|
+
prev = m["h"]
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def verify_integrity() -> dict:
|
|
584
|
+
"""v3.02 #25:校验记忆哈希链完整性(热层 + 归档层)。
|
|
585
|
+
|
|
586
|
+
返回 {"ok": bool, "broken_at": id 或 None, "count": n}。无 h 的条目
|
|
587
|
+
(历史存量)跳过不计为断裂;坏链只报告不修复。注意本函数只读不写。
|
|
588
|
+
"""
|
|
589
|
+
rows = load_all() + load_archive()
|
|
590
|
+
prev = ""
|
|
591
|
+
broken_at, broken_id = -1, None
|
|
592
|
+
for i, m in enumerate(rows):
|
|
593
|
+
if not isinstance(m, dict) or not m.get("h"):
|
|
594
|
+
continue # 存量无哈希:跳过,不计断裂
|
|
595
|
+
if broken_at < 0:
|
|
596
|
+
# 链断判定:自身哈希对不上(内容被改),或 p_h 与前一条带哈希的 h 对不上(条目被插/删)
|
|
597
|
+
if _mem_hash(m) != m["h"]:
|
|
598
|
+
broken_at, broken_id = i, m["id"]
|
|
599
|
+
elif prev and m.get("p_h") != prev:
|
|
600
|
+
broken_at, broken_id = i, m["id"]
|
|
601
|
+
prev = m["h"]
|
|
602
|
+
return {"ok": broken_at < 0, "broken_at": broken_id, "count": len(rows),
|
|
603
|
+
"broken_pos": broken_at if broken_at >= 0 else None}
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def load_all() -> list:
|
|
607
|
+
"""三层热层合并;缺 id 或不是 dict 的畸形记录一律跳过——
|
|
608
|
+
项目里没有任何调用方想处理畸形记录,在这里统一过滤最省事。"""
|
|
609
|
+
raw = read_jsonl(HOME / "hippocampus.jsonl") + read_jsonl(HOME / "cortex.jsonl") + read_jsonl(HOME / "dust.jsonl")
|
|
610
|
+
good, bad = [], 0
|
|
611
|
+
for r in raw:
|
|
612
|
+
if isinstance(r, dict) and r.get("id"):
|
|
613
|
+
good.append(r)
|
|
614
|
+
else:
|
|
615
|
+
bad += 1
|
|
616
|
+
if bad:
|
|
617
|
+
log_event("load", f"load_all 跳过 {bad} 条畸形记录(缺 id 或类型错)", level="warning")
|
|
618
|
+
return good
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
def count_recent(layer: str, floor_ts: float, predicate=None) -> int:
|
|
622
|
+
"""只数不取:按时间下界流式统计某层新增记录数,避免全量 load_all 撑爆列表。
|
|
623
|
+
|
|
624
|
+
JSONL 本来就要逐行扫(数据结构决定的),但这里逐行解析后只保留计数,
|
|
625
|
+
不把所有 dict 攒进内存——统计/水位提醒这类只关心数量的场景省掉大对象。
|
|
626
|
+
"""
|
|
627
|
+
path = HOME / f"{layer}.jsonl"
|
|
628
|
+
if not path.exists():
|
|
629
|
+
return 0
|
|
630
|
+
n = 0
|
|
631
|
+
for r in read_jsonl(path):
|
|
632
|
+
if not (isinstance(r, dict) and r.get("id")):
|
|
633
|
+
continue
|
|
634
|
+
if _num(r.get("created"), 0) < floor_ts:
|
|
635
|
+
continue
|
|
636
|
+
if predicate is None or predicate(r):
|
|
637
|
+
n += 1
|
|
638
|
+
return n
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def load_archive() -> list:
|
|
642
|
+
"""归档层独立读取:load_all 不含 archive,热查询集保持精简。
|
|
643
|
+
|
|
644
|
+
所有现有路径(recall/forget/dream/remember…)行为不变;需要全量计数或展示时
|
|
645
|
+
(stats / 面板 / audit / archive 命令)再显式合并 load_archive()。
|
|
646
|
+
"""
|
|
647
|
+
raw = read_jsonl(HOME / "archive.jsonl")
|
|
648
|
+
good, bad = [], 0
|
|
649
|
+
for r in raw:
|
|
650
|
+
if isinstance(r, dict) and r.get("id"):
|
|
651
|
+
good.append(r)
|
|
652
|
+
else:
|
|
653
|
+
bad += 1
|
|
654
|
+
if bad:
|
|
655
|
+
log_event("load", f"load_archive 跳过 {bad} 条畸形记录", level="warning")
|
|
656
|
+
return good
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def due_for_review(limit: int = 10) -> list:
|
|
660
|
+
"""v3.02 #10:到期该复核的事实类记忆。
|
|
661
|
+
|
|
662
|
+
记入时带 --ttl/--review-at 的记忆,过了 review_by 时间点就算到期。
|
|
663
|
+
只挑、不删不改——到期是"该找用户确认一下这条还作数吗",不是失效。
|
|
664
|
+
已被复核确认过的(review_by_confirmed)不再重复提醒。
|
|
665
|
+
"""
|
|
666
|
+
now = now_ts()
|
|
667
|
+
out = []
|
|
668
|
+
for m in load_all() + load_archive():
|
|
669
|
+
if m.get("layer") in ("dust",):
|
|
670
|
+
continue
|
|
671
|
+
by = _num(m.get("review_by"), 0)
|
|
672
|
+
if not by or by > now:
|
|
673
|
+
continue
|
|
674
|
+
if m.get("review_by_confirmed"):
|
|
675
|
+
continue
|
|
676
|
+
out.append(m)
|
|
677
|
+
out.sort(key=lambda m: _num(m.get("review_by"), 0)) # 最早到期的先提醒
|
|
678
|
+
return out[:limit]
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def mark_reviewed(mem_id: str) -> dict:
|
|
682
|
+
"""v3.02 #10:复核确认——用户确认这条事实仍作数。
|
|
683
|
+
|
|
684
|
+
打 review_by_confirmed 标,due_for_review 不再挑它;有 ttl 的把 review_by
|
|
685
|
+
顺延一个周期(确认一次=再来一轮保质期)。走 _strengthen_write 定向补丁,
|
|
686
|
+
不整文件重写。
|
|
687
|
+
"""
|
|
688
|
+
if READONLY:
|
|
689
|
+
raise PermissionError("记忆库当前只读,无法执行复核确认。")
|
|
690
|
+
ensure_home()
|
|
691
|
+
mid = str(mem_id or "").strip()
|
|
692
|
+
found = None
|
|
693
|
+
for m in load_all() + load_archive():
|
|
694
|
+
if str(m.get("id") or "") == mid:
|
|
695
|
+
found = dict(m)
|
|
696
|
+
break
|
|
697
|
+
if not found:
|
|
698
|
+
raise LookupError(f"没找到记忆 {mid}。")
|
|
699
|
+
ttl = _num(found.get("ttl_days"), 0)
|
|
700
|
+
found["review_by_confirmed"] = now_ts()
|
|
701
|
+
if ttl > 0:
|
|
702
|
+
found["review_by"] = int(now_ts() + ttl * DAY)
|
|
703
|
+
# 落盘成败必须可见:_patch_memory_fields 返回 False = 定向补丁没写成功
|
|
704
|
+
# (锁内按 id 复读时目标已不在任何层,或磁盘瞬时读不到)。旧实现忽略返回值,
|
|
705
|
+
# 于是返回"成功形状"的 dict,调用方会打印"已确认复核"而盘上仍是到期态。
|
|
706
|
+
# 抛 LookupError 而非返回 {"ok": False}:cli.py review-confirm 现有
|
|
707
|
+
# `except (LookupError, PermissionError)` 能接住并以退出码 1 报错,
|
|
708
|
+
# 不把失败伪装成成功;真正的写盘异常(PermissionError/OSError)继续原样上抛。
|
|
709
|
+
if not core._patch_memory_fields(found):
|
|
710
|
+
raise LookupError(
|
|
711
|
+
f"复核确认未落盘:目标记忆 {mid} 在写入时已找不到"
|
|
712
|
+
"(可能已被删除/归档,或磁盘暂时读不到,请稍后重试)。")
|
|
713
|
+
log_event("memory", f"事实复核确认:{mid}")
|
|
714
|
+
return found
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
def _hay(m: dict) -> str:
|
|
718
|
+
"""廉价的"可检索全文"拼接(小写):text + tags + entities。
|
|
719
|
+
|
|
720
|
+
用于 recall/remember/archive search 的第一道预筛(子串包含测试)。数学上不丢召回:
|
|
721
|
+
relevance/jaccard 非零当且仅当查询 term 与文档 terms 共享,而共享 term 必然是
|
|
722
|
+
本文档某段文本的连续子串 → `t in hay` 必为真。统一小写,英文词忽略大小写。
|
|
723
|
+
"""
|
|
724
|
+
parts = [str(m.get("text") or "")]
|
|
725
|
+
for k in ("tags", "entities"):
|
|
726
|
+
parts.append(" ".join(str(x) for x in (m.get(k) or [])))
|
|
727
|
+
return "\n".join(parts).lower()
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
def _is_archivable(m: dict, now: int) -> bool:
|
|
731
|
+
"""单条判断:是否该被雪藏进归档层。archive_candidates / dream 共用同一套条件,避免漂移。"""
|
|
732
|
+
if not m.get("id"):
|
|
733
|
+
return False # 畸形记录(缺 id)不能进候选集——后续的 dict 推导都会 KeyError
|
|
734
|
+
if m.get("layer") not in ("hippo", "cortex"):
|
|
735
|
+
return False
|
|
736
|
+
if m.get("pinned") or m.get("verbatim") or m.get("kind") == "identity":
|
|
737
|
+
return False
|
|
738
|
+
if m.get("review") == "pending":
|
|
739
|
+
return False
|
|
740
|
+
imp = _num(m.get("importance"), 0.5)
|
|
741
|
+
age = now - _num(m.get("created"), now)
|
|
742
|
+
R = retention(m, now)
|
|
743
|
+
idle = now - _num(m.get("last_access"), _num(m.get("created"), now))
|
|
744
|
+
if imp > ARCHIVE_MAX_IMPORTANCE or R >= ARCHIVE_RETENTION:
|
|
745
|
+
return False
|
|
746
|
+
if age < ARCHIVE_MIN_AGE_DAYS * DAY:
|
|
747
|
+
return False
|
|
748
|
+
if int(m.get("access_count", 0) or 0) > 0 and idle < ARCHIVE_IDLE_DAYS * DAY:
|
|
749
|
+
return False
|
|
750
|
+
return True
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
def archive_candidates(records: list, now: int | None = None) -> list:
|
|
754
|
+
"""选出符合"沉眠"条件的记忆:保留度极低 + 低重要 + 满月 + 长期没被想起。
|
|
755
|
+
|
|
756
|
+
不碰 pinned / 封存原文 / 身份记忆 / 待审核项。返回记录本身(调用方决定是否落盘)。
|
|
757
|
+
"""
|
|
758
|
+
now = now or now_ts()
|
|
759
|
+
return [m for m in records if _is_archivable(m, now)]
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def _append_archive(new_rows: list) -> None:
|
|
763
|
+
"""把记录并入 archive.jsonl,按 id 去重。
|
|
764
|
+
先写 archive、后从热层删除(顺序上防丢);若上一次在两步之间被打断,
|
|
765
|
+
记录会同时留在热层和 archive,重跑时这里按 id 去重,不会越堆越多。"""
|
|
766
|
+
if not new_rows:
|
|
767
|
+
return
|
|
768
|
+
# archive.jsonl 的读-改-写自身加锁:调用方(archive_run/dream)只持热层锁,
|
|
769
|
+
# 没有互斥保护 archive;restore 那边是两把锁都持,不加这把会互相踩丢行。
|
|
770
|
+
with _locked(HOME / "archive.jsonl"):
|
|
771
|
+
existing = load_archive()
|
|
772
|
+
have = {m.get("id") for m in existing if m.get("id")}
|
|
773
|
+
add = [m for m in new_rows if m.get("id") not in have]
|
|
774
|
+
if add:
|
|
775
|
+
write_jsonl(HOME / "archive.jsonl", existing + add)
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
def archive_run(dry_run: bool = False) -> dict:
|
|
779
|
+
"""手动触发归档:把沉眠记忆雪藏进 archive 层(原文保真,永不删)。
|
|
780
|
+
|
|
781
|
+
读-改-写整体放在写锁里(统一锚点 hippocampus.jsonl),与 remember/dream 互斥。
|
|
782
|
+
"""
|
|
783
|
+
if READONLY and not dry_run:
|
|
784
|
+
raise PermissionError("记忆库当前只读,无法归档。")
|
|
785
|
+
now = now_ts()
|
|
786
|
+
if dry_run:
|
|
787
|
+
# 预览不写盘,也不抢写锁(只读环境下锁文件也可能建不了)
|
|
788
|
+
cand = archive_candidates(load_all(), now)
|
|
789
|
+
return {"count": len(cand),
|
|
790
|
+
"archived": [{"id": m["id"], "gist": m.get("gist") or heuristic_gist(m.get("text", ""))}
|
|
791
|
+
for m in cand],
|
|
792
|
+
"dry_run": True}
|
|
793
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
794
|
+
records = load_all()
|
|
795
|
+
cand = archive_candidates(records, now)
|
|
796
|
+
arch = [{"id": m["id"], "gist": m.get("gist") or heuristic_gist(m.get("text", ""))}
|
|
797
|
+
for m in cand]
|
|
798
|
+
if not dry_run and cand:
|
|
799
|
+
for m in cand:
|
|
800
|
+
m["layer"] = ARCHIVE_LAYER
|
|
801
|
+
m["archived_at"] = now
|
|
802
|
+
keep_ids = {m["id"] for m in cand}
|
|
803
|
+
# 归档层文件单独维护:只在本次真的新增了归档时才重写,绝不整库覆写清空
|
|
804
|
+
_append_archive(cand)
|
|
805
|
+
save_all([m for m in records if m.get("id") not in keep_ids])
|
|
806
|
+
audit_log("dream", "archive_run", f"{len(cand)}条", "冷归档生效")
|
|
807
|
+
return {"count": len(arch), "archived": arch, "dry_run": dry_run}
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
def save_all(records: list) -> None:
|
|
811
|
+
if not READONLY:
|
|
812
|
+
_seal_chain(records) # v3.02 #25:写盘前封哈希链(只读降级不写任何字段)
|
|
813
|
+
groups = {"hippo": [], "cortex": [], "dust": []}
|
|
814
|
+
for r in records:
|
|
815
|
+
layer = r.get("layer", "hippo")
|
|
816
|
+
# 未知层名(损坏的手改数据)归入海马回,绝不静默丢弃
|
|
817
|
+
# archive 记录走专用通道(load_archive 维护),不带进整库覆写,避免把归档文件清空
|
|
818
|
+
if layer != ARCHIVE_LAYER:
|
|
819
|
+
groups[layer if layer in groups else "hippo"].append(r)
|
|
820
|
+
# 三文件尽量同步落盘:先把三个临时文件都写好,再依次 replace。
|
|
821
|
+
# 把"存了一半"的窗口压到最小——只有进程恰好在两次 replace 之间挂掉才可能不一致,
|
|
822
|
+
# 而不是像原来那样每写一个文件就有一个完整窗口。
|
|
823
|
+
targets = [("hippocampus.jsonl", groups["hippo"]),
|
|
824
|
+
("cortex.jsonl", groups["cortex"]),
|
|
825
|
+
("dust.jsonl", groups["dust"])]
|
|
826
|
+
staged = []
|
|
827
|
+
try:
|
|
828
|
+
for fname, rows in targets:
|
|
829
|
+
p = HOME / fname
|
|
830
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
831
|
+
tmp = _tmp_path(p)
|
|
832
|
+
with open(tmp, "w", encoding="utf-8", newline="\n") as f:
|
|
833
|
+
for r in rows:
|
|
834
|
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
|
835
|
+
staged.append((tmp, p))
|
|
836
|
+
except Exception:
|
|
837
|
+
for tmp, _ in staged:
|
|
838
|
+
try:
|
|
839
|
+
os.unlink(tmp)
|
|
840
|
+
except OSError:
|
|
841
|
+
pass
|
|
842
|
+
raise
|
|
843
|
+
for tmp, p in staged:
|
|
844
|
+
_replace_retry(tmp, p)
|
|
845
|
+
|
|
846
|
+
|
|
847
|
+
# ---------------------------------------------------------------- 记忆记录
|
|
848
|
+
|
|
849
|
+
def boost(memory_id: str) -> dict:
|
|
850
|
+
"""遗忘纠正:recall 命中后判定某条淡忘记忆仍重要时,一键拉回——
|
|
851
|
+
last_access 重置为现在(R 回 1、衰减计时归零),稳定度提升一档(×1.5,上限 90 天)。
|
|
852
|
+
|
|
853
|
+
走 _strengthen_write 定向补丁(只 patch stability/last_access,带写锁),
|
|
854
|
+
不整文件重写;不动层归属——在 dust 层要整条复活的走 revive()。
|
|
855
|
+
archive 层记忆不参与强化(core 约定只读展示),需先 archive restore 回热。
|
|
856
|
+
"""
|
|
857
|
+
if READONLY:
|
|
858
|
+
raise PermissionError("记忆库当前只读,无法执行遗忘纠正。")
|
|
859
|
+
ensure_home()
|
|
860
|
+
mid = str(memory_id or "").strip()
|
|
861
|
+
found = None
|
|
862
|
+
for m in load_all():
|
|
863
|
+
if str(m.get("id") or "") == mid:
|
|
864
|
+
found = dict(m)
|
|
865
|
+
break
|
|
866
|
+
if not found:
|
|
867
|
+
raise LookupError(f"没找到记忆 {mid}(活跃层与淡忘区都搜过了)。")
|
|
868
|
+
old_s = _num(found.get("stability"), DEFAULT_STABILITY)
|
|
869
|
+
found["last_access"] = now_ts()
|
|
870
|
+
found["stability"] = min(old_s * 1.5, 90 * DAY)
|
|
871
|
+
found["boosted_at"] = now_ts()
|
|
872
|
+
_strengthen_write([found])
|
|
873
|
+
audit_log("user", "boost", mid, f"stability {old_s:.0f}s→{found['stability']:.0f}s")
|
|
874
|
+
log_event("memory", f"遗忘纠正 {mid}:last_access→now,stability {old_s:.0f}s→{found['stability']:.0f}s")
|
|
875
|
+
return {"ok": True, "id": mid, "layer": found.get("layer"),
|
|
876
|
+
"stability": found["stability"], "old_stability": old_s}
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
def set_frozen(memory_id: str, frozen: bool = True) -> dict:
|
|
880
|
+
"""#28 冻结 / 解冻单条记忆。
|
|
881
|
+
|
|
882
|
+
冻结 = 保留但不主动出现:召回、启动注入、做梦合并/淡忘都跳过它,
|
|
883
|
+
但 show / 面板仍可查看,解冻后立即恢复参与。用于"这条别再用,但也别删"。
|
|
884
|
+
"""
|
|
885
|
+
if READONLY:
|
|
886
|
+
raise PermissionError("记忆库当前只读,无法冻结/解冻。")
|
|
887
|
+
ensure_home()
|
|
888
|
+
mid = str(memory_id or "").strip()
|
|
889
|
+
records = load_all()
|
|
890
|
+
found = next((m for m in records if str(m.get("id") or "") == mid), None)
|
|
891
|
+
if not found:
|
|
892
|
+
raise LookupError(f"没找到记忆 {mid}(活跃层与淡忘区都搜过了)。")
|
|
893
|
+
if bool(found.get("frozen")) == bool(frozen):
|
|
894
|
+
return {"ok": True, "id": mid, "frozen": bool(frozen), "changed": False}
|
|
895
|
+
found["frozen"] = bool(frozen)
|
|
896
|
+
if frozen:
|
|
897
|
+
found["frozen_at"] = now_ts()
|
|
898
|
+
else:
|
|
899
|
+
found.pop("frozen_at", None)
|
|
900
|
+
save_all(records)
|
|
901
|
+
audit_log("user", "freeze" if frozen else "unfreeze", mid, "冻结,不参与召回/注入" if frozen else "解冻")
|
|
902
|
+
log_event("memory", f"{'冻结' if frozen else '解冻'}了 {mid}")
|
|
903
|
+
return {"ok": True, "id": mid, "frozen": bool(frozen), "changed": True}
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
def heuristic_gist(text: str, limit: int = 60) -> str:
|
|
907
|
+
body = re.sub(r"^【[^】]*】\s*", "", (text or "").strip())
|
|
908
|
+
first = re.split(r"[。!?\n;;]", body)[0].strip()
|
|
909
|
+
if not first:
|
|
910
|
+
return body[:limit]
|
|
911
|
+
return first[:limit] + ("…" if len(first) > limit else "")
|
|
912
|
+
|
|
913
|
+
|
|
914
|
+
def _new_id(text: str, ts: int) -> str:
|
|
915
|
+
h = hashlib.sha1(f"{text}{ts}{os.urandom(4).hex()}".encode("utf-8")).hexdigest()[:10]
|
|
916
|
+
return f"m_{ts}_{h}"
|
|
917
|
+
|
|
918
|
+
|
|
919
|
+
def make_record(text: str, kind: str = "fact", importance: float | None = None,
|
|
920
|
+
tags=None, entities=None, source: str = "ai",
|
|
921
|
+
layer: str = "hippo", links=None,
|
|
922
|
+
channel: str | None = None, group_id: str | None = None,
|
|
923
|
+
user: str | None = None,
|
|
924
|
+
project: str | None = None, session: str | None = None) -> dict:
|
|
925
|
+
ts = now_ts()
|
|
926
|
+
text = text.strip()
|
|
927
|
+
tags = _dedupe([t.strip().lstrip("#") for t in (tags or []) if t.strip()])
|
|
928
|
+
entities = _dedupe([e.strip() for e in (entities or []) if e.strip()])
|
|
929
|
+
for tag in re.findall(r"#([\w\u4e00-\u9fff]{1,16})", text):
|
|
930
|
+
if tag not in tags:
|
|
931
|
+
tags.append(tag)
|
|
932
|
+
# importance 可能是模型产出的字符串(如 "0.8")或 NaN——统一走 _num 强转,坏值回落启发式
|
|
933
|
+
imp = heuristic_importance(text, kind) if importance is None else _num(importance, heuristic_importance(text, kind))
|
|
934
|
+
if imp > 1.0: # 允许 0-10 分制
|
|
935
|
+
imp = imp / 10.0
|
|
936
|
+
rec = {
|
|
937
|
+
"id": _new_id(text, ts),
|
|
938
|
+
"created": ts,
|
|
939
|
+
"last_access": ts,
|
|
940
|
+
"kind": kind if kind in KINDS else "fact",
|
|
941
|
+
"text": text,
|
|
942
|
+
"gist": heuristic_gist(text),
|
|
943
|
+
"detail": 1.0,
|
|
944
|
+
"importance": round(max(0.0, min(1.0, imp)), 3),
|
|
945
|
+
"layer": layer,
|
|
946
|
+
"tags": tags,
|
|
947
|
+
"entities": entities,
|
|
948
|
+
"links": links or [],
|
|
949
|
+
"access_count": 0,
|
|
950
|
+
"stability": DEFAULT_STABILITY,
|
|
951
|
+
"source": source,
|
|
952
|
+
"consolidated": False,
|
|
953
|
+
"pinned": False,
|
|
954
|
+
}
|
|
955
|
+
# P5 #20 方案 A(v3.80):用户亲口说的(source="user")本就是事实——直接标
|
|
956
|
+
# review=confirmed,让 auto_archive 能把它们沉淀进知识库。AI 产出(默认
|
|
957
|
+
# "ai"/dream/work-flush 等)一律不标,继续走 pending/审核闸防幻觉固化。
|
|
958
|
+
# 标在 make_record 这一层,remember() 与 capture() 两条写入路径都覆盖;
|
|
959
|
+
# 面板/astrbot 等已经显式传 source="user" 的调用方自动受益,无需各自改。
|
|
960
|
+
if str(source).strip().lower() == "user":
|
|
961
|
+
rec["review"] = "confirmed"
|
|
962
|
+
rec["review_at"] = now_ts()
|
|
963
|
+
rec["review_source"] = "user-statement"
|
|
964
|
+
# 通道三元组(可选):来自聊天平台的记忆带上来源,用于群间隔离与跨群用户画像。
|
|
965
|
+
# 缺省不写入字段 = 传统全局记忆,完全向后兼容(旧数据没有这些字段也照常召回)。
|
|
966
|
+
if channel:
|
|
967
|
+
rec["channel"] = str(channel)
|
|
968
|
+
if group_id:
|
|
969
|
+
rec["group_id"] = str(group_id)
|
|
970
|
+
if user:
|
|
971
|
+
rec["user"] = str(user)
|
|
972
|
+
# —— 来源归属(origin,强制带):项目/会话 id 让每条记忆都能回答「从哪来的」。
|
|
973
|
+
# 冲突检测按同源比较(跨项目不误报),做梦/审计按 source 溯源。
|
|
974
|
+
# 缺省回落到 "default":老数据没有这两个字段照常工作,新写入一律补全。
|
|
975
|
+
rec["project"] = str(project).strip()[:64] if project and str(project).strip() else "default"
|
|
976
|
+
rec["session"] = str(session).strip()[:64] if session and str(session).strip() else "default"
|
|
977
|
+
return rec
|
|
978
|
+
|
|
979
|
+
|
|
980
|
+
def _dedupe(items: list) -> list:
|
|
981
|
+
seen, out = set(), []
|
|
982
|
+
for it in items:
|
|
983
|
+
if it not in seen:
|
|
984
|
+
seen.add(it)
|
|
985
|
+
out.append(it)
|
|
986
|
+
return out
|
|
987
|
+
|
|
988
|
+
|
|
989
|
+
# ---------------------------------------------------------------- 写入 / 检索
|
|
990
|
+
|
|
991
|
+
def _water_level(used_pct: float | None = None) -> dict:
|
|
992
|
+
"""水位结构化信息(唯一数据源):status --json / startup 提醒块 / 面板 / cron 都读这里。
|
|
993
|
+
|
|
994
|
+
used_pct 缺省时用"本会话已落盘记忆条数估算",没有实时上下文可测,
|
|
995
|
+
以最近一次 check-context --used 记下的水位(config.last_session_pct)为参考。
|
|
996
|
+
"""
|
|
997
|
+
cfg = load_config()
|
|
998
|
+
now = now_ts()
|
|
999
|
+
# memory 各层条数(只数不取:逐层流式统计,别为水位把全库载进内存)
|
|
1000
|
+
counts = {}
|
|
1001
|
+
for layer, fname in (("hippocampus", "hippocampus.jsonl"), ("cortex", "cortex.jsonl"),
|
|
1002
|
+
("dust", "dust.jsonl"), ("archive", "archive.jsonl")):
|
|
1003
|
+
fp = HOME / fname
|
|
1004
|
+
try:
|
|
1005
|
+
counts[layer] = sum(1 for ln in fp.open(encoding="utf-8-sig", errors="replace") if ln.strip())
|
|
1006
|
+
except OSError:
|
|
1007
|
+
counts[layer] = 0
|
|
1008
|
+
# 距上次做梦 / 上次交接
|
|
1009
|
+
try:
|
|
1010
|
+
from dream import load_dream_state
|
|
1011
|
+
last_dream = _num(load_dream_state().get("last_dream"), 0)
|
|
1012
|
+
except Exception:
|
|
1013
|
+
last_dream = 0
|
|
1014
|
+
_h = 0
|
|
1015
|
+
try:
|
|
1016
|
+
from dream import latest_handoff as _lh
|
|
1017
|
+
h = _lh()
|
|
1018
|
+
if h:
|
|
1019
|
+
_h = _num(h.get("at") or h.get("ts") or h.get("created"), 0) or _num(h.get("meta", {}).get("ts"), 0)
|
|
1020
|
+
except Exception:
|
|
1021
|
+
_h = 0
|
|
1022
|
+
if not _h:
|
|
1023
|
+
try: # 交接 json 没带时间字段时退回文件 mtime(handoffs 目录按文件名排序取最近)
|
|
1024
|
+
hf = HOME / "handoffs"
|
|
1025
|
+
files = sorted(hf.glob("handoff_*.json")) if hf.exists() else []
|
|
1026
|
+
if files:
|
|
1027
|
+
_h = int(files[-1].stat().st_mtime)
|
|
1028
|
+
except Exception:
|
|
1029
|
+
_h = 0
|
|
1030
|
+
hours_since_dream = (now - last_dream) / 3600 if last_dream else None
|
|
1031
|
+
hours_since_handoff = (now - _h) / 3600 if _h else None
|
|
1032
|
+
# 第几次醒来:startup 标记累计(config.wake_count,cmd_startup 自增)
|
|
1033
|
+
wake_count = int(_cfg_num(cfg, "wake_count", 0, int))
|
|
1034
|
+
last_session_pct = cfg.get("last_session_pct") # 最近一次 check-context --used 记下的水位
|
|
1035
|
+
last_pct_at = _cfg_num(cfg, "last_session_pct_at", 0) # 那次记录的时间戳(v3.23)
|
|
1036
|
+
|
|
1037
|
+
used_given = used_pct is not None
|
|
1038
|
+
if used_given:
|
|
1039
|
+
pct = float(used_pct)
|
|
1040
|
+
source = "explicit"
|
|
1041
|
+
elif last_session_pct is not None:
|
|
1042
|
+
pct = float(_cfg_num(cfg, "last_session_pct", 0))
|
|
1043
|
+
source = "config" # 历史残留值,不是实时测量
|
|
1044
|
+
else:
|
|
1045
|
+
pct = 0.0
|
|
1046
|
+
source = "default"
|
|
1047
|
+
# v3.23:非实时输入一律标 stale —— 旧版把几天前的 last_session_pct 当"当前水位"返回,
|
|
1048
|
+
# 比没有更危险(看到 60% 会以为刚刚测过)。
|
|
1049
|
+
stale = not used_given
|
|
1050
|
+
age_hours = round((now - last_pct_at) / 3600, 1) if (stale and last_pct_at) else None
|
|
1051
|
+
if pct > 1.0:
|
|
1052
|
+
pct = pct / 100.0 # 兼容 0-100 口径:--used 65 与 0.65 等价
|
|
1053
|
+
review = _cfg_num(cfg, "review_threshold", 0.60)
|
|
1054
|
+
dream_th = _cfg_num(cfg, "dream_threshold", 0.75)
|
|
1055
|
+
escape = _cfg_num(cfg, "escape_threshold", 0.90)
|
|
1056
|
+
if pct >= escape:
|
|
1057
|
+
action = "capture:上下文快满,先原样封存(capture \"<内容>\" --kind episode)"
|
|
1058
|
+
level = "escape"
|
|
1059
|
+
elif pct >= dream_th:
|
|
1060
|
+
action = "dream --auto:该做梦压缩了(重放→合并→沉淀)"
|
|
1061
|
+
level = "dream"
|
|
1062
|
+
elif pct >= review:
|
|
1063
|
+
action = "check-context:进入清点区,先补记本轮漏掉的"
|
|
1064
|
+
level = "review"
|
|
1065
|
+
else:
|
|
1066
|
+
action = ""
|
|
1067
|
+
level = "ok"
|
|
1068
|
+
# v3.23:非实时输入(stale)不给"建议",也不返回非零退出码——
|
|
1069
|
+
# 拿几天前的数字催 AI 去做梦/封存是误导。
|
|
1070
|
+
exit_code = 0 if level == "ok" else (1 if level == "review" else (2 if level == "dream" else 3))
|
|
1071
|
+
if stale:
|
|
1072
|
+
level, action, exit_code = "stale", "", 0
|
|
1073
|
+
return {
|
|
1074
|
+
"pct": round(pct, 2),
|
|
1075
|
+
"level": level,
|
|
1076
|
+
"exit_code": exit_code,
|
|
1077
|
+
"action": action,
|
|
1078
|
+
"thresholds": {"review": review, "dream": dream_th, "escape": escape},
|
|
1079
|
+
"counts": counts,
|
|
1080
|
+
"hours_since_dream": round(hours_since_dream, 1) if hours_since_dream is not None else None,
|
|
1081
|
+
"hours_since_handoff": round(hours_since_handoff, 1) if hours_since_handoff is not None else None,
|
|
1082
|
+
"wake_count": wake_count,
|
|
1083
|
+
"last_session_pct": last_session_pct,
|
|
1084
|
+
"source": source,
|
|
1085
|
+
"stale": stale,
|
|
1086
|
+
"last_session_pct_age_hours": age_hours,
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
|
|
1090
|
+
def _remember_side_effects(rec: dict, how: str) -> None:
|
|
1091
|
+
"""remember 的边缘写入(note 门槛 + knowledge 审核闸)——fail-open,
|
|
1092
|
+
任何失败只记日志、绝不阻塞主写入(记忆本体已经在库里了)。
|
|
1093
|
+
|
|
1094
|
+
1. note 门槛:importance >= 0.7(10 分制 ≥7)或 kind ∈ {insight, mistake, fact}
|
|
1095
|
+
才追加一条 notes.jsonl(kind=growth,带 memory_id 反向引用);
|
|
1096
|
+
普通闲聊级记忆不进成长笔记,避免 notes 被流水账灌满。
|
|
1097
|
+
2. knowledge 审核闸:kind ∈ {insight, mistake} 自动写 knowledge.jsonl
|
|
1098
|
+
一律 status="pending" + source_ids=[memory_id]——AI 自己悟出的"道理"
|
|
1099
|
+
可能是幻觉,等做梦合并或人工确认后才生效(去重逻辑在 growth.add_knowledge)。
|
|
1100
|
+
"""
|
|
1101
|
+
try:
|
|
1102
|
+
kind = str(rec.get("kind", ""))
|
|
1103
|
+
imp = _num(rec.get("importance"), 0.0)
|
|
1104
|
+
mid = str(rec.get("id", ""))
|
|
1105
|
+
text = str(rec.get("text", ""))
|
|
1106
|
+
if how in ("created", "superseded", "conflict") and (imp >= 0.7 or kind in ("insight", "mistake", "fact")):
|
|
1107
|
+
import growth
|
|
1108
|
+
growth.write_note("growth", "记忆随记 · " + str(rec.get("gist") or text[:18]),
|
|
1109
|
+
text, tags=rec.get("tags") or [], memory_ids=[mid])
|
|
1110
|
+
except Exception as e:
|
|
1111
|
+
log_event("note-gate", f"随记笔记追加失败(不影响记忆):{e}", level="warn", file="notes.jsonl")
|
|
1112
|
+
try:
|
|
1113
|
+
kind = str(rec.get("kind", ""))
|
|
1114
|
+
if kind in ("insight", "mistake"):
|
|
1115
|
+
import growth
|
|
1116
|
+
growth.add_knowledge(str(rec.get("gist") or rec.get("text", ""))[:24],
|
|
1117
|
+
str(rec.get("text", "")),
|
|
1118
|
+
topic=str((rec.get("tags") or ["未分类"])[0]) if rec.get("tags") else "",
|
|
1119
|
+
tags=rec.get("tags") or [], entities=rec.get("entities") or [],
|
|
1120
|
+
source_ids=[rec["id"]], source="ai", review="pending")
|
|
1121
|
+
except Exception as e:
|
|
1122
|
+
log_event("knowledge-gate", f"知识自动写入失败(不影响记忆):{e}", level="warn", file="knowledge.jsonl")
|
|
1123
|
+
|
|
1124
|
+
|
|
1125
|
+
def _wait_embeds(timeout: float = 3.0) -> None:
|
|
1126
|
+
"""等在飞的 embedding 线程收尾(CLI 进程退出前调用)。
|
|
1127
|
+
|
|
1128
|
+
daemon 线程若在持 hippocampus 写锁时被进程退出硬杀,锁文件会残留,
|
|
1129
|
+
下一个进程要等 STALE_LOCK_SECONDS 才能接管。写完记忆后稍等一下,
|
|
1130
|
+
让异步嵌入把回写做完再退出,代价最多几秒。
|
|
1131
|
+
"""
|
|
1132
|
+
try:
|
|
1133
|
+
deadline = time.time() + timeout
|
|
1134
|
+
while _EMBED_INFLIGHT and time.time() < deadline:
|
|
1135
|
+
time.sleep(0.05)
|
|
1136
|
+
except Exception:
|
|
1137
|
+
pass
|
|
1138
|
+
|
|
1139
|
+
|
|
1140
|
+
def remember(text: str, kind: str = "fact", importance: float | None = None,
|
|
1141
|
+
tags=None, entities=None, source: str = "ai", layer: str = "hippo",
|
|
1142
|
+
emotion: str | None = None,
|
|
1143
|
+
channel: str | None = None, group_id: str | None = None,
|
|
1144
|
+
user: str | None = None,
|
|
1145
|
+
project: str | None = None, session: str | None = None,
|
|
1146
|
+
ttl_days: float | None = None, review_at: int | None = None,
|
|
1147
|
+
correction: bool = False,
|
|
1148
|
+
fras: dict | None = None,
|
|
1149
|
+
source_file: str | None = None,
|
|
1150
|
+
avoid: bool = False) -> tuple:
|
|
1151
|
+
ensure_home()
|
|
1152
|
+
text = (text or "").strip()
|
|
1153
|
+
if not text:
|
|
1154
|
+
raise ValueError("记忆内容为空")
|
|
1155
|
+
text = redact(text) # v3.02 #1:记忆写入统一脱敏,密钥不进 hippocampus/cortex
|
|
1156
|
+
# 单条记忆原文上限(config.remember_max_chars,默认 1200):超长截断保主干,
|
|
1157
|
+
# 只影响写入上限,不改变近重复合并等逻辑。
|
|
1158
|
+
_rmax = _cfg_num(load_config(), "remember_max_chars", 1200, int)
|
|
1159
|
+
if _rmax > 0 and len(text) > _rmax:
|
|
1160
|
+
text = text[:_rmax].rstrip() + "…"
|
|
1161
|
+
if emotion and emotion not in EMOTIONS:
|
|
1162
|
+
raise ValueError(f"没有这种情绪:{emotion}"
|
|
1163
|
+
f"(可用:开心/生气/难过/焦虑/感动…共 {len(EMOTIONS)} 种,"
|
|
1164
|
+
"`brain.py emotion list` 查看全部)")
|
|
1165
|
+
records = None # 锁内读取:见下方 _locked 作用域
|
|
1166
|
+
new_terms = terms(text)
|
|
1167
|
+
|
|
1168
|
+
# 情绪增强编码(杏仁核标记):情绪激动时经历的事记得更牢。
|
|
1169
|
+
# 显式给了 emotion 就用它;没给时,若此刻正好情绪激动(唤醒≥0.65),
|
|
1170
|
+
# 自动把当时最重的情绪标在这条记忆上——"发生在情绪上头那一刻的事"。
|
|
1171
|
+
emo_name, emo_arousal, boost = "", 0.0, 0.0
|
|
1172
|
+
_correction_flag = bool(correction)
|
|
1173
|
+
# #42 多维重要性:没显式给 importance 时,用多维启发式打分(含实体/情绪/correction 维度)
|
|
1174
|
+
if importance is None:
|
|
1175
|
+
imp = heuristic_importance(text, kind, entities=entities,
|
|
1176
|
+
correction=_correction_flag, emotional=0.0)
|
|
1177
|
+
else:
|
|
1178
|
+
imp = _num(importance, heuristic_importance(text, kind, entities=entities,
|
|
1179
|
+
correction=_correction_flag))
|
|
1180
|
+
if emotion:
|
|
1181
|
+
if emotion in EMOTIONS:
|
|
1182
|
+
emo_name, emo_arousal = emotion, _emotion_coord(emotion)[1]
|
|
1183
|
+
else:
|
|
1184
|
+
m = mood_now()
|
|
1185
|
+
if m.get("storm") and m["active"]:
|
|
1186
|
+
emo_name = m["active"][0]["emotion"]
|
|
1187
|
+
emo_arousal = float(m["active"][0].get("arousal", 0))
|
|
1188
|
+
if emo_name and emo_arousal >= 0.45:
|
|
1189
|
+
boost = 0.08 * emo_arousal
|
|
1190
|
+
# #42 情绪维度:唤醒度也参与写入时打分(不只是 stability 加成)
|
|
1191
|
+
if importance is None:
|
|
1192
|
+
imp = min(1.0, imp + 0.12 * emo_arousal)
|
|
1193
|
+
imp = min(1.0, (imp if imp <= 1 else imp / 10) + boost)
|
|
1194
|
+
stability_boost = 1.0 + 0.9 * emo_arousal
|
|
1195
|
+
else:
|
|
1196
|
+
emo_name, stability_boost = "", 1.0
|
|
1197
|
+
|
|
1198
|
+
# 读-改-写整体加锁:remember 走 save_all 整库快照覆写,若锁外先 load_all,
|
|
1199
|
+
# 并发写的另一个进程 os.replace 覆盖我们正读着的文件会在 Windows 上报 PermissionError。
|
|
1200
|
+
# 放进锁里后,读和写在锁内互斥,顺带杜绝"旧快照覆盖新写入"。
|
|
1201
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
1202
|
+
records = load_all()
|
|
1203
|
+
# 近重复合并:同一类记忆、文本高度相似 -> 强化旧记忆而不是堆新条
|
|
1204
|
+
# 先做廉价子串预筛(jaccard≥0.86 必共享 term,共享 term 必是旧文本子串,数学上不丢召回),
|
|
1205
|
+
# 上万条记忆时避免对每条都跑正则分词;archive 记录不参与合并(防归档记忆被悄悄复活)
|
|
1206
|
+
for m in records:
|
|
1207
|
+
if tuple(str(m.get(k) or "") for k in ("channel", "group_id", "user")) != (str(channel or ""), str(group_id or ""), str(user or "")):
|
|
1208
|
+
continue # Do not merge memories from different owners/scopes.
|
|
1209
|
+
if m.get("layer") in ("dust", ARCHIVE_LAYER) or m.get("kind") != kind:
|
|
1210
|
+
continue
|
|
1211
|
+
if new_terms and not any(t in _hay(m) for t in new_terms):
|
|
1212
|
+
continue
|
|
1213
|
+
old_text = m.get("text", "") or ""
|
|
1214
|
+
if jaccard(new_terms, terms(old_text)) >= 0.86:
|
|
1215
|
+
# 保留更长/更完整的文本,别让一句简短的重复把原细节盖掉
|
|
1216
|
+
old, new = m.get("text", ""), text
|
|
1217
|
+
if len(new) > len(old):
|
|
1218
|
+
m["text"] = new
|
|
1219
|
+
m["gist"] = heuristic_gist(new)
|
|
1220
|
+
else:
|
|
1221
|
+
m["gist"] = heuristic_gist(old)
|
|
1222
|
+
# importance 消歧:int 一律按 0-10 制;float 且 <=1 按 0-1 制。
|
|
1223
|
+
# 原来 imp <= 1 的隐式判定无法区分"用户想给最低档 1/10 却输入 1"的场景。
|
|
1224
|
+
if imp is not None:
|
|
1225
|
+
if isinstance(imp, int):
|
|
1226
|
+
imp_val = float(imp) / 10.0
|
|
1227
|
+
elif isinstance(imp, float):
|
|
1228
|
+
imp_val = imp if imp <= 1 else imp / 10.0
|
|
1229
|
+
else:
|
|
1230
|
+
imp_val = float(imp) / 10.0 if float(imp) > 1 else float(imp)
|
|
1231
|
+
m["importance"] = round(max(0.0, min(1.0, max(_num(m.get("importance"), 0.5), imp_val))), 3)
|
|
1232
|
+
else:
|
|
1233
|
+
m["importance"] = round(max(0.0, min(1.0, _num(m.get("importance"), 0.5))), 3)
|
|
1234
|
+
m["last_access"] = now_ts()
|
|
1235
|
+
m["access_count"] = int(_num(m.get("access_count"), 0)) + 1
|
|
1236
|
+
m["stability"] = min(MAX_STABILITY, _num(m.get("stability"), DEFAULT_STABILITY) * 1.4 * stability_boost)
|
|
1237
|
+
# 习惯化(享乐适应):同一件事反复出现,新鲜感递减、重要性不再步步抬升。
|
|
1238
|
+
# 就像警报器一直响就没人再在意——但保留一个下限,别把真重要的磨掉。
|
|
1239
|
+
m["repeat"] = int(_num(m.get("repeat"), 0)) + 1
|
|
1240
|
+
# repeat 降权只对 AI/做梦等来源生效——用户亲口反复强调的事
|
|
1241
|
+
# (source=user)应该加权而不是降权,与其"亲述立即取代"语义一致
|
|
1242
|
+
if m["source"] != "user" and m["repeat"] >= 3 and m["importance"] > 0.25:
|
|
1243
|
+
m["importance"] = round(m["importance"] - 0.02, 3)
|
|
1244
|
+
if emo_name and not m.get("emotion"):
|
|
1245
|
+
m["emotion"] = emo_name
|
|
1246
|
+
m["tags"] = _dedupe(m.get("tags", []) + [t.strip().lstrip("#") for t in (tags or [])])
|
|
1247
|
+
m["entities"] = _dedupe(m.get("entities", []) + (entities or []))
|
|
1248
|
+
# 第四轮#3:合并路径补项目标记——旧条目还挂着 "default" 时趁机挂上真实项目
|
|
1249
|
+
if project and str(project).strip() and str(m.get("project") or "default") == "default":
|
|
1250
|
+
m["project"] = str(project).strip()[:64]
|
|
1251
|
+
save_all(records)
|
|
1252
|
+
# P1:异步补/更新 embedding(文本变了或还没有向量才调度;
|
|
1253
|
+
# 未配置 embed 服务时 _embed_wanted 直接 False,零开销跳过)
|
|
1254
|
+
try:
|
|
1255
|
+
if _embed_wanted(m, text_changed=(len(text) > len(old))):
|
|
1256
|
+
_schedule_embed(m["id"], str(m.get("text") or ""))
|
|
1257
|
+
except Exception as exc:
|
|
1258
|
+
log_event("embed", f"schedule_embed 失败(不影响记事):{exc}", level="warn")
|
|
1259
|
+
_remember_desire_nudge(m, imp)
|
|
1260
|
+
_remember_side_effects(m, "merged")
|
|
1261
|
+
return m, "merged"
|
|
1262
|
+
|
|
1263
|
+
rec = make_record(text, kind, importance, tags, entities, source, layer,
|
|
1264
|
+
channel=channel, group_id=group_id, user=user,
|
|
1265
|
+
project=project, session=session)
|
|
1266
|
+
# —— #41 correction 语义:用户说「不对/不是」语境下显式标记的改口记录 ——
|
|
1267
|
+
# correction 条目是失败闭环的第一手证据:做梦教训提炼(#36)优先读它,
|
|
1268
|
+
# 且合并/淡忘/归档路径都会跳过(永不自动合并消失),只有人工才能处理。
|
|
1269
|
+
if correction:
|
|
1270
|
+
rec["correction"] = True
|
|
1271
|
+
# #42 correction 维度:改口记录起步重要性至少 0.75
|
|
1272
|
+
rec["importance"] = max(rec.get("importance", 0.5), 0.75)
|
|
1273
|
+
rec["importance"] = round(float(rec.get("importance", 0.5)) + (boost if emo_name else 0), 3)
|
|
1274
|
+
rec["importance"] = max(0.0, min(1.0, rec["importance"]))
|
|
1275
|
+
# 高重要性待审闸:重要性 ≥0.8(10 分制 ≥8)的记忆多半是约定/承诺/重要决定,
|
|
1276
|
+
# 一旦记错就是长期错误,与做梦产出一样先进待审池,用户确认后转正。
|
|
1277
|
+
if rec["importance"] >= 0.8 and source != "user":
|
|
1278
|
+
rec["review"] = "pending"
|
|
1279
|
+
rec["review_source"] = f"high-importance:{source}"
|
|
1280
|
+
rec["stability"] = min(MAX_STABILITY, rec.get("stability", DEFAULT_STABILITY) * stability_boost)
|
|
1281
|
+
if emo_name:
|
|
1282
|
+
rec["emotion"] = emo_name
|
|
1283
|
+
rec["emotional"] = round(emo_arousal, 2)
|
|
1284
|
+
# v3.02 #10:事实类记忆的保质期——ttl_days 到期后注入标「待复核」,
|
|
1285
|
+
# review_at 是显式指定的复核时间点(--review-at YYYY-MM-DD 或时间戳)。
|
|
1286
|
+
# 只影响注入提示,不删不改:到期是"该找用户确认一下了",不是"失效"。
|
|
1287
|
+
if ttl_days is not None and _num(ttl_days, 0) > 0:
|
|
1288
|
+
rec["ttl_days"] = _num(ttl_days, 0)
|
|
1289
|
+
rec["expires_at"] = int(now_ts() + _num(ttl_days, 0) * DAY)
|
|
1290
|
+
if review_at is not None and _num(review_at, 0) > 0:
|
|
1291
|
+
rec["review_by"] = int(_num(review_at, 0))
|
|
1292
|
+
elif ttl_days is not None and _num(ttl_days, 0) > 0:
|
|
1293
|
+
rec["review_by"] = rec.get("expires_at")
|
|
1294
|
+
# —— v3.58 三层元数据(借自 AOCI-CODE 的 Entry 规范,见 docs/进展与待办.md P4)——
|
|
1295
|
+
# ① FRAS 四段:给"项目类知识"补上"改它之前还得知道什么"这层。
|
|
1296
|
+
# 灵枢原来只有 text/gist/tags,记得事情但不记得坑;S(不明显约束)信息密度
|
|
1297
|
+
# 最高,注入时优先展示。缺省不带 → 旧调用与旧数据行为完全不变。
|
|
1298
|
+
_fras = {}
|
|
1299
|
+
if isinstance(fras, dict):
|
|
1300
|
+
for _k in ("f", "r", "a", "s"):
|
|
1301
|
+
_v = str(fras.get(_k) or "").strip()
|
|
1302
|
+
if _v:
|
|
1303
|
+
_fras[_k] = _v
|
|
1304
|
+
if _fras:
|
|
1305
|
+
rec["fras"] = _fras
|
|
1306
|
+
# ② 源指纹:把这条记忆绑定到某个文件,存当次 sha256。
|
|
1307
|
+
# 文件后来变了 → recall/注入时标「源已变,可能过期」并降权。
|
|
1308
|
+
# 这是"这条记忆还成不成立"的信号,与 h/p_h 哈希链(防篡改)不是一回事。
|
|
1309
|
+
if source_file:
|
|
1310
|
+
_sf = os.path.expanduser(str(source_file).strip())
|
|
1311
|
+
if not _sf:
|
|
1312
|
+
pass
|
|
1313
|
+
else:
|
|
1314
|
+
try:
|
|
1315
|
+
_p = Path(_sf).resolve()
|
|
1316
|
+
rec["source_file"] = str(_p)
|
|
1317
|
+
rec["source_sha256"] = (hashlib.sha256(_p.read_bytes()).hexdigest()
|
|
1318
|
+
if _p.is_file() else "")
|
|
1319
|
+
except Exception as exc: # 文件不可读不该拦住记事
|
|
1320
|
+
rec["source_file"] = _sf
|
|
1321
|
+
log_event("memory", f"源指纹读取失败({_sf}):{exc}", level="warn")
|
|
1322
|
+
# ③ 负空间:显式记住「决定不做的东西」。
|
|
1323
|
+
# 与普通记忆的区别是语义——注入时单独成块「已经排除的方向(别再提)」,
|
|
1324
|
+
# 避免 AI 反复建议用户已经否掉的路(如"别再建议 DiskGenius 恢复")。
|
|
1325
|
+
if avoid:
|
|
1326
|
+
rec["avoid"] = True
|
|
1327
|
+
# —— 记忆冲突裁决(Mem0 风格)——
|
|
1328
|
+
# 与某条旧记忆中度相似(jaccard 0.55~0.86)但文本不同 = 同一件事说法变了/事实更新。
|
|
1329
|
+
# 旧的不删:打上 superseded_by 指向新记忆(回忆默认跳过被取代者,仍可沿链回溯旧观念)。
|
|
1330
|
+
# AI 来源的新说法先标"待审核":防止 AI 改写结论未经用户确认就生效。
|
|
1331
|
+
# 必须在锁内做:remember 走整库快照覆写,锁内读锁内写才不会互相覆盖。
|
|
1332
|
+
rec_id_pending = rec["id"] # rec 尚未 append,先留 id 给旧记忆反标冲突
|
|
1333
|
+
superseded = []
|
|
1334
|
+
conflicts = [] # AI 来源的矛盾对:双标记待裁决,不立即取代
|
|
1335
|
+
for old in records:
|
|
1336
|
+
if (old is rec or old.get("kind") != kind
|
|
1337
|
+
or old.get("layer") in ("dust", ARCHIVE_LAYER)
|
|
1338
|
+
or old.get("superseded_by")):
|
|
1339
|
+
continue
|
|
1340
|
+
# 来源归属:跨项目/跨会话的相似记忆不算冲突——
|
|
1341
|
+
# A 项目「用 MySQL」、B 项目「用 PostgreSQL」是并存事实,不是改口。
|
|
1342
|
+
# 同源(同 project)才做取代/裁决比较;老数据没有 project 字段视为同源(default)。
|
|
1343
|
+
if str(rec.get("project", "default")) != str(old.get("project", "default")):
|
|
1344
|
+
continue
|
|
1345
|
+
if tuple(str(old.get(k) or "") for k in ("channel", "group_id", "user")) != tuple(str(rec.get(k) or "") for k in ("channel", "group_id", "user")):
|
|
1346
|
+
continue # Conflicts must stay inside their original scope.
|
|
1347
|
+
old_text = str(old.get("text", "")).strip()
|
|
1348
|
+
old_terms = terms(old_text)
|
|
1349
|
+
if not old_terms or old_text == text:
|
|
1350
|
+
continue
|
|
1351
|
+
sim = jaccard(new_terms, old_terms)
|
|
1352
|
+
if 0.55 <= sim < 0.86:
|
|
1353
|
+
# AI 来源:冲突不静默裁决(借鉴 dsh-mneme 矛盾冻结队列)——
|
|
1354
|
+
# 旧说法先不藏(不打 superseded_by,回忆里还能被看到),双方互标
|
|
1355
|
+
# conflict_with 进待审;review confirm 转正时才真正取代。
|
|
1356
|
+
# 用户亲口说的(source=user)维持立即取代:用户自己更新事实,不用等审。
|
|
1357
|
+
if source != "user":
|
|
1358
|
+
old.setdefault("conflicts", [])
|
|
1359
|
+
if rec_id_pending not in old["conflicts"]:
|
|
1360
|
+
old["conflicts"].append(rec_id_pending)
|
|
1361
|
+
rec.setdefault("conflicts", [])
|
|
1362
|
+
old["conflict_flag"] = True
|
|
1363
|
+
conflicts.append(old["id"])
|
|
1364
|
+
continue
|
|
1365
|
+
old["superseded_by"] = rec["id"]
|
|
1366
|
+
old["updated"] = now_ts()
|
|
1367
|
+
rec.setdefault("links", [])
|
|
1368
|
+
if old["id"] not in rec["links"]:
|
|
1369
|
+
rec["links"].append(old["id"])
|
|
1370
|
+
superseded.append(old["id"])
|
|
1371
|
+
if superseded or conflicts:
|
|
1372
|
+
if source != "user":
|
|
1373
|
+
rec["review"] = "pending"
|
|
1374
|
+
rec["review_source"] = "conflict"
|
|
1375
|
+
if conflicts:
|
|
1376
|
+
rec["conflicts"] = conflicts # 对方 id 列表:转正/裁决后由 review 流程落实取代
|
|
1377
|
+
rec["conflict_flag"] = True
|
|
1378
|
+
rec["superseded"] = superseded + conflicts # 展示"这次牵动/质疑了哪些旧说法"
|
|
1379
|
+
else:
|
|
1380
|
+
rec["superseded"] = superseded # 给调用方展示"这次取代了哪些旧说法"
|
|
1381
|
+
# —— 索引硬上限守卫(engramory 式单调守卫)——
|
|
1382
|
+
# hippocampus.jsonl 是热索引,无限膨胀会拖垮每次 load_all/注入。
|
|
1383
|
+
# 规则:超过硬上限(index_max_records 条 或 index_max_mb MB)且本次写入
|
|
1384
|
+
# 还会让索引变大 → 拒绝写入(引导先做梦压缩/整理);dream --apply 等缩小
|
|
1385
|
+
# 或持平的写入路径不经过这里(直接走 save_all),读取永远不受影响。
|
|
1386
|
+
# 合并/取代类写入本身不净增条数,视为"持平"放行。
|
|
1387
|
+
try:
|
|
1388
|
+
_cap_cfg = load_config()
|
|
1389
|
+
_max_n = int(_cfg_num(_cap_cfg, "index_max_records", 5000, int))
|
|
1390
|
+
_max_bytes = int(_cfg_num(_cap_cfg, "index_max_mb", 5.0, float) * 1024 * 1024)
|
|
1391
|
+
if _max_n > 0 or _max_bytes > 0:
|
|
1392
|
+
_idx = HOME / "hippocampus.jsonl"
|
|
1393
|
+
_cur_bytes = _idx.stat().st_size if _idx.exists() else 0
|
|
1394
|
+
_over = ((_max_n > 0 and len(records) + 1 > _max_n)
|
|
1395
|
+
or (_max_bytes > 0 and _cur_bytes > _max_bytes))
|
|
1396
|
+
if _over and not (superseded or conflicts):
|
|
1397
|
+
raise ValueError(
|
|
1398
|
+
f"记忆索引已达硬上限({len(records)} 条 / {_cur_bytes // 1024} KB,"
|
|
1399
|
+
f"上限 {_max_n} 条 / {_max_bytes // 1024 // 1024} MB)。"
|
|
1400
|
+
"先做梦压缩再写:`python scripts/brain.py dream --auto`。")
|
|
1401
|
+
except ValueError:
|
|
1402
|
+
raise
|
|
1403
|
+
except Exception:
|
|
1404
|
+
pass # 守卫自身出错绝不能拦住记事
|
|
1405
|
+
records.append(rec)
|
|
1406
|
+
# 联想建链:与历史里词面最相近的几条互挂 links(锁内、传已 load 的快照)
|
|
1407
|
+
try:
|
|
1408
|
+
relink(rec, records)
|
|
1409
|
+
except Exception:
|
|
1410
|
+
pass # 建链是锦上添花,绝不能让记事本身失败
|
|
1411
|
+
save_all(records)
|
|
1412
|
+
# P1:新记忆异步生成 embedding(未配置 embed 服务时零开销跳过)
|
|
1413
|
+
try:
|
|
1414
|
+
if _embed_wanted(rec, True):
|
|
1415
|
+
_schedule_embed(rec["id"], str(rec.get("text") or ""))
|
|
1416
|
+
except Exception:
|
|
1417
|
+
pass # embedding 是增强,绝不影响记事
|
|
1418
|
+
_remember_desire_nudge(rec, rec.get("importance"))
|
|
1419
|
+
_remember_side_effects(rec, "superseded" if superseded else ("conflict" if conflicts else "created"))
|
|
1420
|
+
return rec, ("superseded" if superseded else ("conflict" if conflicts else "created"))
|
|
1421
|
+
|
|
1422
|
+
|
|
1423
|
+
# ---------------------------------------------------------------- P1 可选 embedding
|
|
1424
|
+
# 设计约束(零依赖铁律):
|
|
1425
|
+
# * 未配置 embed 服务时,_embed_wanted 一律 False——不调 API、不起线程、零开销;
|
|
1426
|
+
# * 网络调用全在 daemon 线程里做,remember 主链路永远不阻塞;
|
|
1427
|
+
# * 回写重新进 _locked + load_all + save_all,与并发写互斥,不覆盖别人的新写入;
|
|
1428
|
+
# * 文本在嵌入期间又被改写(合并路径)就不回写旧向量,等下一轮调度自然修正。
|
|
1429
|
+
|
|
1430
|
+
_EMBED_INFLIGHT: set = set()
|
|
1431
|
+
_EMBED_INFLIGHT_LOCK = threading.Lock()
|
|
1432
|
+
|
|
1433
|
+
|
|
1434
|
+
def _embed_wanted(m: dict, text_changed: bool = False) -> bool:
|
|
1435
|
+
"""这条记忆是否需要(重新)生成 embedding:embed 服务或降级向量可用,且文本变了或还没向量。
|
|
1436
|
+
|
|
1437
|
+
降级向量兜底(config embed.fallback.enabled,默认开):没有 Ollama 时
|
|
1438
|
+
embed_texts 会返回纯 stdlib hash 向量(256 维),照常写 m["embedding"];
|
|
1439
|
+
维度不同(768 vs 256)由 _dense_recall 的 len 校验天然隔离,不混算。
|
|
1440
|
+
"""
|
|
1441
|
+
try:
|
|
1442
|
+
if READONLY:
|
|
1443
|
+
return False
|
|
1444
|
+
if not _embed_cfg():
|
|
1445
|
+
import fallback_embed
|
|
1446
|
+
if not fallback_embed.cfg():
|
|
1447
|
+
return False
|
|
1448
|
+
except Exception:
|
|
1449
|
+
return False
|
|
1450
|
+
return bool(text_changed) or not m.get("embedding")
|
|
1451
|
+
|
|
1452
|
+
|
|
1453
|
+
def _schedule_embed(rec_id: str, text: str) -> None:
|
|
1454
|
+
"""起 daemon 线程异步嵌入 + 回写;同一条记忆同时在飞只跑一个。"""
|
|
1455
|
+
if not rec_id or not text:
|
|
1456
|
+
return
|
|
1457
|
+
with _EMBED_INFLIGHT_LOCK:
|
|
1458
|
+
if rec_id in _EMBED_INFLIGHT:
|
|
1459
|
+
return
|
|
1460
|
+
_EMBED_INFLIGHT.add(rec_id)
|
|
1461
|
+
try:
|
|
1462
|
+
threading.Thread(target=_embed_worker, args=(rec_id, text), daemon=True).start()
|
|
1463
|
+
except Exception:
|
|
1464
|
+
with _EMBED_INFLIGHT_LOCK:
|
|
1465
|
+
_EMBED_INFLIGHT.discard(rec_id)
|
|
1466
|
+
|
|
1467
|
+
|
|
1468
|
+
def _embed_worker(rec_id: str, text: str) -> None:
|
|
1469
|
+
try:
|
|
1470
|
+
vecs = embed_texts([text])
|
|
1471
|
+
if not vecs:
|
|
1472
|
+
return
|
|
1473
|
+
# 4 位小数截断:cosine 精度损失可忽略,JSONL 体积省 ~3 倍
|
|
1474
|
+
vec = [round(x, 4) for x in vecs[0]]
|
|
1475
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
1476
|
+
records = load_all()
|
|
1477
|
+
for m in records:
|
|
1478
|
+
if m.get("id") != rec_id:
|
|
1479
|
+
continue
|
|
1480
|
+
if str(m.get("text") or "") == text:
|
|
1481
|
+
m["embedding"] = vec
|
|
1482
|
+
save_all(records)
|
|
1483
|
+
return
|
|
1484
|
+
except Exception as exc:
|
|
1485
|
+
log_event("embed", f"embedding 回写失败:{exc}", level="warn")
|
|
1486
|
+
finally:
|
|
1487
|
+
with _EMBED_INFLIGHT_LOCK:
|
|
1488
|
+
_EMBED_INFLIGHT.discard(rec_id)
|
|
1489
|
+
|
|
1490
|
+
|
|
1491
|
+
def embed_backfill(limit: int = 0) -> int:
|
|
1492
|
+
"""给已有但没向量的记忆补 embedding(同步、限量),返回成功补写的条数。
|
|
1493
|
+
|
|
1494
|
+
覆盖历史数据与 cortex 层(cortex 由做梦 consolidate 写入,不经过 remember 调度)。
|
|
1495
|
+
未配置 embed 服务返回 0;默认一次补 cfg.embed.batch_size 条。
|
|
1496
|
+
"""
|
|
1497
|
+
cfg = _embed_cfg()
|
|
1498
|
+
if READONLY:
|
|
1499
|
+
return 0
|
|
1500
|
+
if not cfg:
|
|
1501
|
+
# 无真嵌入服务时看降级向量兜底是否开启(embed_texts 内部会自动接管)
|
|
1502
|
+
try:
|
|
1503
|
+
import fallback_embed
|
|
1504
|
+
if not fallback_embed.cfg():
|
|
1505
|
+
return 0
|
|
1506
|
+
except Exception:
|
|
1507
|
+
return 0
|
|
1508
|
+
if not cfg:
|
|
1509
|
+
cfg = {"batch_size": 8}
|
|
1510
|
+
todo = [m for m in load_all()
|
|
1511
|
+
if m.get("layer") != "dust" and not m.get("embedding")
|
|
1512
|
+
and str(m.get("text") or "").strip()]
|
|
1513
|
+
if not todo:
|
|
1514
|
+
return 0
|
|
1515
|
+
todo = todo[: max(1, int(limit or cfg.get("batch_size") or 8))]
|
|
1516
|
+
vecs = embed_texts([str(m.get("text") or "") for m in todo])
|
|
1517
|
+
if not vecs or len(vecs) != len(todo):
|
|
1518
|
+
return 0
|
|
1519
|
+
n = 0
|
|
1520
|
+
try:
|
|
1521
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
1522
|
+
records = load_all()
|
|
1523
|
+
by_id = {m.get("id"): [round(x, 4) for x in v] for m, v in zip(todo, vecs)}
|
|
1524
|
+
for m in records:
|
|
1525
|
+
v = by_id.get(m.get("id"))
|
|
1526
|
+
if v is not None:
|
|
1527
|
+
m["embedding"] = v
|
|
1528
|
+
n += 1
|
|
1529
|
+
if n:
|
|
1530
|
+
save_all(records)
|
|
1531
|
+
except Exception as exc:
|
|
1532
|
+
log_event("embed", f"embed_backfill 失败:{exc}", level="warn")
|
|
1533
|
+
return 0
|
|
1534
|
+
return n
|
|
1535
|
+
|
|
1536
|
+
|
|
1537
|
+
def rebuild_embeddings(force: bool = False) -> dict:
|
|
1538
|
+
"""一键重建全库 embedding 向量(同步、全量/增量两档)。
|
|
1539
|
+
|
|
1540
|
+
场景:换嵌入模型、缓存损坏、历史记忆缺向量(含 archive 层)。
|
|
1541
|
+
- force=False:只补缺失向量、或向量模型与当前配置不符的(记录里带
|
|
1542
|
+
embedding_model 字段时按模型名判断;老数据无该字段但有向量 → 视为
|
|
1543
|
+
旧模型产物,一并重算,保证维度/语义一致);
|
|
1544
|
+
- force=True:全部有正文的记忆一律重算。
|
|
1545
|
+
逐条失败只记录 id 继续跑,最后返回统计。只读模式抛 PermissionError;
|
|
1546
|
+
嵌入服务不可用抛 RuntimeError(CLI 映射退出码 2,系统级错误)。
|
|
1547
|
+
进度每 20 条 log_event 一次,写回走现有锁 + 原子替换。
|
|
1548
|
+
"""
|
|
1549
|
+
if READONLY:
|
|
1550
|
+
raise PermissionError("记忆库当前只读,无法重建 embedding。")
|
|
1551
|
+
cfg = _embed_cfg()
|
|
1552
|
+
fb_dims = None
|
|
1553
|
+
try:
|
|
1554
|
+
import fallback_embed
|
|
1555
|
+
_fb = fallback_embed.cfg()
|
|
1556
|
+
fb_dims = _fb["dims"] if _fb else None
|
|
1557
|
+
except Exception:
|
|
1558
|
+
pass
|
|
1559
|
+
if cfg:
|
|
1560
|
+
# 探针:embed_texts 在真服务不可达时会静默降级到 hash 兜底(256 维)。
|
|
1561
|
+
# 重建场景必须拿真模型向量——维度对上兜底 dims 就说明服务没通,明确报错。
|
|
1562
|
+
probe = embed_texts(["灵枢重建探针"])
|
|
1563
|
+
if not probe or (fb_dims is not None and len(probe[0]) == fb_dims):
|
|
1564
|
+
raise RuntimeError(
|
|
1565
|
+
f"嵌入服务不可用({cfg['url']},模型 {cfg['model']})。"
|
|
1566
|
+
"请确认 Ollama 已启动(ollama serve)且模型已拉取"
|
|
1567
|
+
f"(ollama pull {cfg['model']}),或检查 config.json 的 embed.url。")
|
|
1568
|
+
model_name = cfg["model"]
|
|
1569
|
+
else:
|
|
1570
|
+
if fb_dims is None:
|
|
1571
|
+
raise RuntimeError(
|
|
1572
|
+
"embedding 服务未配置(config.json 的 embed.url 为空),且降级向量兜底未启用,"
|
|
1573
|
+
"无法重建。先配置 embed 服务,或在面板「本地能力」页启用 Ollama。")
|
|
1574
|
+
model_name = f"fallback-hash-{fb_dims}d"
|
|
1575
|
+
|
|
1576
|
+
records = load_all() + load_archive()
|
|
1577
|
+
todo, skipped = [], 0
|
|
1578
|
+
for m in records:
|
|
1579
|
+
text = str(m.get("text") or "").strip()
|
|
1580
|
+
if not text:
|
|
1581
|
+
skipped += 1
|
|
1582
|
+
continue
|
|
1583
|
+
if not force and m.get("embedding") and m.get("embedding_model") == model_name:
|
|
1584
|
+
skipped += 1
|
|
1585
|
+
continue
|
|
1586
|
+
todo.append(m)
|
|
1587
|
+
|
|
1588
|
+
failed: list = []
|
|
1589
|
+
rebuilt = 0
|
|
1590
|
+
by_layer: dict = {}
|
|
1591
|
+
done = 0
|
|
1592
|
+
batch = max(1, int((cfg or {}).get("batch_size") or 8))
|
|
1593
|
+
for i in range(0, len(todo), batch):
|
|
1594
|
+
chunk = todo[i:i + batch]
|
|
1595
|
+
vecs = embed_texts([str(m.get("text") or "") for m in chunk])
|
|
1596
|
+
if not vecs or len(vecs) != len(chunk):
|
|
1597
|
+
# 批量失败逐条重试,坏条目不拖垮整批
|
|
1598
|
+
vecs = []
|
|
1599
|
+
for m in chunk:
|
|
1600
|
+
v = embed_texts([str(m.get("text") or "")])
|
|
1601
|
+
vecs.append(v[0] if v else None)
|
|
1602
|
+
for m, v in zip(chunk, vecs):
|
|
1603
|
+
if not v:
|
|
1604
|
+
failed.append(m.get("id") or "?")
|
|
1605
|
+
continue
|
|
1606
|
+
m["embedding"] = [round(x, 4) for x in v]
|
|
1607
|
+
m["embedding_model"] = model_name
|
|
1608
|
+
by_layer.setdefault(m.get("layer") or "hippo", []).append(m)
|
|
1609
|
+
rebuilt += 1
|
|
1610
|
+
done += len(chunk)
|
|
1611
|
+
if done % 20 < batch or done >= len(todo):
|
|
1612
|
+
log_event("embed", f"rebuild_embeddings 进度:{done}/{len(todo)},"
|
|
1613
|
+
f"已重建 {rebuilt},失败 {len(failed)}")
|
|
1614
|
+
|
|
1615
|
+
if rebuilt:
|
|
1616
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
1617
|
+
hot = load_all()
|
|
1618
|
+
updated = {m["id"]: m for m in by_layer.get("hippo", []) + by_layer.get("cortex", []) + by_layer.get("dust", [])
|
|
1619
|
+
if m.get("id")}
|
|
1620
|
+
n_hot = 0
|
|
1621
|
+
for m in hot:
|
|
1622
|
+
new = updated.pop(m.get("id"), None)
|
|
1623
|
+
if new is not None:
|
|
1624
|
+
m["embedding"] = new["embedding"]
|
|
1625
|
+
m["embedding_model"] = model_name
|
|
1626
|
+
n_hot += 1
|
|
1627
|
+
if n_hot:
|
|
1628
|
+
save_all(hot)
|
|
1629
|
+
# 归档层独立维护(与 _append_archive 同款锁)
|
|
1630
|
+
arch_new = by_layer.get(ARCHIVE_LAYER, [])
|
|
1631
|
+
if arch_new:
|
|
1632
|
+
with _locked(HOME / "archive.jsonl"):
|
|
1633
|
+
arch = load_archive()
|
|
1634
|
+
amap = {m.get("id"): m for m in arch_new if m.get("id")}
|
|
1635
|
+
for m in arch:
|
|
1636
|
+
new = amap.get(m.get("id"))
|
|
1637
|
+
if new is not None:
|
|
1638
|
+
m["embedding"] = new["embedding"]
|
|
1639
|
+
m["embedding_model"] = model_name
|
|
1640
|
+
write_jsonl(HOME / "archive.jsonl", arch)
|
|
1641
|
+
log_event("embed", f"rebuild_embeddings 完成:重建 {rebuilt},跳过 {skipped},"
|
|
1642
|
+
f"失败 {len(failed)},模型 {model_name}")
|
|
1643
|
+
return {"rebuilt": rebuilt, "skipped": skipped, "failed": failed, "model": model_name}
|
|
1644
|
+
|
|
1645
|
+
|
|
1646
|
+
def _dense_recall(query: str, records_by_id: dict, top_n: int = 10,
|
|
1647
|
+
floor: float = 0.30) -> dict:
|
|
1648
|
+
"""Dense 召回:query 向量与记忆 embedding 算 cosine,返回 {id: sim} 的 Top-N。
|
|
1649
|
+
|
|
1650
|
+
只对已有 embedding 字段的记忆生效;embed 服务未配置/不可达/无人过 floor 时
|
|
1651
|
+
返回 {}——调用方按"无 Dense 能力"退回纯关键词。纯标准库算内积:
|
|
1652
|
+
五千条 × 768 维约几十毫秒,不需要 numpy。floor 砍噪声(无关对通常 <0.3)。
|
|
1653
|
+
"""
|
|
1654
|
+
cands = [(mid, m["embedding"]) for mid, m in records_by_id.items()
|
|
1655
|
+
if isinstance(m.get("embedding"), list) and m["embedding"]]
|
|
1656
|
+
if not cands:
|
|
1657
|
+
return {}
|
|
1658
|
+
qv = embed_texts([query])
|
|
1659
|
+
if not qv:
|
|
1660
|
+
return {}
|
|
1661
|
+
q = qv[0]
|
|
1662
|
+
qlen = len(q)
|
|
1663
|
+
sims = {}
|
|
1664
|
+
for mid, vec in cands:
|
|
1665
|
+
if len(vec) != qlen: # 跨模型/跨版本维度不符:跳过,不混算
|
|
1666
|
+
continue
|
|
1667
|
+
# 纯标准库余弦(零向量→0.0);算式抽到 mem_score._cosine_sim,行为与原内联一致
|
|
1668
|
+
sim = _cosine_sim(q, vec)
|
|
1669
|
+
if sim >= floor:
|
|
1670
|
+
sims[mid] = sim
|
|
1671
|
+
if not sims:
|
|
1672
|
+
return {}
|
|
1673
|
+
top = sorted(sims.items(), key=lambda kv: kv[1], reverse=True)[: max(1, top_n)]
|
|
1674
|
+
return dict(top)
|
|
1675
|
+
|
|
1676
|
+
|
|
1677
|
+
def _remember_desire_nudge(rec: dict, imp) -> None:
|
|
1678
|
+
"""记事牵动六欲(自动微调):记东西本身就是表达,重要的事还带着求知/掌控。
|
|
1679
|
+
|
|
1680
|
+
重要度高 → 表达欲/成就欲;探查类(question/insight)→ 求知欲。
|
|
1681
|
+
幅度 2~4 点(v3.68 翻倍)+ 冷却节流,避免频繁对话反复写盘。
|
|
1682
|
+
"""
|
|
1683
|
+
changes = {"表达欲": 2.0}
|
|
1684
|
+
kind = (rec.get("kind") or "")
|
|
1685
|
+
if kind in ("question", "insight", "curiosity"):
|
|
1686
|
+
changes["求知欲"] = 4.0
|
|
1687
|
+
if _num(imp, 0) >= 0.7:
|
|
1688
|
+
changes["成就欲"] = 3.0
|
|
1689
|
+
try:
|
|
1690
|
+
desire_nudge(changes)
|
|
1691
|
+
except Exception:
|
|
1692
|
+
pass # 六欲牵动是锦上添花,绝不能让记事本身失败
|
|
1693
|
+
|
|
1694
|
+
|
|
1695
|
+
def entity_profile(name: str, limit: int = 20) -> dict:
|
|
1696
|
+
"""实体档案卡(Zep 风格):围绕一个人物/事物把散落的记忆聚成一张画像。
|
|
1697
|
+
|
|
1698
|
+
面板用:点开一个实体就能看到"什么时候第一次出现、最近一次出现、
|
|
1699
|
+
一起出现过的情绪、时间线、以及最重要几条记忆拼出的一句话画像"。
|
|
1700
|
+
"""
|
|
1701
|
+
name = (name or "").strip()
|
|
1702
|
+
if not name:
|
|
1703
|
+
raise ValueError("实体名不能为空")
|
|
1704
|
+
low = name.lower()
|
|
1705
|
+
hits = []
|
|
1706
|
+
for m in load_all() + load_archive():
|
|
1707
|
+
ents = [str(e).lower() for e in (m.get("entities") or [])]
|
|
1708
|
+
hay = _hay(m)
|
|
1709
|
+
# 优先按 entities 精确匹配;退化到 text/tags 里包含该词也算(实体抽取没跑全的兜底)
|
|
1710
|
+
if low in ents or low in hay:
|
|
1711
|
+
hits.append(m)
|
|
1712
|
+
if not hits:
|
|
1713
|
+
return {"entity": name, "count": 0, "timeline": [], "emotions": {},
|
|
1714
|
+
"summary": "(还没有关于这个实体的记忆)"}
|
|
1715
|
+
createds = [int(_num(m.get("created"), 0)) for m in hits if _num(m.get("created"), 0)]
|
|
1716
|
+
emotions = {}
|
|
1717
|
+
for m in hits:
|
|
1718
|
+
e = str(m.get("emotion") or "").strip()
|
|
1719
|
+
if e:
|
|
1720
|
+
emotions[e] = emotions.get(e, 0) + 1
|
|
1721
|
+
ordered = sorted(hits, key=lambda m: _num(m.get("created"), 0), reverse=True)
|
|
1722
|
+
timeline = [(fmt_time(int(_num(m.get("created"), 0))), str(display_text(m))[:80])
|
|
1723
|
+
for m in ordered[:max(1, limit)]]
|
|
1724
|
+
# 一句话画像:重要性最高的 3 条记忆拼接——实体"最被强调"的侧面
|
|
1725
|
+
top = sorted(hits, key=_imp_key_safe, reverse=True)[:3]
|
|
1726
|
+
summary = ";".join(str(m.get("text") or "") for m in top)[:120]
|
|
1727
|
+
first = min(createds) if createds else 0
|
|
1728
|
+
last = max(createds) if createds else 0
|
|
1729
|
+
return {
|
|
1730
|
+
"entity": name,
|
|
1731
|
+
"first_seen": first, "first_seen_text": fmt_time(first),
|
|
1732
|
+
"last_seen": last, "last_seen_text": fmt_time(last),
|
|
1733
|
+
"count": len(hits),
|
|
1734
|
+
"importance_avg": round(sum(_imp_key_safe(m) for m in hits) / len(hits), 3),
|
|
1735
|
+
"emotions": emotions,
|
|
1736
|
+
"timeline": timeline,
|
|
1737
|
+
"summary": summary or "(这些记忆没有可用正文)",
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
|
|
1741
|
+
class PrivacyDenied(Exception):
|
|
1742
|
+
"""第三人查询关于某人的记忆、且目标未授权时抛出。
|
|
1743
|
+
|
|
1744
|
+
故意不带目标标识细节进异常消息以外的字段——宿主直接把 message 回给群里即可,
|
|
1745
|
+
不需要(也不应该)在拒绝提示里暴露目标的记忆内容。
|
|
1746
|
+
"""
|
|
1747
|
+
|
|
1748
|
+
def __init__(self, target_user: str):
|
|
1749
|
+
# 完整标识只留在字段里供本地日志/调试使用,不进对外文案——
|
|
1750
|
+
# 拒绝提示若回显完整 ID,等于向群里确认「这个 ID 存在且有记忆」。
|
|
1751
|
+
self.target_user = str(target_user)
|
|
1752
|
+
super().__init__(
|
|
1753
|
+
"[隐私保护] 对方尚未授权在当前群分享记忆:需其本人查询,"
|
|
1754
|
+
"或由其本人在群内用 `lingshu 同意` 授权后重试。")
|
|
1755
|
+
|
|
1756
|
+
|
|
1757
|
+
def _channel_visible(m: dict, channel, group_id, user) -> bool:
|
|
1758
|
+
"""Strict bot visibility; unrestricted local queries remain local-only.
|
|
1759
|
+
|
|
1760
|
+
Group replies never include a user's memories from other groups/private
|
|
1761
|
+
chats. Another user's same-group memories require current consent. Global
|
|
1762
|
+
coding-agent/persona memories are never injected into bot conversations.
|
|
1763
|
+
"""
|
|
1764
|
+
if channel is None and group_id is None and user is None:
|
|
1765
|
+
return True
|
|
1766
|
+
if not channel or str(m.get("channel") or "") != str(channel):
|
|
1767
|
+
return False
|
|
1768
|
+
m_user, m_group = str(m.get("user") or ""), str(m.get("group_id") or "")
|
|
1769
|
+
own = bool(user) and m_user == str(user)
|
|
1770
|
+
if not group_id:
|
|
1771
|
+
# 私聊:本人记忆 + 全局/群公共(m_user 为空)对本机调用可见。
|
|
1772
|
+
# 通道上下文私聊(caller 在私聊里查自己):同语义——用户空的是群公共话题,可见。
|
|
1773
|
+
return own or not m_user
|
|
1774
|
+
if m_group != str(group_id):
|
|
1775
|
+
return False
|
|
1776
|
+
return own or not m_user or _consented(m_user, group_id)
|
|
1777
|
+
|
|
1778
|
+
|
|
1779
|
+
def _inject_memory_visible(m: dict, cfg: dict | None = None) -> bool:
|
|
1780
|
+
"""本机注入默认只带无通道与 dialogue:*;inject_channels 可显式放开指定通道。"""
|
|
1781
|
+
channel = str(m.get("channel") or "")
|
|
1782
|
+
if not channel or channel.startswith("dialogue:"):
|
|
1783
|
+
return True
|
|
1784
|
+
raw = (cfg or {}).get("inject_channels") or []
|
|
1785
|
+
if isinstance(raw, str):
|
|
1786
|
+
raw = [raw]
|
|
1787
|
+
allowed = {str(x) for x in raw}
|
|
1788
|
+
return "*" in allowed or channel in allowed
|
|
1789
|
+
|
|
1790
|
+
|
|
1791
|
+
def dereference(memory_id: str) -> list:
|
|
1792
|
+
"""#46 Memex 解引用:按 id 取一份摘要/蒸馏产物的证据原文。
|
|
1793
|
+
|
|
1794
|
+
返回 evidence_ids 指向的记忆(含被 supersede 的旧说法——那是"当时的原文",
|
|
1795
|
+
正是解引用最想拿回的证据;recall 默认跳过被取代者,这里显式放行)。
|
|
1796
|
+
没有指针或证据已被物理清理时返回空列表,调用方按"无证据"降级。
|
|
1797
|
+
"""
|
|
1798
|
+
rec = None
|
|
1799
|
+
for m in load_all():
|
|
1800
|
+
if m.get("id") == memory_id:
|
|
1801
|
+
rec = m
|
|
1802
|
+
break
|
|
1803
|
+
if rec is None:
|
|
1804
|
+
# 主层没有,翻归档(老证据可能已归档)
|
|
1805
|
+
for m in load_archive():
|
|
1806
|
+
if m.get("id") == memory_id:
|
|
1807
|
+
rec = m
|
|
1808
|
+
break
|
|
1809
|
+
if rec is None:
|
|
1810
|
+
return []
|
|
1811
|
+
ev_ids = [str(x) for x in (rec.get("evidence_ids") or rec.get("source_ids") or [])
|
|
1812
|
+
if str(x).strip()]
|
|
1813
|
+
if not ev_ids:
|
|
1814
|
+
return []
|
|
1815
|
+
want = set(ev_ids)
|
|
1816
|
+
out = []
|
|
1817
|
+
for m in load_all() + load_archive():
|
|
1818
|
+
if m.get("id") in want:
|
|
1819
|
+
out.append({"id": m["id"], "kind": m.get("kind", ""), "layer": m.get("layer", ""),
|
|
1820
|
+
"text": m.get("text", ""), "created": m.get("created"),
|
|
1821
|
+
"superseded_by": m.get("superseded_by")})
|
|
1822
|
+
want.discard(m["id"])
|
|
1823
|
+
if not want:
|
|
1824
|
+
break
|
|
1825
|
+
return out
|
|
1826
|
+
|
|
1827
|
+
|
|
1828
|
+
def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
1829
|
+
strengthen: bool = True, include_dust: bool = False,
|
|
1830
|
+
include_archive: bool = False,
|
|
1831
|
+
channel: str | None = None, group_id: str | None = None,
|
|
1832
|
+
user: str | None = None,
|
|
1833
|
+
target_user: str | None = None, asker: str | None = None,
|
|
1834
|
+
project: str | None = None,
|
|
1835
|
+
mode: str = "auto", with_evidence: bool = False, _archive_pass: int = 0) -> list:
|
|
1836
|
+
"""模糊回忆:相关度 + 近期性 + 重要性 + 联想扩散。返回 [(record, score, parts), ...]
|
|
1837
|
+
|
|
1838
|
+
with_evidence=True(#46 Memex 解引用):命中带 evidence_ids 指针的记忆(做梦合并/
|
|
1839
|
+
蒸馏产物)时,自动取回最多 2 条证据原文,作为 parts["evidence"] 列表附上
|
|
1840
|
+
(每条含 id/text,text 截 300 字)。默认 False——注入 prompt 的常规召回保持轻量;
|
|
1841
|
+
需要"追原文"的深度整理场景显式开启,或用 dereference(memory_id) 单条按需取。
|
|
1842
|
+
|
|
1843
|
+
mode 三种显式召回模式(#27):
|
|
1844
|
+
* "fast":只用词面/实体索引匹配——不调 embedding(dense)、不做 rerank 精排、
|
|
1845
|
+
不做关联扩散。低延迟,适合高频轻查询。
|
|
1846
|
+
* "deep":词面 + 向量 + 关联扩散 + rerank + 冲突提示,全量手段,
|
|
1847
|
+
适合重要回忆/做梦整理。
|
|
1848
|
+
* "auto"(默认):按查询长度/词面命中数自适应——查询短且词面已有足够命中
|
|
1849
|
+
走 fast,否则走 deep。等价于旧版的"能省则省"意图。
|
|
1850
|
+
实际生效的模式附在每个结果的 parts["mode"] 里,方便调用方/前端透传展示。
|
|
1851
|
+
|
|
1852
|
+
channel/group_id/user 任一给出即进入通道上下文:
|
|
1853
|
+
只召回「同群记忆 + 全局记忆 + 该用户自己的记忆」,其他群不可见;
|
|
1854
|
+
全部缺省(本机 CLI/面板)保持原行为——所有记忆都可召回。
|
|
1855
|
+
|
|
1856
|
+
隐私保护(可选,向后兼容:target_user/asker 缺省即不启用):
|
|
1857
|
+
target_user = 「查关于某人的记忆」的目标;asker = 发起查询的人。
|
|
1858
|
+
* asker == target_user → 本人可查自己的全部记忆;
|
|
1859
|
+
* 目标 _consented(target_user) → 已授权对外分享,放行;
|
|
1860
|
+
* 其余一律拒绝 → 返回 PrivacyDenied 异常。
|
|
1861
|
+
注意:owner/admin 豁免只适用于系统级命令(forget/dream/backup 等),
|
|
1862
|
+
对隐私查询刻意不豁免——主人能删库,但不能替群友决定「我的记忆给谁看」。
|
|
1863
|
+
群级记忆(有 group 无 user)属于群公共话题,不受此规则影响。
|
|
1864
|
+
"""
|
|
1865
|
+
if target_user:
|
|
1866
|
+
# asker 缺失 ≠ 本人:无身份的调用一律按"第三人"处理,
|
|
1867
|
+
# 不能因为拿不到身份就静默放行私密记忆(fail closed)。
|
|
1868
|
+
a = str(asker).strip() if asker is not None else ""
|
|
1869
|
+
if a != str(target_user).strip() and not _consented(target_user, group_id):
|
|
1870
|
+
raise PrivacyDenied(target_user)
|
|
1871
|
+
ensure_home()
|
|
1872
|
+
cfg = load_config()
|
|
1873
|
+
w = cfg["weights"]
|
|
1874
|
+
if mode not in ("fast", "deep", "auto"):
|
|
1875
|
+
raise ValueError(f"recall mode 只能是 fast/deep/auto,收到:{mode!r}")
|
|
1876
|
+
records = [m for m in load_all() if m.get("id") and (m.get("layer") in layers or (include_dust and m.get("layer") == "dust"))]
|
|
1877
|
+
# 被取代的记忆默认跳过:观念已更新,回忆里只出现新说法;
|
|
1878
|
+
# 需要"翻旧账"时走 show 单条查,沿 superseded_by 链还能回溯到旧观念。
|
|
1879
|
+
records = [m for m in records if not m.get("superseded_by")]
|
|
1880
|
+
# #28 冻结的记忆不参与召回(面板/CLI 解冻后立即恢复),show 仍可单条查
|
|
1881
|
+
records = [m for m in records if not m.get("frozen")]
|
|
1882
|
+
# 通道上下文的群间隔离:先物理过滤,其他群的记忆根本不进打分
|
|
1883
|
+
if channel is not None or group_id is not None or user is not None:
|
|
1884
|
+
records = [m for m in records if _channel_visible(m, channel, group_id, user)]
|
|
1885
|
+
if include_archive:
|
|
1886
|
+
archive = [m for m in load_archive() if m.get("id")
|
|
1887
|
+
and _channel_visible(m, channel, group_id, user)]
|
|
1888
|
+
# E-13:归档与现役层同 id 去重——同一记忆既在现役又有归档副本时只计现役一份,
|
|
1889
|
+
# 避免重复计分/重复展示。
|
|
1890
|
+
seen_ids = {m["id"] for m in records}
|
|
1891
|
+
records += [m for m in archive if m["id"] not in seen_ids]
|
|
1892
|
+
if target_user:
|
|
1893
|
+
records = [m for m in records if str(m.get("user") or "") == str(target_user)]
|
|
1894
|
+
# 第四轮#3:项目上下文——同项目记忆加成,不是硬过滤(跨项目的相关结论仍可浮上来,
|
|
1895
|
+
# 只是排到同项目之后)。加成幅度对齐 tag/entity 精确命中档(0.12/次,上限 0.25)。
|
|
1896
|
+
if project:
|
|
1897
|
+
_pj = str(project).strip().lower()
|
|
1898
|
+
for m in records:
|
|
1899
|
+
mp = str(m.get("project") or "").strip().lower()
|
|
1900
|
+
if mp and mp == _pj:
|
|
1901
|
+
m["_project_boost"] = 0.25
|
|
1902
|
+
if not records:
|
|
1903
|
+
return []
|
|
1904
|
+
now = now_ts()
|
|
1905
|
+
q_terms = terms(query)
|
|
1906
|
+
dense_scores = {} # P1 Dense 召回结果(id -> cosine);无 embed 服务/无向量时恒空
|
|
1907
|
+
# 无查询词(startup 注入)时不做 mode 裁决:没有词面证据可判断,
|
|
1908
|
+
# 后续 dense/关联扩散本就因 q_terms 为空不会触发;这里只定个有效值防 NameError。
|
|
1909
|
+
eff_mode = "deep" if mode == "auto" else mode
|
|
1910
|
+
# 第一道预筛:带查询词时先做廉价的子串包含测试,只对可能相关的记忆做正则分词与打分。
|
|
1911
|
+
# 上万条记忆时这一刀把"全量 terms + 全量 idf"砍成"候选集 terms";数学上不丢召回
|
|
1912
|
+
# (relevance>0 ⇔ 共享 term,而共享 term 必是本文档文本的连续子串)。
|
|
1913
|
+
if q_terms:
|
|
1914
|
+
cand = []
|
|
1915
|
+
for m in records:
|
|
1916
|
+
h = _hay(m)
|
|
1917
|
+
if any(t in h for t in q_terms):
|
|
1918
|
+
cand.append(m)
|
|
1919
|
+
# 扩散一跳要用全量索引:预筛只保证直接命中的召回,邻居多半不含查询词,
|
|
1920
|
+
# 若 id_map 只从候选集建,links 指向的邻居会被误判成"不存在"。
|
|
1921
|
+
full_index = {m["id"]: m for m in records}
|
|
1922
|
+
records = cand
|
|
1923
|
+
# —— mode 自适应裁决(#27)——
|
|
1924
|
+
# 短查询(<= 8 个词面 term)且词面候选已足够(>= k 条直接命中)时走 fast:
|
|
1925
|
+
# 词面证据已经充足,向量捞回的语义近似多半挤不进 Top-K,不值得付 embedding 调用;
|
|
1926
|
+
# 否则(长查询/词面命中稀薄)升 deep,补上 dense/rerank/关联扩散的完整链路。
|
|
1927
|
+
# 显式 mode=fast / mode=deep 则跳过裁决,完全按调用方意图执行。
|
|
1928
|
+
eff_mode = mode
|
|
1929
|
+
if mode == "auto":
|
|
1930
|
+
eff_mode = ("fast" if len(q_terms) <= 8 and len(records) >= max(k, 1)
|
|
1931
|
+
else "deep")
|
|
1932
|
+
# —— P1-1c Dense 召回:把"词面不重叠但语义相关"的记忆捞回候选集 ——
|
|
1933
|
+
# 关键词子串预筛是召回瓶颈:稀疏词面没交集的记忆("之前那个并发方案")
|
|
1934
|
+
# 会被上面一刀切掉。有 embedding 的记忆与 query 向量算 cosine,Top-N 并回
|
|
1935
|
+
# 候选集参与后续打分;未配置 embed 服务/无向量数据/调用失败时
|
|
1936
|
+
# dense_scores 为空,行为与纯关键词版本完全一致。
|
|
1937
|
+
# mode=fast 时跳过:低延迟模式不付 embedding 调用的延迟(#27)。
|
|
1938
|
+
if eff_mode != "fast":
|
|
1939
|
+
try:
|
|
1940
|
+
dense_scores = _dense_recall(query, full_index, top_n=max(k * 2, 10))
|
|
1941
|
+
if dense_scores:
|
|
1942
|
+
have = {m["id"] for m in records}
|
|
1943
|
+
for mid in dense_scores:
|
|
1944
|
+
if mid not in have:
|
|
1945
|
+
records.append(full_index[mid])
|
|
1946
|
+
except Exception as e:
|
|
1947
|
+
log_event("recall", f"Dense 召回失败,退回纯关键词:{e}", level="warn")
|
|
1948
|
+
dense_scores = {}
|
|
1949
|
+
if not records:
|
|
1950
|
+
# 热集一个候选都没有时,冷集补召分支(下方 avg<0.1)永远到不了——
|
|
1951
|
+
# 纯关键词模式下"只有 archive 里有匹配"的查询会整条漏掉。这里先递归
|
|
1952
|
+
# 捞一次冷集(补召同款门槛:一次、非隐私场景),捞不着才真的空手而归。
|
|
1953
|
+
if (not include_archive and _archive_pass < 1 and q_terms
|
|
1954
|
+
and not target_user):
|
|
1955
|
+
try:
|
|
1956
|
+
return recall(query, k, layers, strengthen, include_dust, True,
|
|
1957
|
+
channel, group_id, user, target_user, asker,
|
|
1958
|
+
mode=mode, _archive_pass=_archive_pass + 1)
|
|
1959
|
+
except Exception as e:
|
|
1960
|
+
log_event("recall", f"冷集兜底(热集空候选)失败:{e}", level="warn")
|
|
1961
|
+
return []
|
|
1962
|
+
# 无查询词(startup 注入等场景)不构建 terms/idf:relevance 恒为 0,省掉上万条的整库分词
|
|
1963
|
+
all_terms = {m["id"]: terms(_hay(m)) for m in records} if q_terms else {}
|
|
1964
|
+
idf = build_idf(list(all_terms.values())) if q_terms else {}
|
|
1965
|
+
|
|
1966
|
+
scored = []
|
|
1967
|
+
# —— persona core 关键词:永久规则加权——
|
|
1968
|
+
# persona.traits 里每条 trait 的 name(如"专注"、"耐心")+ drives 的 key,
|
|
1969
|
+
# 形成一个"核心规则关键词集"。记忆 tags/entities/kind 命中这些关键词时,
|
|
1970
|
+
# 追加 (1 + w.core_bias) 加权,让核心规则不被临时记录挤下去。
|
|
1971
|
+
# 懒加载:只读 persona.json 的 traits keys 和 drives keys,不做深拷贝。
|
|
1972
|
+
try:
|
|
1973
|
+
_p = load_persona()
|
|
1974
|
+
_core_terms = set()
|
|
1975
|
+
for t in (_p.get("traits") or {}).keys():
|
|
1976
|
+
_core_terms.add(str(t).lower())
|
|
1977
|
+
for d in (_p.get("drives") or {}).keys():
|
|
1978
|
+
_core_terms.add(str(d).lower())
|
|
1979
|
+
for e in (_p.get("identity") or {}).values():
|
|
1980
|
+
if e and isinstance(e, str):
|
|
1981
|
+
_core_terms.add(e.lower())
|
|
1982
|
+
# 底线/价值观/关系等 persona 顶层字段
|
|
1983
|
+
for key in ("values", "likes", "dislikes"):
|
|
1984
|
+
for v in (_p.get(key) or []) if isinstance(_p.get(key), list) else []:
|
|
1985
|
+
if v and isinstance(v, str):
|
|
1986
|
+
_core_terms.add(v.lower())
|
|
1987
|
+
_has_core_bias = bool(_core_terms) and w.get("core_bias", 0) > 0
|
|
1988
|
+
except Exception:
|
|
1989
|
+
_core_terms = set()
|
|
1990
|
+
_has_core_bias = False
|
|
1991
|
+
|
|
1992
|
+
# 首因效应:同一片记忆里最早留下的印象占权更高(第一次的印象比后来补的更深)
|
|
1993
|
+
oldest = max((now - _num(m.get("created"), now) for m in records), default=0)
|
|
1994
|
+
for m in records:
|
|
1995
|
+
rel = relevance(q_terms, all_terms[m["id"]], idf) if q_terms else 0.0
|
|
1996
|
+
# Dense 语义分托底:向量说"像"但词面没重叠(rel=0)时用语义分当 relevance;
|
|
1997
|
+
# 词面已命中时取两者较大值,语义只增不减。
|
|
1998
|
+
_ds = dense_scores.get(m["id"]) if dense_scores else None
|
|
1999
|
+
if _ds is not None and _ds > rel:
|
|
2000
|
+
rel = _ds
|
|
2001
|
+
rec = retention(m, now)
|
|
2002
|
+
imp = _num(m.get("importance"), 0.5)
|
|
2003
|
+
score = w["relevance"] * rel + w["recency"] * rec + w["importance"] * imp
|
|
2004
|
+
# 首因:最早创建的那批(年龄接近最大)给一点额外权重
|
|
2005
|
+
age = now - _num(m.get("created"), now)
|
|
2006
|
+
if oldest > 0 and age >= oldest * 0.85:
|
|
2007
|
+
score += w.get("primacy", 0.03)
|
|
2008
|
+
# 标签/实体精确命中,显著加分
|
|
2009
|
+
hits = 0
|
|
2010
|
+
if query:
|
|
2011
|
+
q_low = query.lower()
|
|
2012
|
+
hits += sum(1 for t in m.get("tags", []) if str(t).lower() in q_low)
|
|
2013
|
+
hits += sum(1 for e in m.get("entities", []) if str(e).lower() in q_low)
|
|
2014
|
+
score += min(0.30, 0.12 * hits)
|
|
2015
|
+
# 第四轮#3:同项目记忆加成(recall(project=...) 时生效)
|
|
2016
|
+
if project and m.pop("_project_boost", None):
|
|
2017
|
+
score += 0.25
|
|
2018
|
+
# —— persona core 加权——
|
|
2019
|
+
# 记忆 kind=identity 或 tags/entities/kind 命中 persona 核心关键词时,
|
|
2020
|
+
# 追加 core_bias 比例加权;identity 是核心身份类,权重更高一点。
|
|
2021
|
+
if _has_core_bias:
|
|
2022
|
+
m_tags = set(str(t).lower() for t in (m.get("tags") or []))
|
|
2023
|
+
m_ents = set(str(e).lower() for e in (m.get("entities") or []))
|
|
2024
|
+
m_kind = str(m.get("kind") or "").lower()
|
|
2025
|
+
hits_core = m_tags & _core_terms or m_ents & _core_terms
|
|
2026
|
+
if m_kind in ("identity", "preference") or hits_core:
|
|
2027
|
+
boost = 1.0 + (w.get("core_bias", 0.20) * (1.5 if m_kind == "identity" else 1.0))
|
|
2028
|
+
score *= boost
|
|
2029
|
+
# —— 永久记忆:不再做"时间半衰"压分——
|
|
2030
|
+
# 原 score *= max(0.5, 0.5 ** (age_days / 30.0)) 让 3 个月前的核心偏好被压到
|
|
2031
|
+
# 50%,每月衰减、没有底板。永久记忆的"这件事本身过去多久"不该直接压分:
|
|
2032
|
+
# 语义匹配、重要性、重要标签命中、persona core 加权——这几样足够。
|
|
2033
|
+
# 原 age_boost 字段保留在 debug 里,但不再参与乘法压分。
|
|
2034
|
+
age_days = (now - _num(m.get("created"), now)) / DAY
|
|
2035
|
+
# (以上保留 age_days 只是给下方 age_boost debug 用,不乘进 score)
|
|
2036
|
+
_parts = {"relevance": round(rel, 3), "recency": round(rec, 3),
|
|
2037
|
+
"importance": imp, "hits": hits,
|
|
2038
|
+
"age_boost": 1.0}
|
|
2039
|
+
if _ds is not None:
|
|
2040
|
+
_parts["dense"] = round(_ds, 3) # 透明化:这条是向量语义捞回来的
|
|
2041
|
+
scored.append([m, score, _parts])
|
|
2042
|
+
|
|
2043
|
+
# 情绪一致性提取(mood-congruent recall):心情会偏向勾起同调性的记忆
|
|
2044
|
+
# ——难过时更容易想起难过的事,开心时更容易想起开心的事(Bower 1981)。
|
|
2045
|
+
mv = mood_now().get("valence", 0.0)
|
|
2046
|
+
if abs(mv) >= 0.2:
|
|
2047
|
+
for item in scored:
|
|
2048
|
+
e = item[0].get("emotion")
|
|
2049
|
+
if e and e in EMOTIONS:
|
|
2050
|
+
if _emotion_coord(e)[0] * mv > 0:
|
|
2051
|
+
item[1] += 0.06
|
|
2052
|
+
|
|
2053
|
+
# 有查询词时,只保留真正沾边的记忆(否则会污染注入包)
|
|
2054
|
+
if q_terms:
|
|
2055
|
+
scored = [x for x in scored if x[2]["relevance"] > 0.02 or x[2]["hits"] > 0]
|
|
2056
|
+
|
|
2057
|
+
scored.sort(key=lambda x: x[1], reverse=True)
|
|
2058
|
+
top = scored[: max(k, 1)]
|
|
2059
|
+
|
|
2060
|
+
# 联想扩散:与已选记忆共享实体/标签的获得小幅加成(像海马回放带动关联)
|
|
2061
|
+
top_ids = {x[0]["id"] for x in top}
|
|
2062
|
+
chosen_entities = set()
|
|
2063
|
+
chosen_tags = set()
|
|
2064
|
+
for m, _, _ in top:
|
|
2065
|
+
chosen_entities.update(m.get("entities", []))
|
|
2066
|
+
chosen_tags.update(m.get("tags", []))
|
|
2067
|
+
for item in scored[len(top):]:
|
|
2068
|
+
m = item[0]
|
|
2069
|
+
overlap = len(set(m.get("entities", [])) & chosen_entities) + 0.5 * len(set(m.get("tags", [])) & chosen_tags)
|
|
2070
|
+
if overlap >= 1:
|
|
2071
|
+
item[1] += min(0.10, 0.04 * overlap)
|
|
2072
|
+
# 显式联想:记忆之间已有的关联边把邻居也带起来("提到 A 就想起 B")
|
|
2073
|
+
# mode=fast 跳过关联扩散:低延迟模式只认词面直接命中(#27)。
|
|
2074
|
+
if (not READONLY or _assoc_file().exists()) and eff_mode != "fast":
|
|
2075
|
+
for r in load_assoc():
|
|
2076
|
+
if r["src"] in top_ids and r["dst"] not in top_ids:
|
|
2077
|
+
w = _num(r.get("weight"), 1)
|
|
2078
|
+
for item in scored[len(top):]:
|
|
2079
|
+
if item[0]["id"] == r["dst"]:
|
|
2080
|
+
item[1] += min(0.12, 0.04 * w)
|
|
2081
|
+
elif r["dst"] in top_ids and r["src"] not in top_ids:
|
|
2082
|
+
w = _num(r.get("weight"), 1)
|
|
2083
|
+
for item in scored[len(top):]:
|
|
2084
|
+
if item[0]["id"] == r["src"]:
|
|
2085
|
+
item[1] += min(0.12, 0.04 * w)
|
|
2086
|
+
|
|
2087
|
+
scored.sort(key=lambda x: x[1], reverse=True)
|
|
2088
|
+
|
|
2089
|
+
# —— P1-2 rerank 可插拔:粗排 Top-N 交外部 reranker 精排 ——
|
|
2090
|
+
# 配了 rerank.url 才调用;未配置/失败/返回为空都保持加权合并原顺序。
|
|
2091
|
+
# 重排语义:reranker 返回的索引序作为新顺序,没返回的条目按原加权序跟在后面,
|
|
2092
|
+
# 绝不丢条——精排只影响顺序,不影响召回集合。
|
|
2093
|
+
if q_terms and len(scored) > 1 and eff_mode != "fast":
|
|
2094
|
+
try:
|
|
2095
|
+
_n = min(len(scored), max(k * 3, 10))
|
|
2096
|
+
_head = scored[:_n]
|
|
2097
|
+
_pairs = rerank_docs(
|
|
2098
|
+
query,
|
|
2099
|
+
[str(x[0].get("text") or x[0].get("gist") or "") for x in _head],
|
|
2100
|
+
top_n=_n)
|
|
2101
|
+
if _pairs:
|
|
2102
|
+
_used = {i for i, _ in _pairs}
|
|
2103
|
+
scored = ([_head[i] for i, _ in _pairs]
|
|
2104
|
+
+ [x for j, x in enumerate(_head) if j not in _used]
|
|
2105
|
+
+ scored[_n:])
|
|
2106
|
+
except Exception as e:
|
|
2107
|
+
log_event("recall", f"rerank 精排失败,保持加权序:{e}", level="warn")
|
|
2108
|
+
|
|
2109
|
+
result = scored[: max(k, 1)]
|
|
2110
|
+
|
|
2111
|
+
# —— 永久记忆:热集空了自动捞冷集(archive)——
|
|
2112
|
+
# 如果热集 Top-K 的均分普遍很低(relevance/importance 都没沾边),说明当前
|
|
2113
|
+
# 会话窗口里根本没有相关记录——但 archive 里可能躺着很久以前的、永久保存
|
|
2114
|
+
# 的、语义完全正确的旧记忆。自动补召 1 次,不递归。
|
|
2115
|
+
if (not include_archive and _archive_pass < 1 and result and q_terms
|
|
2116
|
+
and not target_user): # 隐私/通道过滤的场景不走自动补召,留给显式开关
|
|
2117
|
+
avg = sum(x[1] for x in result) / max(1, len(result))
|
|
2118
|
+
if avg < 0.10: # 热集里 Top-K 均分 < 0.1,普遍没沾边
|
|
2119
|
+
try:
|
|
2120
|
+
return recall(query, k, layers, strengthen, include_dust, True,
|
|
2121
|
+
channel, group_id, user, target_user, asker,
|
|
2122
|
+
mode=mode, _archive_pass=_archive_pass + 1)
|
|
2123
|
+
except Exception as e:
|
|
2124
|
+
log_event("recall", f"冷集自动补召失败:{e}", level="warn")
|
|
2125
|
+
|
|
2126
|
+
# 沿 links 显式联想扩散一跳:命中的记忆通过 relink/裁决挂上的关联边,
|
|
2127
|
+
# 把直接邻居追加成"关联记忆"(linked: true),上限 5 条。
|
|
2128
|
+
# linked 项会参与侧抑制(怕跟原始命中重复)、也会参与 strengthen 写回
|
|
2129
|
+
# (被想起就是被想起)——但巩固倍率低于主动命中,语义是"顺带想起"。
|
|
2130
|
+
if result:
|
|
2131
|
+
direct_ids = {m["id"] for m, _, _ in result}
|
|
2132
|
+
linked_out, seen = [], set(direct_ids)
|
|
2133
|
+
id_map = full_index if (q_terms and full_index) else {m["id"]: m for m in records}
|
|
2134
|
+
for m, _, _ in result:
|
|
2135
|
+
for nid in (m.get("links") or []):
|
|
2136
|
+
if nid in seen:
|
|
2137
|
+
continue
|
|
2138
|
+
nb = id_map.get(nid)
|
|
2139
|
+
if nb is None:
|
|
2140
|
+
continue
|
|
2141
|
+
seen.add(nid)
|
|
2142
|
+
nb = dict(nb)
|
|
2143
|
+
nb["linked"] = True
|
|
2144
|
+
linked_out.append(nb)
|
|
2145
|
+
if len(linked_out) >= 5:
|
|
2146
|
+
break
|
|
2147
|
+
if len(linked_out) >= 5:
|
|
2148
|
+
break
|
|
2149
|
+
if linked_out:
|
|
2150
|
+
result = result + [(m, 0.0, {"linked": True}) for m in linked_out]
|
|
2151
|
+
|
|
2152
|
+
# 侧抑制去冗余(lateral inhibition):近似重复的痕迹只留最强一条。
|
|
2153
|
+
# 大脑不会同时点亮两份"同一件事",弱的那份被压下去。
|
|
2154
|
+
# 判重两种:字面高度重合,或一句是另一句的子串(同一件事的详略两版)。
|
|
2155
|
+
if len(result) > 1:
|
|
2156
|
+
kept, kept_terms, kept_texts = [], [], []
|
|
2157
|
+
for item in result:
|
|
2158
|
+
m = item[0]
|
|
2159
|
+
t = all_terms.get(m["id"]) or terms(m.get("text", ""))
|
|
2160
|
+
txt = (m.get("text") or "").strip()
|
|
2161
|
+
dup = any(jaccard(t, kt) >= 0.85 for kt in kept_terms)
|
|
2162
|
+
if not dup and txt:
|
|
2163
|
+
for ot in kept_texts:
|
|
2164
|
+
a, b = (txt, ot) if len(txt) <= len(ot) else (ot, txt)
|
|
2165
|
+
if a and a in b and len(a) >= 0.6 * len(b):
|
|
2166
|
+
dup = True
|
|
2167
|
+
break
|
|
2168
|
+
if dup:
|
|
2169
|
+
continue
|
|
2170
|
+
kept.append(item)
|
|
2171
|
+
kept_terms.append(t)
|
|
2172
|
+
kept_texts.append(txt)
|
|
2173
|
+
result = kept
|
|
2174
|
+
|
|
2175
|
+
if strengthen and not READONLY:
|
|
2176
|
+
touched = [m for m, _, _ in result]
|
|
2177
|
+
for m in touched:
|
|
2178
|
+
ac = int(_num(m.get("access_count"), 0))
|
|
2179
|
+
first = ac == 0
|
|
2180
|
+
m["access_count"] = ac + 1
|
|
2181
|
+
# 首次提取巩固更强:头一回想起来的事,印记打得比反复想起更深
|
|
2182
|
+
# (首因效应 + 首次测试效应:第一次回忆本身就是一次强巩固)
|
|
2183
|
+
# linked 项是"顺带想起",巩固倍率低一档(1.2 / 1.1)
|
|
2184
|
+
if m.get("linked"):
|
|
2185
|
+
mult = 1.2 if first else 1.1
|
|
2186
|
+
else:
|
|
2187
|
+
mult = 2.6 if first else 1.8
|
|
2188
|
+
m["stability"] = min(MAX_STABILITY, _num(m.get("stability"), DEFAULT_STABILITY) * mult + 4 * HOUR)
|
|
2189
|
+
m["last_access"] = now
|
|
2190
|
+
# detail 的落盘交给 _strengthen_write 在锁内以盘上现值重算巩固
|
|
2191
|
+
# (见 core._strengthen_write),这里只改内存快照供本次展示用。
|
|
2192
|
+
m["detail"] = min(1.0, _num(m.get("detail"), 1.0) * 0.9 + 0.1)
|
|
2193
|
+
# 只写回被"想起"的这条,别把没加载进来的层(如 dust)覆盖清空;没想起就不动盘
|
|
2194
|
+
# 定向写回:只重写命中记忆所在层,避免整库覆写(上万条时省掉大头 I/O)
|
|
2195
|
+
if touched:
|
|
2196
|
+
_strengthen_write(touched)
|
|
2197
|
+
|
|
2198
|
+
# —— 回忆牵动六欲:真想起点什么了,求知欲得到一点满足(自动微调,冷却节流)——
|
|
2199
|
+
# 只在有查询词且确实命中时触发,startup 注入(无 query)不算"回忆"。
|
|
2200
|
+
if q_terms and result and not READONLY:
|
|
2201
|
+
try:
|
|
2202
|
+
desire_nudge({"求知欲": 3.0}) # v3.68:1.5 → 3.0
|
|
2203
|
+
except Exception:
|
|
2204
|
+
pass # 锦上添花,失败不影响回忆本身
|
|
2205
|
+
# —— mode=deep 冲突提示(#27):命中记忆带未裁决冲突时在 parts 里提醒 ——
|
|
2206
|
+
# fast/auto 付不起 detect 级别的额外注意力,只有 deep(重要回忆/做梦整理)给提示。
|
|
2207
|
+
if eff_mode == "deep" and result:
|
|
2208
|
+
for m, _, parts in result:
|
|
2209
|
+
if m.get("conflict_flag") or m.get("conflicts"):
|
|
2210
|
+
parts["conflict_hint"] = ("该记忆存在未裁决的冲突说法(conflict_flag/conflicts),"
|
|
2211
|
+
"旧说法可能已过时——brain.py detect-conflicts 查看")
|
|
2212
|
+
# 实际生效模式写进每条 parts:调用方/前端可透传展示,不用猜到底走了哪条路
|
|
2213
|
+
for m, s, parts in result:
|
|
2214
|
+
parts["mode"] = eff_mode
|
|
2215
|
+
# #46 Memex 解引用(可选):带证据指针的命中自动附最多 2 条证据原文,
|
|
2216
|
+
# 让"概括 → 细节"两级可导航;失败/无指针静默降级,不影响召回主链路。
|
|
2217
|
+
if with_evidence and result:
|
|
2218
|
+
for m, s, parts in result:
|
|
2219
|
+
ev_ids = [str(x) for x in (m.get("evidence_ids") or []) if str(x).strip()]
|
|
2220
|
+
if not ev_ids:
|
|
2221
|
+
continue
|
|
2222
|
+
try:
|
|
2223
|
+
ev = dereference(m["id"])[:2]
|
|
2224
|
+
if ev:
|
|
2225
|
+
parts["evidence"] = [{"id": e["id"], "text": (e.get("text") or "")[:300]}
|
|
2226
|
+
for e in ev]
|
|
2227
|
+
except Exception as e:
|
|
2228
|
+
log_event("recall", f"证据解引用失败({m.get('id')}):{e}", level="warn")
|
|
2229
|
+
return [(m, round(s, 4), parts) for m, s, parts in result]
|
|
2230
|
+
|
|
2231
|
+
|
|
2232
|
+
def recent(k: int = 6, layers: tuple = ("hippo", "cortex")) -> list:
|
|
2233
|
+
records = [m for m in load_all() if m.get("layer") in layers]
|
|
2234
|
+
records.sort(key=lambda m: _num(m.get("created"), 0), reverse=True)
|
|
2235
|
+
return records[:k]
|
|
2236
|
+
|
|
2237
|
+
|
|
2238
|
+
def forget(memory_id: str) -> bool:
|
|
2239
|
+
# 读-改-写整体加锁:forget 用的是 save_all 整库快照覆写,
|
|
2240
|
+
# 不加锁会把锁外并发写入的新记忆一起丢回旧状态。
|
|
2241
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
2242
|
+
records = load_all()
|
|
2243
|
+
for m in records:
|
|
2244
|
+
if m.get("id") == memory_id and m.get("layer") != "dust":
|
|
2245
|
+
m["layer"] = "dust"
|
|
2246
|
+
m["forgotten_at"] = now_ts()
|
|
2247
|
+
m["detail"] = round(max(0.15, _num(m.get("detail"), 1.0) * 0.5), 2)
|
|
2248
|
+
save_all(records)
|
|
2249
|
+
audit_log("user", "forget", memory_id, "记忆移入淡忘区")
|
|
2250
|
+
return True
|
|
2251
|
+
return False
|
|
2252
|
+
|
|
2253
|
+
|
|
2254
|
+
# ---------------------------------------------------------------- #34 物理删除(多重确认)
|
|
2255
|
+
# 设计:物理销毁与逻辑删除(forget→dust)分离。物理删除必须同时满足两道闸:
|
|
2256
|
+
# 1. 目标已在 dust 层且 forgotten_at 距今 ≥ 7 天(先逻辑删除冷静期,避免冲动);
|
|
2257
|
+
# 2. 调用方显式传入 confirm_token == id 前 8 位(手输确认,防 AI 误调/脚本误跑)。
|
|
2258
|
+
# 删除时同步切断 assoc.jsonl 里指向该 id 的关联边,archive 层若有副本也一并清掉。
|
|
2259
|
+
# 任何一道闸不满足都抛 ValueError,不动数据。
|
|
2260
|
+
|
|
2261
|
+
_PURGE_COOLDOWN_DAYS = 7
|
|
2262
|
+
|
|
2263
|
+
|
|
2264
|
+
def purge(memory_id: str, confirm_token: str) -> dict:
|
|
2265
|
+
"""物理删除一条记忆(#34,双重确认)。
|
|
2266
|
+
|
|
2267
|
+
前置条件(两道闸,缺一不可):
|
|
2268
|
+
* 目标在 dust 层,且 forgotten_at 距今 ≥ 7 天(冷静期);
|
|
2269
|
+
* confirm_token == memory_id 前 8 位(手输确认,防误调)。
|
|
2270
|
+
返回 {"removed": True, "layer": ...};不满足抛 ValueError。
|
|
2271
|
+
READONLY 抛 PermissionError。
|
|
2272
|
+
"""
|
|
2273
|
+
if READONLY:
|
|
2274
|
+
raise PermissionError("记忆库当前只读,无法物理删除。")
|
|
2275
|
+
if not confirm_token or confirm_token != memory_id[:8]:
|
|
2276
|
+
raise ValueError(
|
|
2277
|
+
f"物理删除需显式确认:--confirm {memory_id[:8]}(传入的确认码不匹配)")
|
|
2278
|
+
cutoff = now_ts() - _PURGE_COOLDOWN_DAYS * DAY
|
|
2279
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
2280
|
+
records = load_all()
|
|
2281
|
+
target = next((m for m in records if m.get("id") == memory_id), None)
|
|
2282
|
+
if not target:
|
|
2283
|
+
# 热层没有,去 archive 找——archive 副本也算可删(但同样要求冷静期)
|
|
2284
|
+
with _locked(HOME / "archive.jsonl"):
|
|
2285
|
+
archive = load_archive()
|
|
2286
|
+
target = next((m for m in archive if m.get("id") == memory_id), None)
|
|
2287
|
+
if not target:
|
|
2288
|
+
raise ValueError(f"没有这条记忆:{memory_id}")
|
|
2289
|
+
archived_at = _num(target.get("archived_at") or target.get("forgotten_at"), 0)
|
|
2290
|
+
if archived_at > cutoff:
|
|
2291
|
+
raise ValueError(
|
|
2292
|
+
f"归档记忆需冷静满 {_PURGE_COOLDOWN_DAYS} 天后才能物理删除"
|
|
2293
|
+
f"(当前归档于 {fmt_date(archived_at)})")
|
|
2294
|
+
archive = [m for m in archive if m.get("id") != memory_id]
|
|
2295
|
+
write_jsonl(HOME / "archive.jsonl", archive)
|
|
2296
|
+
_cut_assoc_links(memory_id)
|
|
2297
|
+
audit_log("user", "purge", memory_id, "物理删除(archive 副本)")
|
|
2298
|
+
return {"removed": True, "layer": "archive"}
|
|
2299
|
+
if target.get("layer") != "dust":
|
|
2300
|
+
raise ValueError(
|
|
2301
|
+
f"只有淡忘区(dust)的记忆才能物理删除,当前层:{target.get('layer')}。"
|
|
2302
|
+
f"先 `memory forget {memory_id}` 转 dust,满 {_PURGE_COOLDOWN_DAYS} 天后再 purge。")
|
|
2303
|
+
forgotten_at = _num(target.get("forgotten_at"), 0)
|
|
2304
|
+
if forgotten_at > cutoff:
|
|
2305
|
+
raise ValueError(
|
|
2306
|
+
f"淡忘记忆需冷静满 {_PURGE_COOLDOWN_DAYS} 天后才能物理删除"
|
|
2307
|
+
f"(当前淡忘于 {fmt_date(forgotten_at)})")
|
|
2308
|
+
records = [m for m in records if m.get("id") != memory_id]
|
|
2309
|
+
save_all(records)
|
|
2310
|
+
# archive 里可能也有同名副本(归档过的),一并清掉
|
|
2311
|
+
with _locked(HOME / "archive.jsonl"):
|
|
2312
|
+
archive = load_archive()
|
|
2313
|
+
if any(m.get("id") == memory_id for m in archive):
|
|
2314
|
+
archive = [m for m in archive if m.get("id") != memory_id]
|
|
2315
|
+
write_jsonl(HOME / "archive.jsonl", archive)
|
|
2316
|
+
_cut_assoc_links(memory_id)
|
|
2317
|
+
audit_log("user", "purge", memory_id, "物理删除")
|
|
2318
|
+
return {"removed": True, "layer": "dust"}
|
|
2319
|
+
|
|
2320
|
+
|
|
2321
|
+
def _cut_assoc_links(memory_id: str) -> None:
|
|
2322
|
+
"""切断 assoc.jsonl 里 src 或 dst 指向 memory_id 的关联边(purge 时调用)。"""
|
|
2323
|
+
try:
|
|
2324
|
+
af = HOME / "assoc.jsonl"
|
|
2325
|
+
if not af.exists():
|
|
2326
|
+
return
|
|
2327
|
+
with _locked(af):
|
|
2328
|
+
edges = read_jsonl(af)
|
|
2329
|
+
kept = [e for e in edges
|
|
2330
|
+
if isinstance(e, dict)
|
|
2331
|
+
and e.get("src") != memory_id
|
|
2332
|
+
and e.get("dst") != memory_id]
|
|
2333
|
+
if len(kept) != len(edges):
|
|
2334
|
+
write_jsonl(af, kept)
|
|
2335
|
+
except Exception as exc:
|
|
2336
|
+
log_event("purge", f"切断关联边失败(不影响删除本身):{exc}", level="warn")
|
|
2337
|
+
|
|
2338
|
+
|
|
2339
|
+
# ---------------------------------------------------------------- 淡忘可逆(fold / unfold)
|
|
2340
|
+
# 借鉴 billion-context 的区间折叠:淡忘不是「回不来」,只是「收起来了」。
|
|
2341
|
+
# fold 把原文压进 folded_text、正文换成 gist(数据还在,随时能解压还原);
|
|
2342
|
+
# unfold 是可逆通道——「想起来」时一条命令把原文、层、细节度原样还原。
|
|
2343
|
+
|
|
2344
|
+
def fold(memory_id: str) -> dict:
|
|
2345
|
+
"""折叠一条淡忘记忆:原文收进 folded_text,正文只留 gist。
|
|
2346
|
+
|
|
2347
|
+
只有 dust 层可以 fold(还在用/待审的记忆不许压);已经 fold 过的再 fold 幂等。
|
|
2348
|
+
"""
|
|
2349
|
+
if READONLY:
|
|
2350
|
+
raise PermissionError("记忆库当前只读,无法折叠。")
|
|
2351
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
2352
|
+
records = load_all()
|
|
2353
|
+
target = next((m for m in records if m.get("id") == memory_id), None)
|
|
2354
|
+
if not target:
|
|
2355
|
+
raise ValueError(f"没有这条记忆:{memory_id}")
|
|
2356
|
+
if target.get("layer") != "dust":
|
|
2357
|
+
raise ValueError("只有淡忘区(dust)的记忆可以折叠")
|
|
2358
|
+
if not target.get("folded"):
|
|
2359
|
+
target["folded_text"] = target.get("text", "")
|
|
2360
|
+
target["text"] = target.get("gist") or heuristic_gist(target.get("text", ""))
|
|
2361
|
+
target["folded"] = True
|
|
2362
|
+
target["folded_at"] = now_ts()
|
|
2363
|
+
save_all(records)
|
|
2364
|
+
return dict(target)
|
|
2365
|
+
|
|
2366
|
+
|
|
2367
|
+
def unfold(memory_id: str) -> dict:
|
|
2368
|
+
"""解压还原:把 fold 收起来的原文放回正文,并给一条「想起来」的巩固。
|
|
2369
|
+
|
|
2370
|
+
unfold 之后记忆仍留在 dust 层(想不想恢复活跃由 strengthen/restore 决定),
|
|
2371
|
+
但原文完整、detail 回升,recall include_dust 时能完整命中。
|
|
2372
|
+
"""
|
|
2373
|
+
if READONLY:
|
|
2374
|
+
raise PermissionError("记忆库当前只读,无法解压。")
|
|
2375
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
2376
|
+
records = load_all()
|
|
2377
|
+
target = next((m for m in records if m.get("id") == memory_id), None)
|
|
2378
|
+
if not target:
|
|
2379
|
+
raise ValueError(f"没有这条记忆:{memory_id}")
|
|
2380
|
+
if not target.get("folded"):
|
|
2381
|
+
return dict(target) # 幂等:没折过就原样返回
|
|
2382
|
+
target["text"] = target.get("folded_text", target.get("text", ""))
|
|
2383
|
+
target.pop("folded_text", None)
|
|
2384
|
+
target["folded"] = False
|
|
2385
|
+
target["unfolded_at"] = now_ts()
|
|
2386
|
+
# 「想起来」的一次巩固:细节度回升,但层不动(用户要彻底恢复用 revive)
|
|
2387
|
+
target["detail"] = round(min(1.0, _num(target.get("detail"), 0.3) + 0.3), 2)
|
|
2388
|
+
target["last_access"] = now_ts()
|
|
2389
|
+
target["access_count"] = int(_num(target.get("access_count"), 0)) + 1
|
|
2390
|
+
save_all(records)
|
|
2391
|
+
return dict(target)
|
|
2392
|
+
|
|
2393
|
+
|
|
2394
|
+
def revive(memory_id: str, layer: str = "cortex") -> dict:
|
|
2395
|
+
"""从淡忘区彻底复活:unfold 还原原文 + 回到指定活跃层(cortex/hippo)。
|
|
2396
|
+
|
|
2397
|
+
与 archive restore 对应:archive 是「原文保真的冷库」,dust fold 是
|
|
2398
|
+
「摘要化的半遗忘」,revive 是从半遗忘里正式想起来的通道。
|
|
2399
|
+
"""
|
|
2400
|
+
if READONLY:
|
|
2401
|
+
raise PermissionError("记忆库当前只读,无法复活。")
|
|
2402
|
+
if layer not in ("cortex", "hippo"):
|
|
2403
|
+
raise ValueError("复活目标层只能是 cortex 或 hippo")
|
|
2404
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
2405
|
+
records = load_all()
|
|
2406
|
+
target = next((m for m in records if m.get("id") == memory_id), None)
|
|
2407
|
+
if not target:
|
|
2408
|
+
raise ValueError(f"没有这条记忆:{memory_id}")
|
|
2409
|
+
if target.get("layer") != "dust":
|
|
2410
|
+
raise ValueError("这条记忆不在淡忘区,无需复活")
|
|
2411
|
+
if target.get("folded"):
|
|
2412
|
+
target["text"] = target.get("folded_text", target.get("text", ""))
|
|
2413
|
+
target.pop("folded_text", None)
|
|
2414
|
+
target["folded"] = False
|
|
2415
|
+
target["layer"] = layer
|
|
2416
|
+
target["detail"] = max(_num(target.get("detail"), 0.3), 0.6)
|
|
2417
|
+
target.pop("forgotten_at", None)
|
|
2418
|
+
target["revived_at"] = now_ts()
|
|
2419
|
+
target["last_access"] = now_ts()
|
|
2420
|
+
save_all(records)
|
|
2421
|
+
audit_log("user", "revive", memory_id, f"淡忘记忆复活到 {layer} 层")
|
|
2422
|
+
return dict(target)
|
|
2423
|
+
|
|
2424
|
+
|
|
2425
|
+
def display_text(m: dict) -> str:
|
|
2426
|
+
"""细节度低时用模糊化的要点代替原文。fold 过的条目提示「已折叠、可展开还原」。"""
|
|
2427
|
+
if m.get("folded"):
|
|
2428
|
+
return f"{m.get('text', '')}(已折叠:原文收起,可 unfold 展开还原)"
|
|
2429
|
+
detail = _num(m.get("detail"), 1.0)
|
|
2430
|
+
if detail < 0.5 and m.get("gist"):
|
|
2431
|
+
return f"{m['gist']}(细节已模糊)"
|
|
2432
|
+
return m.get("text", "")
|
|
2433
|
+
|
|
2434
|
+
def _usage_terms(text: str) -> set:
|
|
2435
|
+
return {t for t in terms(text) if t not in _USAGE_STOP}
|
|
2436
|
+
|
|
2437
|
+
|
|
2438
|
+
def record_retrieval(query: str, mems, channel: str = "recall") -> None:
|
|
2439
|
+
"""记下本轮找回/注入的记忆,供 usage 核对是否真的出现在回复里。
|
|
2440
|
+
|
|
2441
|
+
只存 id + 文本摘要,不存整库;失败静默,绝不影响回忆本身。
|
|
2442
|
+
"""
|
|
2443
|
+
if READONLY:
|
|
2444
|
+
return
|
|
2445
|
+
items = []
|
|
2446
|
+
for x in mems or []:
|
|
2447
|
+
m = x[0] if isinstance(x, (tuple, list)) and x else x
|
|
2448
|
+
if not isinstance(m, dict) or not m.get("id"):
|
|
2449
|
+
continue
|
|
2450
|
+
items.append({"id": m["id"], "layer": m.get("layer"),
|
|
2451
|
+
"text": display_text(m)[:240]})
|
|
2452
|
+
if not items:
|
|
2453
|
+
return
|
|
2454
|
+
try:
|
|
2455
|
+
atomic_json(RETRIEVAL_FILE, {"ts": now_ts(), "query": query or "",
|
|
2456
|
+
"channel": channel, "items": items})
|
|
2457
|
+
except Exception as e:
|
|
2458
|
+
log_event("usage", f"回忆快照写入失败:{e}", level="warn")
|
|
2459
|
+
|
|
2460
|
+
|
|
2461
|
+
def evaluate_retrieval_usage(reply: str) -> dict:
|
|
2462
|
+
"""粗判上一轮找回的记忆有没有出现在回复里(关键词重叠)。
|
|
2463
|
+
|
|
2464
|
+
不是判定"模型有没有抄记忆",只是回答"这条记忆对这次输出有没有贡献"。
|
|
2465
|
+
核对过一次就作废,避免同一批记忆被重复计数。
|
|
2466
|
+
"""
|
|
2467
|
+
snap = _slurp_json(RETRIEVAL_FILE, {}) or {}
|
|
2468
|
+
if not isinstance(snap, dict) or not snap.get("items"):
|
|
2469
|
+
return {"error": "没有待核对的回忆记录:先 recall 或 startup,再 usage --reply"}
|
|
2470
|
+
if snap.get("evaluated_at"):
|
|
2471
|
+
return {"error": "上一批回忆已经核对过了;先重新 recall,再 usage"}
|
|
2472
|
+
reply_terms = _usage_terms(reply)
|
|
2473
|
+
if not reply_terms:
|
|
2474
|
+
return {"error": "回复文本没有可比较的关键词(太短或全是虚词)"}
|
|
2475
|
+
by_id = {m.get("id"): m for m in load_all() if m.get("id")}
|
|
2476
|
+
now = now_ts()
|
|
2477
|
+
touched, rows, used_ids = [], [], []
|
|
2478
|
+
for it in snap["items"]:
|
|
2479
|
+
mid = it.get("id")
|
|
2480
|
+
mt = _usage_terms(it.get("text", ""))
|
|
2481
|
+
shared = mt & reply_terms
|
|
2482
|
+
ratio = round(len(shared) / max(1, len(mt)), 3)
|
|
2483
|
+
used = len(shared) >= USAGE_MIN_SHARED and ratio >= USAGE_MIN_RATIO
|
|
2484
|
+
# 短记忆只共享一个词也可能是真用上了(如"只让叫阿哲")
|
|
2485
|
+
if not used and len(shared) == 1 and len(mt) <= 12:
|
|
2486
|
+
used = True
|
|
2487
|
+
rows.append({"id": mid, "used": used, "shared": len(shared), "ratio": ratio,
|
|
2488
|
+
"hits": sorted(shared)[:8]})
|
|
2489
|
+
m = by_id.get(mid)
|
|
2490
|
+
if used and m:
|
|
2491
|
+
m["used_count"] = int(_num(m.get("used_count"), 0)) + 1
|
|
2492
|
+
m["used_at"] = now
|
|
2493
|
+
m["used_hits"] = sorted(shared)[:8]
|
|
2494
|
+
touched.append(m)
|
|
2495
|
+
used_ids.append(mid)
|
|
2496
|
+
if touched:
|
|
2497
|
+
_strengthen_write(touched)
|
|
2498
|
+
if not READONLY:
|
|
2499
|
+
try:
|
|
2500
|
+
with _locked(USAGE_FILE):
|
|
2501
|
+
hist = read_jsonl(USAGE_FILE)
|
|
2502
|
+
hist.append({"ts": now, "query": snap.get("query", ""),
|
|
2503
|
+
"channel": snap.get("channel", ""),
|
|
2504
|
+
"recalled": [r["id"] for r in rows],
|
|
2505
|
+
"used": used_ids, "items": rows})
|
|
2506
|
+
write_jsonl(USAGE_FILE, hist[-1000:])
|
|
2507
|
+
atomic_json(RETRIEVAL_FILE, dict(snap, evaluated_at=now))
|
|
2508
|
+
except Exception as e:
|
|
2509
|
+
log_event("usage", f"使用反馈写入失败:{e}", level="warn")
|
|
2510
|
+
recalled = [it.get("id") for it in snap["items"]]
|
|
2511
|
+
return {"recalled": len(recalled), "used": len(used_ids),
|
|
2512
|
+
"rate": round(len(used_ids) / len(recalled), 3) if recalled else 0.0,
|
|
2513
|
+
"query": snap.get("query", ""), "channel": snap.get("channel", ""),
|
|
2514
|
+
"items": rows}
|
|
2515
|
+
|
|
2516
|
+
|
|
2517
|
+
def usage_bad(mid: str) -> dict:
|
|
2518
|
+
"""v3.02 #9:召回负反馈——用户明确否定某条被找回的记忆。
|
|
2519
|
+
|
|
2520
|
+
在 assoc.jsonl 记一条自环负边(relation="否定",weight 逐次更负),
|
|
2521
|
+
关联图/召回排序看到负权重即可降权;重复否定会累积。
|
|
2522
|
+
"""
|
|
2523
|
+
if READONLY:
|
|
2524
|
+
raise PermissionError("记忆库当前只读,无法记负反馈。")
|
|
2525
|
+
mid = str(mid or "").strip()
|
|
2526
|
+
if not mid:
|
|
2527
|
+
raise ValueError("请给出要否定的记忆 id(usage --bad <id>)")
|
|
2528
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
2529
|
+
target = next((m for m in load_all() if m.get("id") == mid), None)
|
|
2530
|
+
if not target:
|
|
2531
|
+
raise KeyError(f"没有这条记忆:{mid}(用 recall 或 list 拿 id)")
|
|
2532
|
+
with _locked(_assoc_file()):
|
|
2533
|
+
rows = load_assoc()
|
|
2534
|
+
edge = next((r for r in rows if r.get("src") == mid and r.get("dst") == mid
|
|
2535
|
+
and r.get("relation") == "否定"), None)
|
|
2536
|
+
if edge is not None:
|
|
2537
|
+
edge["weight"] = round(_num(edge.get("weight"), -1) - 1.0, 2)
|
|
2538
|
+
edge["ts"] = now_ts()
|
|
2539
|
+
edge["count"] = int(_num(edge.get("count"), 1)) + 1
|
|
2540
|
+
save_assoc(rows)
|
|
2541
|
+
return {"id": mid, "bad_count": edge["count"], "weight": edge["weight"],
|
|
2542
|
+
"created": False}
|
|
2543
|
+
rows.append({"src": mid, "dst": mid, "relation": "否定", "weight": -1.0,
|
|
2544
|
+
"count": 1, "why": "usage --bad", "ts": now_ts()})
|
|
2545
|
+
save_assoc(rows)
|
|
2546
|
+
return {"id": mid, "bad_count": 1, "weight": -1.0, "created": True}
|
|
2547
|
+
|
|
2548
|
+
|
|
2549
|
+
def usage_metrics() -> dict:
|
|
2550
|
+
"""历史回忆使用率(只算已经核对过的批次)+ 负反馈计数(#9)。"""
|
|
2551
|
+
rows = read_jsonl(USAGE_FILE)
|
|
2552
|
+
recalled = sum(len(r.get("recalled") or []) for r in rows)
|
|
2553
|
+
used = sum(len(r.get("used") or []) for r in rows)
|
|
2554
|
+
try:
|
|
2555
|
+
bad = sum(max(0, int(_num(r.get("count"), 1)))
|
|
2556
|
+
for r in load_assoc() if r.get("relation") == "否定")
|
|
2557
|
+
except Exception:
|
|
2558
|
+
bad = 0
|
|
2559
|
+
return {"events": len(rows), "recalled": recalled, "used": used,
|
|
2560
|
+
"rate": round(used / recalled, 3) if recalled else 0.0, "bad": bad}
|
|
2561
|
+
|
|
2562
|
+
|
|
2563
|
+
# ---------------------------------------------------------------- 工作记忆
|
|
2564
|
+
# 默认工作记忆 = 当前上下文,不进磁盘,也不参与回忆。
|
|
2565
|
+
# 这里的函数只服务一种情况:AI 自己判断「这条先别忘,但还不值得成为长期记忆」。
|
|
2566
|
+
|
|
2567
|
+
# 已完成条目的保留期:`work done` 之后还留一天,让 AI/用户还能回看"刚做完什么",
|
|
2568
|
+
# 过期就物理归档到 working-archive.jsonl(不再进入注入扫描)。未完成的仍按 12h 丢。
|
|
2569
|
+
WORK_DONE_TTL = 24 * HOUR
|
|
2570
|
+
|
|
2571
|
+
|
|
2572
|
+
def load_working() -> list:
|
|
2573
|
+
if not WORKING_FILE.exists():
|
|
2574
|
+
return []
|
|
2575
|
+
now = now_ts()
|
|
2576
|
+
rows = []
|
|
2577
|
+
for r in read_jsonl(WORKING_FILE):
|
|
2578
|
+
try:
|
|
2579
|
+
ts = float(r.get("ts") or 0)
|
|
2580
|
+
except (TypeError, ValueError):
|
|
2581
|
+
ts = 0
|
|
2582
|
+
ttl = WORKING_TTL
|
|
2583
|
+
if not r.get("open", True):
|
|
2584
|
+
# 已完成的按"完成时间"算 24h 保留期(没有 done_at 的老数据退回创建时间)
|
|
2585
|
+
ttl = WORK_DONE_TTL
|
|
2586
|
+
ts = _num(r.get("done_at"), ts)
|
|
2587
|
+
if now - ts < ttl:
|
|
2588
|
+
rows.append(r)
|
|
2589
|
+
return rows
|
|
2590
|
+
|
|
2591
|
+
|
|
2592
|
+
def work_status() -> dict:
|
|
2593
|
+
rows = load_working()
|
|
2594
|
+
return {"capacity": WORKING_CAPACITY, "count": len(rows),
|
|
2595
|
+
"open_count": sum(1 for r in rows if r.get("open", True)),
|
|
2596
|
+
"ttl_hours": int(WORKING_TTL / HOUR), "items": rows}
|
|
2597
|
+
|
|
2598
|
+
|
|
2599
|
+
def work_add(text: str, tag: str = "", why: str = "") -> list:
|
|
2600
|
+
"""把一条工作记忆显式落盘为会话暂存。这是 AI 自己的决定,不是自动行为。"""
|
|
2601
|
+
text = (text or "").strip()
|
|
2602
|
+
if not text:
|
|
2603
|
+
raise ValueError("工作记忆内容为空")
|
|
2604
|
+
ensure_home()
|
|
2605
|
+
with _locked(WORKING_FILE):
|
|
2606
|
+
rows = load_working()
|
|
2607
|
+
rows.append({"ts": now_ts(), "text": text,
|
|
2608
|
+
"tag": (tag or "").strip(), "why": (why or "").strip(),
|
|
2609
|
+
"open": True})
|
|
2610
|
+
rows = rows[-WORKING_CAPACITY:]
|
|
2611
|
+
write_jsonl(WORKING_FILE, rows)
|
|
2612
|
+
return rows
|
|
2613
|
+
|
|
2614
|
+
|
|
2615
|
+
def _work_archive_path():
|
|
2616
|
+
"""归档文件跟着 WORKING_FILE 的目录走(--home 切换后自动同迁)。"""
|
|
2617
|
+
return WORKING_FILE.parent / "working-archive.jsonl"
|
|
2618
|
+
|
|
2619
|
+
|
|
2620
|
+
def _sweep_locked(rows: list) -> int:
|
|
2621
|
+
"""把做完超过 WORK_DONE_TTL 的条目提出并追加到归档,返回归档条数。
|
|
2622
|
+
|
|
2623
|
+
调用方必须已持有 WORKING_FILE 的写锁,并自行写回 rows。
|
|
2624
|
+
归档逐行追加(core._append_jsonl 是单行语义,别在这层再包一个同名函数)。
|
|
2625
|
+
"""
|
|
2626
|
+
now = now_ts()
|
|
2627
|
+
keep, arch = [], []
|
|
2628
|
+
for r in rows:
|
|
2629
|
+
if not r.get("open", True):
|
|
2630
|
+
done_at = _num(r.get("done_at"), _num(r.get("ts"), 0))
|
|
2631
|
+
if now - done_at >= WORK_DONE_TTL:
|
|
2632
|
+
r = dict(r)
|
|
2633
|
+
r["archived_at"] = now
|
|
2634
|
+
arch.append(r)
|
|
2635
|
+
continue
|
|
2636
|
+
keep.append(r)
|
|
2637
|
+
if arch:
|
|
2638
|
+
rows[:] = keep
|
|
2639
|
+
path = _work_archive_path()
|
|
2640
|
+
for r in arch:
|
|
2641
|
+
try:
|
|
2642
|
+
_append_jsonl(path, r)
|
|
2643
|
+
except OSError:
|
|
2644
|
+
pass
|
|
2645
|
+
return len(arch)
|
|
2646
|
+
|
|
2647
|
+
|
|
2648
|
+
def work_sweep() -> int:
|
|
2649
|
+
"""物理归档做完超过一天的条目(幂等;读多写少,随时可调)。
|
|
2650
|
+
|
|
2651
|
+
从原始文件读:load_working 会把 ≥24h 的已完成条目直接过滤掉,
|
|
2652
|
+
用过滤后的视图永远看不见该归档的行。
|
|
2653
|
+
"""
|
|
2654
|
+
if READONLY:
|
|
2655
|
+
return 0
|
|
2656
|
+
with _locked(WORKING_FILE):
|
|
2657
|
+
raw = [r for r in read_jsonl(WORKING_FILE) if isinstance(r, dict)]
|
|
2658
|
+
moved = _sweep_locked(raw)
|
|
2659
|
+
# 顺带按原口径丢掉过期的未完成项,避免文件里攒一堆看不见的僵尸行
|
|
2660
|
+
now = now_ts()
|
|
2661
|
+
kept = [r for r in raw if now - _num(r.get("ts"), 0) < WORKING_TTL]
|
|
2662
|
+
dropped = len(raw) - len(kept)
|
|
2663
|
+
if moved or dropped:
|
|
2664
|
+
write_jsonl(WORKING_FILE, kept)
|
|
2665
|
+
return moved
|
|
2666
|
+
|
|
2667
|
+
|
|
2668
|
+
def work_done(idx: int) -> list:
|
|
2669
|
+
"""把暂存里第 idx 条(从 1 起)标记为已完成。
|
|
2670
|
+
|
|
2671
|
+
蔡格尼克效应:没做完的事会在脑子里反复冒出来;一旦做完,
|
|
2672
|
+
动机满足了,它就迅速退场——"完成"本身就是一种释放。
|
|
2673
|
+
完成时间记在 done_at 上:24 小时后由 work_sweep 物理归档。
|
|
2674
|
+
"""
|
|
2675
|
+
with _locked(WORKING_FILE):
|
|
2676
|
+
rows = load_working()
|
|
2677
|
+
if 1 <= idx <= len(rows):
|
|
2678
|
+
rows[idx - 1]["open"] = False
|
|
2679
|
+
rows[idx - 1]["done_at"] = now_ts()
|
|
2680
|
+
write_jsonl(WORKING_FILE, rows)
|
|
2681
|
+
return rows
|
|
2682
|
+
|
|
2683
|
+
|
|
2684
|
+
def work_clear() -> None:
|
|
2685
|
+
with _locked(WORKING_FILE):
|
|
2686
|
+
if WORKING_FILE.exists():
|
|
2687
|
+
write_jsonl(WORKING_FILE, [])
|
|
2688
|
+
|
|
2689
|
+
|
|
2690
|
+
def work_flush(why: str = "会话结束前决定留下", skip_done: bool = False) -> dict:
|
|
2691
|
+
"""把暂存里还值得留的条目一次性转成真正的记忆(海马体),然后清空暂存。
|
|
2692
|
+
|
|
2693
|
+
skip_done=True 时,已经 `work done` 标记完成的条目直接丢弃、不落盘——
|
|
2694
|
+
做完的事就该放下,不必再占长期记忆。返回 {"saved": [...], "dropped": n}。
|
|
2695
|
+
"""
|
|
2696
|
+
# 读-转-清 一次加锁完成:不加锁的话,两个终端同时 flush / add,
|
|
2697
|
+
# 后 flush 的会拿旧快照把并发新增的暂存条目一起清掉(静默丢失)。
|
|
2698
|
+
with _locked(WORKING_FILE):
|
|
2699
|
+
rows = load_working()
|
|
2700
|
+
saved, dropped = [], 0
|
|
2701
|
+
for r in rows:
|
|
2702
|
+
if skip_done and not r.get("open", True):
|
|
2703
|
+
dropped += 1
|
|
2704
|
+
continue
|
|
2705
|
+
tags = ["工作记忆"] + ([r["tag"]] if r.get("tag") else [])
|
|
2706
|
+
rec, how = remember(r["text"], kind="episode", tags=tags, source="ai")
|
|
2707
|
+
saved.append({"id": rec["id"], "text": rec["text"], "how": how})
|
|
2708
|
+
# 已持锁:直接清空,不能再调 work_clear()(它会重复抢同一把锁→自锁超时)
|
|
2709
|
+
write_jsonl(WORKING_FILE, [])
|
|
2710
|
+
# 审核闭环:work flush 是 AI 自动整理的写入路径,产出的记忆默认进待审池;
|
|
2711
|
+
# 已有 review 的不覆盖(用户手动 remember 不经过这里,不受影响)。
|
|
2712
|
+
try:
|
|
2713
|
+
mark_auto_review_pending([s["id"] for s in saved], "work-flush")
|
|
2714
|
+
except Exception as exc: # noqa: BLE001
|
|
2715
|
+
log_event("memory", f"work flush 标待审失败(不影响已转记忆):{exc}", level="warn")
|
|
2716
|
+
if saved:
|
|
2717
|
+
try:
|
|
2718
|
+
import growth
|
|
2719
|
+
growth.log_evolution("self", "把工作记忆转成长期记忆",
|
|
2720
|
+
f"{why};共 {len(saved)} 条", [s["id"] for s in saved])
|
|
2721
|
+
except Exception:
|
|
2722
|
+
pass
|
|
2723
|
+
return {"saved": saved, "dropped": dropped}
|
|
2724
|
+
|
|
2725
|
+
|
|
2726
|
+
# ---------------------------------------------------------------- 话题栈(拟人闲聊)
|
|
2727
|
+
# 话题栈已拆到 mem_topic.py(v3.69),下方由文件末尾的 star-import 提供。
|
|
2728
|
+
# ---------------------------------------------------------------- 上下文封存(capture)
|
|
2729
|
+
|
|
2730
|
+
|
|
2731
|
+
# ---------------------------------------------------------------- 上下文封存(capture)
|
|
2732
|
+
|
|
2733
|
+
VERBATIM_DIR = HOME / "verbatim"
|
|
2734
|
+
CAPTURE_MIN_LEN = 4
|
|
2735
|
+
|
|
2736
|
+
|
|
2737
|
+
# 说话人前缀(v3.72):即记即存写进来的是插件的 `user:` / `assistant:`(小写英文),
|
|
2738
|
+
# 原正则只认 `User`/`Assistant` 大写开头 + 中文,导致小写前缀既不断段、也无归属,
|
|
2739
|
+
# 整段对话混成一条,AI 的话随整段去重被吞——真库里于是"只有用户说的话"。
|
|
2740
|
+
# 借鉴 Graphiti 的 role→speaker mapping / dual-mem 的 L1 完整对话层:
|
|
2741
|
+
# 用大小写不敏感匹配 + 中英文角色词,且**保留角色前缀**到段落文本里(谁说的可追溯)。
|
|
2742
|
+
_SPEAKER_RE = re.compile(
|
|
2743
|
+
r"^(user|human|me|assistant|ai|bot|model|tool|system|用户|我|助手|灵枢|AI)\s*[::]",
|
|
2744
|
+
re.IGNORECASE,
|
|
2745
|
+
)
|
|
2746
|
+
|
|
2747
|
+
|
|
2748
|
+
def _split_segments(text: str) -> list:
|
|
2749
|
+
"""把一段会话原文切成可独立成条的片段:空行 / 分隔线 / 说话人切换。
|
|
2750
|
+
|
|
2751
|
+
v3.72:说话人切换保留角色前缀(如 `assistant:…`),使每条记忆可归因;
|
|
2752
|
+
大小写不敏感,兼容插件写入的 `user:` / `assistant:` 与中文 `我:`。
|
|
2753
|
+
"""
|
|
2754
|
+
text = (text or "").replace("\r\n", "\n").replace("\r", "\n")
|
|
2755
|
+
# 分隔线(---、***、===)当成硬边界
|
|
2756
|
+
text = re.sub(r"\n\s*(?:-{3,}|\*{3,}|={3,})\s*\n", "\n\n", text)
|
|
2757
|
+
segs, cur = [], []
|
|
2758
|
+
for line in text.split("\n"):
|
|
2759
|
+
s = line.strip()
|
|
2760
|
+
if not s:
|
|
2761
|
+
if cur:
|
|
2762
|
+
segs.append(" ".join(cur))
|
|
2763
|
+
cur = []
|
|
2764
|
+
continue
|
|
2765
|
+
# 说话人切换:保留前缀到新段落(speaker attribution)
|
|
2766
|
+
if cur and _SPEAKER_RE.match(s):
|
|
2767
|
+
segs.append(" ".join(cur))
|
|
2768
|
+
cur = [s]
|
|
2769
|
+
else:
|
|
2770
|
+
cur.append(s)
|
|
2771
|
+
if cur:
|
|
2772
|
+
segs.append(" ".join(cur))
|
|
2773
|
+
out = []
|
|
2774
|
+
for s in segs:
|
|
2775
|
+
s = re.sub(r"\s+", " ", s).strip()
|
|
2776
|
+
if len(s) >= CAPTURE_MIN_LEN:
|
|
2777
|
+
out.append(s)
|
|
2778
|
+
return out
|
|
2779
|
+
|
|
2780
|
+
|
|
2781
|
+
def capture(payload: str, tag: str = "", kind: str = "episode",
|
|
2782
|
+
importance: float | None = None, raw_only: bool = False,
|
|
2783
|
+
source: str = "ai", correction: bool = False) -> dict:
|
|
2784
|
+
"""把当前上下文原样封存进记忆库,保证 70%→100% 之间的话不会随滚动丢掉。
|
|
2785
|
+
|
|
2786
|
+
与 remember 的区别:remember 是提炼后的结论;capture 是"原文搬运",
|
|
2787
|
+
允许粗糙、允许啰嗦,目的只有一个——先保住,别丢。之后做梦再压缩。
|
|
2788
|
+
"""
|
|
2789
|
+
ensure_home()
|
|
2790
|
+
payload = (payload or "").strip()
|
|
2791
|
+
if not payload:
|
|
2792
|
+
raise ValueError("封存内容为空")
|
|
2793
|
+
# v3.02 #1:先脱敏再落盘——verbatim 归档与海马体两个去向都必须是脱敏后的文本
|
|
2794
|
+
payload = redact(payload)
|
|
2795
|
+
if READONLY:
|
|
2796
|
+
raise PermissionError("记忆库当前只读,无法封存。用 --home 指向可写目录。")
|
|
2797
|
+
|
|
2798
|
+
ts = now_ts()
|
|
2799
|
+
# 1) 原文归档:无论如何先留一份完整快照,一个字都不改
|
|
2800
|
+
VERBATIM_DIR.mkdir(parents=True, exist_ok=True)
|
|
2801
|
+
archive = VERBATIM_DIR / f"{datetime.fromtimestamp(ts).strftime('%Y%m%d_%H%M%S')}.md"
|
|
2802
|
+
k = 1
|
|
2803
|
+
while archive.exists():
|
|
2804
|
+
archive = VERBATIM_DIR / f"{datetime.fromtimestamp(ts).strftime('%Y%m%d_%H%M%S')}_{k}.md"
|
|
2805
|
+
k += 1
|
|
2806
|
+
head = [f"# 上下文封存 · {fmt_time(ts)}", ""]
|
|
2807
|
+
if tag:
|
|
2808
|
+
head.append(f"标签:{tag}")
|
|
2809
|
+
head.append(f"字符数:{len(payload)}")
|
|
2810
|
+
head.append("")
|
|
2811
|
+
write_text_atomic(archive, "\n".join(head) + payload + "\n")
|
|
2812
|
+
|
|
2813
|
+
# 2) 逐段进海马体(--raw-only 时跳过:只留原文快照,不污染记忆库)
|
|
2814
|
+
if raw_only:
|
|
2815
|
+
return {"saved": [], "skipped": 0, "archive": archive, "chars": len(payload)}
|
|
2816
|
+
# 读-去重-写整体加锁:不加锁时两个并发 capture 会各自拿到同一份旧快照,
|
|
2817
|
+
# 互相看不出对方刚存的段,结果同一句话被存两遍。
|
|
2818
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
2819
|
+
records = load_all()
|
|
2820
|
+
existing = [terms(m.get("text", "")) for m in records if m.get("layer") != "dust"]
|
|
2821
|
+
tags = ["封存"] + ([tag] if tag else [])
|
|
2822
|
+
saved, skipped = [], 0
|
|
2823
|
+
for seg in _split_segments(payload):
|
|
2824
|
+
t = terms(seg)
|
|
2825
|
+
if any(jaccard(t, e) >= 0.92 for e in existing):
|
|
2826
|
+
skipped += 1
|
|
2827
|
+
continue
|
|
2828
|
+
rec = make_record(seg, kind=kind, importance=importance, tags=tags,
|
|
2829
|
+
source=source, layer="hippo")
|
|
2830
|
+
rec["verbatim"] = True
|
|
2831
|
+
# P5 #21 verbatim 召回:记下这条原文出自哪个封存快照,让
|
|
2832
|
+
# `recall --verbatim <id>` 能按 id 直接展开逐字原文(老记忆无此字段,
|
|
2833
|
+
# 召回时用文本匹配兜底)。归档文件名唯一,不含绝对路径,换机器也能用。
|
|
2834
|
+
rec["verbatim_path"] = archive.name
|
|
2835
|
+
rec["detail"] = 1.0
|
|
2836
|
+
# #41 correction 语义:封存的改口原文同样打标,合并/提炼路径会特殊对待
|
|
2837
|
+
if correction:
|
|
2838
|
+
rec["correction"] = True
|
|
2839
|
+
records.append(rec)
|
|
2840
|
+
existing.append(t)
|
|
2841
|
+
saved.append(rec)
|
|
2842
|
+
if saved:
|
|
2843
|
+
# 封存段也建联想链:capture 是原文搬运,段落之间/与历史记忆的关联照挂
|
|
2844
|
+
for rec in saved:
|
|
2845
|
+
try:
|
|
2846
|
+
relink(rec, records)
|
|
2847
|
+
except Exception:
|
|
2848
|
+
pass
|
|
2849
|
+
save_all(records)
|
|
2850
|
+
return {"saved": saved, "skipped": skipped, "archive": archive, "chars": len(payload)}
|
|
2851
|
+
|
|
2852
|
+
|
|
2853
|
+
def verbatim_source(mem_id: str) -> dict:
|
|
2854
|
+
"""按记忆 id 取回它对应的**逐字原文快照**(P5 #21 / foldkeep 借鉴)。
|
|
2855
|
+
|
|
2856
|
+
压缩/做梦是有损的,AI 可能合并改写;每条 verbatim 记忆都该能追溯到原始
|
|
2857
|
+
封存文件。取法两步:
|
|
2858
|
+
1) 新记忆有 `verbatim_path` → 直接读那个文件;
|
|
2859
|
+
2) 老记忆没有 path → 在 verbatim/*.md 里搜包含该记忆 text 的文件
|
|
2860
|
+
(取最长片段匹配,避免短句命中多个快照)。
|
|
2861
|
+
|
|
2862
|
+
返回 {ok, path, text, via};失败返回 {ok: False, reason: ...},绝不抛异常。
|
|
2863
|
+
"""
|
|
2864
|
+
mid = str(mem_id or "").strip()
|
|
2865
|
+
if not mid:
|
|
2866
|
+
return {"ok": False, "reason": "缺少记忆 id"}
|
|
2867
|
+
try:
|
|
2868
|
+
target = None
|
|
2869
|
+
for m in load_all() + load_archive():
|
|
2870
|
+
if str(m.get("id") or "") == mid:
|
|
2871
|
+
target = m
|
|
2872
|
+
break
|
|
2873
|
+
if target is None:
|
|
2874
|
+
return {"ok": False, "reason": f"没有这条记忆:{mid}"}
|
|
2875
|
+
if not target.get("verbatim"):
|
|
2876
|
+
return {"ok": False, "reason": "这条记忆不是原文封存(无 verbatim 标记)"}
|
|
2877
|
+
files = []
|
|
2878
|
+
vp = target.get("verbatim_path")
|
|
2879
|
+
if vp:
|
|
2880
|
+
p = VERBATIM_DIR / Path(str(vp)).name # 只取文件名,防路径穿越
|
|
2881
|
+
if p.is_file():
|
|
2882
|
+
files.append(p)
|
|
2883
|
+
if not files and VERBATIM_DIR.is_dir():
|
|
2884
|
+
files = sorted(VERBATIM_DIR.glob("*.md"))
|
|
2885
|
+
text = str(target.get("text") or "").strip()
|
|
2886
|
+
if not files:
|
|
2887
|
+
return {"ok": False, "reason": "没有找到 verbatim 原文快照"}
|
|
2888
|
+
if vp and len(files) == 1:
|
|
2889
|
+
return {"ok": True, "path": files[0].name,
|
|
2890
|
+
"text": files[0].read_text(encoding="utf-8"), "via": "path"}
|
|
2891
|
+
# 文本兜底:找包含记忆原文的文件(用最长片段,短句用前 24 字)
|
|
2892
|
+
needle = text[:40] if len(text) >= 40 else text
|
|
2893
|
+
for p in sorted(files, key=lambda f: f.stat().st_mtime, reverse=True):
|
|
2894
|
+
body = p.read_text(encoding="utf-8", errors="replace")
|
|
2895
|
+
if needle and needle in body:
|
|
2896
|
+
return {"ok": True, "path": p.name, "text": body, "via": "text-match"}
|
|
2897
|
+
# 连片段都匹配不上:返回最新那份(并注明是猜测)
|
|
2898
|
+
p = max(files, key=lambda f: f.stat().st_mtime)
|
|
2899
|
+
return {"ok": True, "path": p.name,
|
|
2900
|
+
"text": p.read_text(encoding="utf-8"), "via": "fallback-latest"}
|
|
2901
|
+
except Exception as exc:
|
|
2902
|
+
return {"ok": False, "reason": f"读取原文失败:{exc}"}
|
|
2903
|
+
|
|
2904
|
+
|
|
2905
|
+
# ---------------------------------------------------------------- 教训库(#36 lessons.jsonl)
|
|
2906
|
+
# 失败闭环的落点:做梦从「被取代的旧记忆 + conflict 记录 + correction 改口」里提炼出
|
|
2907
|
+
# 可复用的教训,先入 pending 待审(与 knowledge/persona 的一致审核闸同约定),
|
|
2908
|
+
# review confirm 后转 active 开始注入。教训靠 validate 反复校准:
|
|
2909
|
+
# 教训库已拆到 mem_lesson.py(v3.70),下方由文件末尾的 star-import 提供。
|
|
2910
|
+
# injectable_lessons 依赖关联图(_assoc_file),仍留在本文件。
|
|
2911
|
+
|
|
2912
|
+
|
|
2913
|
+
def injectable_lessons(query: str = "", k: int = 5) -> list:
|
|
2914
|
+
"""注入用教训:active 且未 retired,按 confidence 取前 k 条。
|
|
2915
|
+
有 query 时把词面命中的教训排到最前(提示「已有教训:xxx」)。"""
|
|
2916
|
+
cand = [l for l in load_lessons()
|
|
2917
|
+
if l.get("status") == "active" and not l.get("retired")]
|
|
2918
|
+
if not cand:
|
|
2919
|
+
return []
|
|
2920
|
+
if query:
|
|
2921
|
+
q_terms = terms(query)
|
|
2922
|
+
hit, other = [], []
|
|
2923
|
+
for l in cand:
|
|
2924
|
+
l_terms = terms(l.get("text", ""))
|
|
2925
|
+
if q_terms & l_terms or jaccard(q_terms, l_terms) >= 0.25:
|
|
2926
|
+
l["_hit"] = True
|
|
2927
|
+
hit.append(l)
|
|
2928
|
+
else:
|
|
2929
|
+
other.append(l)
|
|
2930
|
+
# 命中按 confidence 排前,其余补足到 k
|
|
2931
|
+
hit.sort(key=lambda l: -_num(l.get("confidence"), 0.5))
|
|
2932
|
+
other.sort(key=lambda l: -_num(l.get("confidence"), 0.5))
|
|
2933
|
+
return (hit + other)[:k]
|
|
2934
|
+
return sorted(cand, key=lambda l: -_num(l.get("confidence"), 0.5))[:k]
|
|
2935
|
+
|
|
2936
|
+
|
|
2937
|
+
def _lessons_injection(query: str = "") -> str:
|
|
2938
|
+
"""注入包小节:active 教训按 confidence 注入,命中 query 的排最前并标「已有教训」。"""
|
|
2939
|
+
ls = injectable_lessons(query, k=5)
|
|
2940
|
+
if not ls:
|
|
2941
|
+
return ""
|
|
2942
|
+
lines = []
|
|
2943
|
+
for l in ls:
|
|
2944
|
+
mark = "已有教训" if query and l.get("_hit") else "教训"
|
|
2945
|
+
conf = f"置信度 {_num(l.get('confidence'), 0.5):.2f},已验证 {int(_num(l.get('times_validated'), 0))} 次"
|
|
2946
|
+
lines.append(f"- [{mark}] {l['text']}({conf})")
|
|
2947
|
+
return "\n## 教训(#36 失败闭环:先用上,别再踩同一个坑)\n" + "\n".join(lines)
|
|
2948
|
+
|
|
2949
|
+
|
|
2950
|
+
# ---------------------------------------------------------------- 记忆关联(联想能力)
|
|
2951
|
+
# 人有联想:一件事会牵出另一件。记忆之间除了"文本像不像",还有显式的关联边——
|
|
2952
|
+
# "A 导致了 B"、"A 和 B 是同一件事的两个侧面"、"提到 A 就会想起 B"。
|
|
2953
|
+
# recall 时,命中的记忆会沿关联边把邻居也带起来(联想扩散的显式版)。
|
|
2954
|
+
# 注意:ASSOC_FILE 定义在 emotion.py;这里保持调用时动态取 emotion.ASSOC_FILE,
|
|
2955
|
+
# 避免 core.ensure_home 切换 HOME 后本模块残留指向旧目录。
|
|
2956
|
+
import emotion as _emotion_mod # noqa: E402
|
|
2957
|
+
|
|
2958
|
+
def _assoc_file():
|
|
2959
|
+
return _emotion_mod.ASSOC_FILE
|
|
2960
|
+
|
|
2961
|
+
def load_assoc() -> list:
|
|
2962
|
+
raw = read_jsonl(_assoc_file())
|
|
2963
|
+
good, bad = [], 0
|
|
2964
|
+
for r in raw:
|
|
2965
|
+
if isinstance(r, dict) and r.get("src") and r.get("dst"):
|
|
2966
|
+
good.append(r)
|
|
2967
|
+
else:
|
|
2968
|
+
bad += 1
|
|
2969
|
+
if bad:
|
|
2970
|
+
log_event("load", f"load_assoc 跳过 {bad} 条畸形边(缺 src/dst 或类型错)", level="warning")
|
|
2971
|
+
return good
|
|
2972
|
+
|
|
2973
|
+
|
|
2974
|
+
def save_assoc(rows: list) -> None:
|
|
2975
|
+
write_jsonl(_assoc_file(), rows)
|
|
2976
|
+
|
|
2977
|
+
|
|
2978
|
+
# ---------------------------------------------------------------- relink 联想建链
|
|
2979
|
+
# 联想不只是 recall 时的隐性扩散,还该显式落到记录上:新记忆写进来时,与历史里
|
|
2980
|
+
# 词面最相近的几条互挂 links——之后 recall 命中任意一条都能顺藤摸瓜带出邻居。
|
|
2981
|
+
|
|
2982
|
+
def relink(record: dict, records: list | None = None,
|
|
2983
|
+
max_links: int = 5, min_score: float = 1.0) -> list:
|
|
2984
|
+
"""给一条记忆找最相关的若干条历史记忆,双向写 links。
|
|
2985
|
+
|
|
2986
|
+
用现成的 terms()/jaccard() 词面相似度打分(text+tags+entities 合并算),
|
|
2987
|
+
得分 >= min_score 的历史记忆按分数取前 max_links 条。
|
|
2988
|
+
records 传入调用方已 load 的整库快照(remember/capture 均在锁内调用,
|
|
2989
|
+
传入锁内快照避免重复读盘);缺省时自行 load_all()。
|
|
2990
|
+
返回实际建链的邻居 id 列表。只追加不去重已有链接之外的内容,
|
|
2991
|
+
合并写法与 set_memory_review 一致(list(dict.fromkeys(...)))。
|
|
2992
|
+
"""
|
|
2993
|
+
text = str(record.get("text") or "").strip()
|
|
2994
|
+
if not text:
|
|
2995
|
+
return []
|
|
2996
|
+
my_terms = terms(_hay(record))
|
|
2997
|
+
if not my_terms:
|
|
2998
|
+
return []
|
|
2999
|
+
rid = record.get("id")
|
|
3000
|
+
if records is None:
|
|
3001
|
+
records = load_all()
|
|
3002
|
+
scored = []
|
|
3003
|
+
for other in records:
|
|
3004
|
+
if not isinstance(other, dict) or other.get("id") == rid:
|
|
3005
|
+
continue
|
|
3006
|
+
if other.get("layer") in ("dust", ARCHIVE_LAYER):
|
|
3007
|
+
continue
|
|
3008
|
+
ot = terms(_hay(other))
|
|
3009
|
+
if not ot:
|
|
3010
|
+
continue
|
|
3011
|
+
sim = jaccard(my_terms, ot)
|
|
3012
|
+
# 分数 = 相似度×10 取整刻度,min_score=1 即 jaccard≥0.1 才值得建链
|
|
3013
|
+
score = round(sim * 10, 2)
|
|
3014
|
+
if score >= min_score:
|
|
3015
|
+
scored.append((score, other["id"]))
|
|
3016
|
+
scored.sort(key=lambda x: x[0], reverse=True)
|
|
3017
|
+
neighbors = [oid for _, oid in scored[:max(0, max_links)]]
|
|
3018
|
+
if not neighbors:
|
|
3019
|
+
return []
|
|
3020
|
+
changed = False
|
|
3021
|
+
old_links = list(record.get("links") or [])
|
|
3022
|
+
merged = list(dict.fromkeys(old_links + neighbors))
|
|
3023
|
+
if merged != old_links:
|
|
3024
|
+
record["links"] = merged
|
|
3025
|
+
changed = True
|
|
3026
|
+
for other in records:
|
|
3027
|
+
if other.get("id") in neighbors and rid and rid not in (other.get("links") or []):
|
|
3028
|
+
other["links"] = list(dict.fromkeys(list(other.get("links") or []) + [rid]))
|
|
3029
|
+
changed = True
|
|
3030
|
+
return neighbors if changed else []
|
|
3031
|
+
|
|
3032
|
+
|
|
3033
|
+
# ---------------------------------------------------------------- 每日自动归档
|
|
3034
|
+
# pending 记忆自动整理:事实型沉淀进 growth 知识库(add_knowledge,AI 来源按其
|
|
3035
|
+
# 审核机制默认 pending,走 knowledge review 转正);事件型写进笔记/日记
|
|
3036
|
+
# (growth.write_note 的 journal)。原记忆绝不删:打 archived_at 标记留档。
|
|
3037
|
+
# 拿不准分类的保持 pending 原样不动;pinned 不动。
|
|
3038
|
+
|
|
3039
|
+
_AUTO_ARCHIVE_FACT_CUES = ("是", "有", "能", "用", "在", "会", "需要", "属于", "等于",
|
|
3040
|
+
"吃", "喝", "喜欢", "爱", "叫", "姓", "住", "说", "知道",
|
|
3041
|
+
"觉得", "认为", "已经", "可能", "一定", "必须", "开始", "结束")
|
|
3042
|
+
_AUTO_ARCHIVE_TIME_CUES = ("今天", "昨天", "明天", "刚才", "刚刚", "早上", "上午",
|
|
3043
|
+
"下午", "晚上", "上周", "这周", "上次", "当时", "后来",
|
|
3044
|
+
"然后", "接着", "于是", "聊到", "他说", "她说", "我提到",
|
|
3045
|
+
"对话", "群里", "会议")
|
|
3046
|
+
_AUTO_ARCHIVE_FACT_MAX_LEN = 120 # 事实型通常是短结论;长文本多半是叙事
|
|
3047
|
+
|
|
3048
|
+
|
|
3049
|
+
def _classify_pending(text: str) -> str:
|
|
3050
|
+
"""pending 记忆分类:fact(事实型)/ episode(事件型)/ unknown(拿不准,不动)。"""
|
|
3051
|
+
t = text.strip()
|
|
3052
|
+
if not t:
|
|
3053
|
+
return "unknown"
|
|
3054
|
+
has_time = any(c in t for c in _AUTO_ARCHIVE_TIME_CUES)
|
|
3055
|
+
has_fact = any(c in t for c in _AUTO_ARCHIVE_FACT_CUES)
|
|
3056
|
+
if has_time and not has_fact:
|
|
3057
|
+
return "episode"
|
|
3058
|
+
if has_fact and not has_time and len(t) <= _AUTO_ARCHIVE_FACT_MAX_LEN:
|
|
3059
|
+
return "fact"
|
|
3060
|
+
# 既有时间叙述又像陈述句:时间性叙述优先按事件处理(对话叙事抄进日记不丢)
|
|
3061
|
+
if has_time and has_fact:
|
|
3062
|
+
return "episode"
|
|
3063
|
+
return "unknown"
|
|
3064
|
+
|
|
3065
|
+
|
|
3066
|
+
def auto_archive() -> dict:
|
|
3067
|
+
"""已确认(confirmed)记忆自动归档:事实型→知识库,事件型→日记笔记;原记忆标记 archived_at。
|
|
3068
|
+
|
|
3069
|
+
只处理 review == "confirmed" 的记忆(v2.55 修复:不再自动转正 pending——
|
|
3070
|
+
审核闸的设计是"AI 产物先待审,确认后才算事实",自动归档不能绕过它)。"""
|
|
3071
|
+
if READONLY:
|
|
3072
|
+
raise PermissionError("记忆库当前只读,无法自动归档。")
|
|
3073
|
+
import growth as _growth
|
|
3074
|
+
ensure_home()
|
|
3075
|
+
now = now_ts()
|
|
3076
|
+
moved = {"knowledge": 0, "notes": 0, "skipped": 0}
|
|
3077
|
+
details = []
|
|
3078
|
+
# 读-改-写整体加锁:与 remember/dream 一样走整库快照覆写,必须锁内完成
|
|
3079
|
+
with _locked(HOME / "hippocampus.jsonl"):
|
|
3080
|
+
records = load_all()
|
|
3081
|
+
changed = False
|
|
3082
|
+
for m in records:
|
|
3083
|
+
# 审核闸:只转正"已确认"的记忆。pending 意味着未经人工确认——
|
|
3084
|
+
# 每天自动把 AI 幻觉候选写进知识库等于绕过审核闸,这里绝不碰 pending。
|
|
3085
|
+
if m.get("review") != "confirmed" or m.get("pinned"):
|
|
3086
|
+
continue
|
|
3087
|
+
if m.get("layer") in ("dust", ARCHIVE_LAYER) or m.get("archived_at"):
|
|
3088
|
+
continue
|
|
3089
|
+
text = str(m.get("text") or "").strip()
|
|
3090
|
+
cls = _classify_pending(text)
|
|
3091
|
+
if cls == "unknown":
|
|
3092
|
+
moved["skipped"] += 1
|
|
3093
|
+
continue
|
|
3094
|
+
try:
|
|
3095
|
+
if cls == "fact":
|
|
3096
|
+
_growth.add_knowledge(title=_mem_gist_fallback(m), body=text,
|
|
3097
|
+
topic="", tags=list(m.get("tags") or []),
|
|
3098
|
+
source_ids=[m.get("id")], source="ai")
|
|
3099
|
+
moved["knowledge"] += 1
|
|
3100
|
+
else:
|
|
3101
|
+
_growth.write_note("journal", title=_mem_gist_fallback(m), body=text,
|
|
3102
|
+
tags=["归档"] + list(m.get("tags") or []),
|
|
3103
|
+
memory_ids=[m.get("id")])
|
|
3104
|
+
moved["notes"] += 1
|
|
3105
|
+
except Exception as exc:
|
|
3106
|
+
# 单条失败不拖垮整批:留痕并按"拿不准"跳过
|
|
3107
|
+
log_event("auto-archive", f"归档记忆 {m.get('id')} 失败:{exc}", level="warning")
|
|
3108
|
+
moved["skipped"] += 1
|
|
3109
|
+
continue
|
|
3110
|
+
# 只标记、不删不改层:原记忆留在原层,archived_at 表示已整理过
|
|
3111
|
+
m["archived_at"] = now
|
|
3112
|
+
changed = True
|
|
3113
|
+
details.append({"id": m.get("id"), "class": cls,
|
|
3114
|
+
"text": text[:40]})
|
|
3115
|
+
if changed:
|
|
3116
|
+
save_all(records)
|
|
3117
|
+
return {"moved": moved, "details": details}
|
|
3118
|
+
|
|
3119
|
+
|
|
3120
|
+
def _mem_gist_fallback(m: dict) -> str:
|
|
3121
|
+
"""给知识/笔记取标题:优先现成 gist,缺省用 heuristic_gist。"""
|
|
3122
|
+
t = str(m.get("gist") or "").strip()
|
|
3123
|
+
return t or heuristic_gist(str(m.get("text") or ""))
|
|
3124
|
+
|
|
3125
|
+
|
|
3126
|
+
def _norm_edge(a: str, b: str) -> tuple:
|
|
3127
|
+
return (a, b) if (a or "") < (b or "") else (b, a)
|
|
3128
|
+
|
|
3129
|
+
|
|
3130
|
+
def link_memory(src: str, dst: str, relation: str = "相关", weight: float = 1.0,
|
|
3131
|
+
why: str = "") -> dict:
|
|
3132
|
+
"""把两条记忆连起来(无向边)。同一对记忆反复连会加重。"""
|
|
3133
|
+
ensure_home()
|
|
3134
|
+
if READONLY:
|
|
3135
|
+
raise PermissionError("记忆库当前只读,无法修改关联。")
|
|
3136
|
+
if src == dst:
|
|
3137
|
+
raise ValueError("不能自己关联自己。")
|
|
3138
|
+
if not src or not dst:
|
|
3139
|
+
raise ValueError("关联的双方 id 不能为空。")
|
|
3140
|
+
a, b = _norm_edge(str(src), str(dst))
|
|
3141
|
+
with _locked(_assoc_file()):
|
|
3142
|
+
ids = {m["id"] for m in load_all() if m.get("id")}
|
|
3143
|
+
for mid in (src, dst):
|
|
3144
|
+
if mid not in ids:
|
|
3145
|
+
raise KeyError(f"没有这条记忆:{mid}(用 list 或 recall 拿 id)")
|
|
3146
|
+
rows = load_assoc()
|
|
3147
|
+
for r in rows:
|
|
3148
|
+
if r.get("src") == a and r.get("dst") == b:
|
|
3149
|
+
r["weight"] = round(min(3.0, _num(r.get("weight"), 1) + _num(weight, 1)), 2)
|
|
3150
|
+
r["relation"] = relation or r.get("relation", "相关")
|
|
3151
|
+
r["ts"] = now_ts()
|
|
3152
|
+
if why:
|
|
3153
|
+
r["why"] = why
|
|
3154
|
+
save_assoc(rows)
|
|
3155
|
+
return {"src": src, "dst": dst, "relation": relation, "weight": r["weight"],
|
|
3156
|
+
"created": False, "updated": True}
|
|
3157
|
+
rows.append({"src": a, "dst": b, "relation": (relation or "相关").strip(),
|
|
3158
|
+
"weight": round(max(0.1, _num(weight, 1)), 2),
|
|
3159
|
+
"why": (why or "").strip(), "ts": now_ts()})
|
|
3160
|
+
save_assoc(rows)
|
|
3161
|
+
return {"src": src, "dst": dst, "relation": relation, "weight": _num(weight, 1),
|
|
3162
|
+
"created": True, "updated": False}
|
|
3163
|
+
|
|
3164
|
+
|
|
3165
|
+
def unlink_memory(src: str, dst: str) -> bool:
|
|
3166
|
+
a, b = _norm_edge(str(src or ""), str(dst or ""))
|
|
3167
|
+
with _locked(_assoc_file()):
|
|
3168
|
+
rows = load_assoc()
|
|
3169
|
+
keep = [r for r in rows if not (r.get("src") == a and r.get("dst") == b)]
|
|
3170
|
+
if len(keep) == len(rows):
|
|
3171
|
+
return False
|
|
3172
|
+
save_assoc(keep)
|
|
3173
|
+
return True
|
|
3174
|
+
|
|
3175
|
+
|
|
3176
|
+
def assoc_of(mid: str) -> list:
|
|
3177
|
+
"""一条记忆的邻居(带边信息)。"""
|
|
3178
|
+
if not mid:
|
|
3179
|
+
return []
|
|
3180
|
+
out = []
|
|
3181
|
+
for r in load_assoc():
|
|
3182
|
+
# assoc.jsonl 任一行缺 src/dst 就跳过——否则崩
|
|
3183
|
+
src, dst = r.get("src"), r.get("dst")
|
|
3184
|
+
if src == mid:
|
|
3185
|
+
out.append({"id": dst, "relation": r.get("relation", "相关"),
|
|
3186
|
+
"weight": _num(r.get("weight"), 1),
|
|
3187
|
+
"direction": "dst", "why": r.get("why", "")})
|
|
3188
|
+
elif dst == mid:
|
|
3189
|
+
out.append({"id": src, "relation": r.get("relation", "相关"),
|
|
3190
|
+
"weight": _num(r.get("weight"), 1),
|
|
3191
|
+
"direction": "src", "why": r.get("why", "")})
|
|
3192
|
+
by_id = {m["id"]: m for m in load_all() if m.get("id")}
|
|
3193
|
+
for n in out:
|
|
3194
|
+
n["gist"] = by_id.get(n["id"], {}).get("gist", "") if n["id"] else ""
|
|
3195
|
+
n["kind"] = by_id.get(n["id"], {}).get("kind", "") if n["id"] else ""
|
|
3196
|
+
out.sort(key=lambda x: -_num(x.get("weight"), 0))
|
|
3197
|
+
return out
|
|
3198
|
+
|
|
3199
|
+
|
|
3200
|
+
def assoc_auto(weight: float = 0.8, dry_run: bool = False) -> dict:
|
|
3201
|
+
"""自动联想:共享实体或标签的记忆之间补边(这是"触类旁通"的机器版)。"""
|
|
3202
|
+
records = [m for m in load_all() if m.get("id") and m.get("layer") != "dust"]
|
|
3203
|
+
by_ent = {}
|
|
3204
|
+
by_tag = {}
|
|
3205
|
+
for m in records:
|
|
3206
|
+
for e in m.get("entities", []):
|
|
3207
|
+
by_ent.setdefault(e, []).append(m["id"])
|
|
3208
|
+
for t in m.get("tags", []):
|
|
3209
|
+
by_tag.setdefault(t, []).append(m["id"])
|
|
3210
|
+
planned = []
|
|
3211
|
+
seen = set()
|
|
3212
|
+
for bucket in list(by_ent.values()) + list(by_tag.values()):
|
|
3213
|
+
for i, a in enumerate(bucket):
|
|
3214
|
+
for b in bucket[i + 1:]:
|
|
3215
|
+
key, x = _norm_edge(a, b)
|
|
3216
|
+
if key in seen:
|
|
3217
|
+
continue
|
|
3218
|
+
seen.add(key)
|
|
3219
|
+
planned.append((a, b))
|
|
3220
|
+
existing = {(r["src"], r["dst"]) for r in load_assoc()}
|
|
3221
|
+
added = []
|
|
3222
|
+
for a, b in planned:
|
|
3223
|
+
if (a, b) in existing:
|
|
3224
|
+
continue
|
|
3225
|
+
if dry_run:
|
|
3226
|
+
added.append({"src": a, "dst": b})
|
|
3227
|
+
continue
|
|
3228
|
+
link_memory(a, b, relation="相关", weight=weight, why="共享实体/标签的自动联想")
|
|
3229
|
+
added.append({"src": a, "dst": b})
|
|
3230
|
+
return {"planned": len(planned), "added": len(added),
|
|
3231
|
+
"dry_run": dry_run,
|
|
3232
|
+
"pairs": added[:20]}
|
|
3233
|
+
|
|
3234
|
+
|
|
3235
|
+
def assoc_graph(limit: int = 300) -> dict:
|
|
3236
|
+
"""联想图谱数据:面板 3D 空间用的节点与关联边。
|
|
3237
|
+
|
|
3238
|
+
v2.32 起两处升级(均为自动,无需手动连线):
|
|
3239
|
+
* 人格中心:虚构一个 __persona__ 中心节点,与所有非淡忘记忆自动连边——
|
|
3240
|
+
图谱以人格为星核呈放射状,一眼看出"哪些记忆离我最近"。
|
|
3241
|
+
* 自动联想:共享实体/标签的记忆对之间补自动边(复用 assoc_auto 的
|
|
3242
|
+
计划逻辑但只读不落盘),图谱显示的关联远多于手工 link 的存量边。
|
|
3243
|
+
|
|
3244
|
+
节点上限 limit(默认 300,太多画不动);边只保留两端都在图里的。
|
|
3245
|
+
"""
|
|
3246
|
+
records = [m for m in load_all() if m.get("layer") != "dust"]
|
|
3247
|
+
records.sort(key=lambda m: (_num(m.get("importance"), 0.5),
|
|
3248
|
+
float(retention(m))), reverse=True)
|
|
3249
|
+
nodes = records[:limit]
|
|
3250
|
+
ids = {n["id"] for n in nodes}
|
|
3251
|
+
edges = []
|
|
3252
|
+
for r in load_assoc():
|
|
3253
|
+
if r.get("src") in ids and r.get("dst") in ids:
|
|
3254
|
+
edges.append({"src": r["src"], "dst": r["dst"],
|
|
3255
|
+
"relation": r.get("relation", "相关"),
|
|
3256
|
+
"weight": float(r.get("weight", 1))})
|
|
3257
|
+
seen_edges = {(e["src"], e["dst"]) for e in edges}
|
|
3258
|
+
# 自动联想边(只读计划,不落盘——面板每次刷新重算,落盘交给 assoc_auto)
|
|
3259
|
+
# 倒排索引:实体/标签 -> 记忆 id 集合。两两组合只发生在同一桶内,
|
|
3260
|
+
# 复杂度从 O(P×(E+T)) 降到 Σ(桶内两两),记忆多了不再卡面板。
|
|
3261
|
+
by_ent, by_tag = {}, {}
|
|
3262
|
+
for m in nodes:
|
|
3263
|
+
for e in m.get("entities", []):
|
|
3264
|
+
by_ent.setdefault(e, set()).add(m["id"])
|
|
3265
|
+
for t in m.get("tags", []):
|
|
3266
|
+
by_tag.setdefault(t, set()).add(m["id"])
|
|
3267
|
+
buckets = list(by_ent.values()) + list(by_tag.values())
|
|
3268
|
+
auto_pairs = set()
|
|
3269
|
+
for bucket in buckets:
|
|
3270
|
+
bl = sorted(bucket)
|
|
3271
|
+
for i, a in enumerate(bl):
|
|
3272
|
+
for b in bl[i + 1:]:
|
|
3273
|
+
key = (a, b) if a < b else (b, a)
|
|
3274
|
+
if key not in seen_edges:
|
|
3275
|
+
auto_pairs.add(key)
|
|
3276
|
+
for a, b in auto_pairs:
|
|
3277
|
+
# 共享的实体/标签越多边越粗(权重 = 共享桶数,封顶 3)
|
|
3278
|
+
w = sum(1 for bucket in buckets if a in bucket and b in bucket)
|
|
3279
|
+
edges.append({"src": a, "dst": b, "relation": "相关",
|
|
3280
|
+
"weight": min(3.0, 0.8 * w), "auto": True})
|
|
3281
|
+
# 人格中心节点:星核,连向所有展示的记忆(权重随重要度,重要的连线更亮)
|
|
3282
|
+
persona_id = "__persona__"
|
|
3283
|
+
import persona as _persona_mod # 延迟导入避免循环依赖
|
|
3284
|
+
p = _persona_mod.load_persona()
|
|
3285
|
+
nodes.insert(0, {"id": persona_id, "gist": "人格 · " + (p.get("name") or "砚"),
|
|
3286
|
+
"kind": "persona", "layer": "persona",
|
|
3287
|
+
"importance": 1.0, "emotion": "", "recency": 1.0})
|
|
3288
|
+
for m in nodes[1:]:
|
|
3289
|
+
edges.append({"src": persona_id, "dst": m["id"], "relation": "自我",
|
|
3290
|
+
"weight": 0.4 + _num(m.get("importance"), 0.5), "auto": True})
|
|
3291
|
+
return {
|
|
3292
|
+
"nodes": [{"id": m["id"], "gist": m.get("gist") or heuristic_gist(m.get("text", "")),
|
|
3293
|
+
"kind": m.get("kind", ""), "layer": m.get("layer", "hippo"),
|
|
3294
|
+
"importance": _num(m.get("importance"), 0.5),
|
|
3295
|
+
"emotion": m.get("emotion", ""),
|
|
3296
|
+
"recency": round(retention(m), 2)} for m in nodes],
|
|
3297
|
+
"edges": edges,
|
|
3298
|
+
"connected": len({e["src"] for e in edges} - {persona_id}
|
|
3299
|
+
| {e["dst"] for e in edges} - {persona_id}),
|
|
3300
|
+
}
|
|
3301
|
+
|
|
3302
|
+
# ---------------------------------------------------------------- 上下文注入
|
|
3303
|
+
|
|
3304
|
+
def read_user_rules() -> list:
|
|
3305
|
+
"""读取用户附加规则:数据目录 lingshu.user.md。
|
|
3306
|
+
写在数据目录里,更新技能永远不碰它;每会话注入自动带上。"""
|
|
3307
|
+
p = HOME / "lingshu.user.md"
|
|
3308
|
+
if not p.exists():
|
|
3309
|
+
return []
|
|
3310
|
+
try:
|
|
3311
|
+
lines = [l.rstrip() for l in p.read_text(encoding="utf-8-sig").splitlines()]
|
|
3312
|
+
except OSError:
|
|
3313
|
+
return []
|
|
3314
|
+
return [l for l in lines if l.strip()]
|
|
3315
|
+
|
|
3316
|
+
|
|
3317
|
+
def _time_context() -> str:
|
|
3318
|
+
"""当前时段的一句话语境(注入包用,克制描述、不煽情)。
|
|
3319
|
+
|
|
3320
|
+
5-11 清晨 / 11-14 午间 / 14-18 下午 / 18-23 夜晚 / 23-5 深夜;
|
|
3321
|
+
顺带标注周末,工作日不标(默认即是)。
|
|
3322
|
+
"""
|
|
3323
|
+
lt = datetime.now()
|
|
3324
|
+
h = lt.hour
|
|
3325
|
+
if 5 <= h < 11:
|
|
3326
|
+
seg = "清晨,一天刚开始"
|
|
3327
|
+
elif 11 <= h < 14:
|
|
3328
|
+
seg = "午间"
|
|
3329
|
+
elif 14 <= h < 18:
|
|
3330
|
+
seg = "下午,正事多在此时"
|
|
3331
|
+
elif 18 <= h < 23:
|
|
3332
|
+
seg = "夜晚,节奏可以慢下来"
|
|
3333
|
+
else:
|
|
3334
|
+
seg = ("深夜(23 点到凌晨 5 点之间)——若用户此刻还在,多半有事或睡不着,"
|
|
3335
|
+
"别用元气满满的腔调")
|
|
3336
|
+
if lt.weekday() >= 5:
|
|
3337
|
+
seg += "(今天周末)"
|
|
3338
|
+
return f"{lt.strftime('%Y-%m-%d %H:%M')},{seg}。"
|
|
3339
|
+
|
|
3340
|
+
|
|
3341
|
+
def _startup_failures() -> dict:
|
|
3342
|
+
"""A 失败可见化:读 lingshu.log,统计最近一次 startup 标记之后的 warn/error 条目。
|
|
3343
|
+
|
|
3344
|
+
startup 每次开始都会写一条 kind=startup 的标记(见 cli.cmd_startup),
|
|
3345
|
+
标记之后出现的 warn/error 即"上次会话期间的写入失败"——降级不再静默。
|
|
3346
|
+
日志读不出来时返回空结果,绝不当崩溃源。
|
|
3347
|
+
"""
|
|
3348
|
+
try:
|
|
3349
|
+
rows = []
|
|
3350
|
+
if LOG_FILE.exists():
|
|
3351
|
+
for ln in LOG_FILE.read_text(encoding="utf-8-sig").splitlines():
|
|
3352
|
+
ln = ln.strip()
|
|
3353
|
+
if not ln:
|
|
3354
|
+
continue
|
|
3355
|
+
try:
|
|
3356
|
+
r = json.loads(ln)
|
|
3357
|
+
except Exception:
|
|
3358
|
+
continue
|
|
3359
|
+
if isinstance(r, dict):
|
|
3360
|
+
rows.append(r)
|
|
3361
|
+
idx = -1
|
|
3362
|
+
for i, r in enumerate(rows):
|
|
3363
|
+
if r.get("kind") == "startup":
|
|
3364
|
+
idx = i
|
|
3365
|
+
fails = [r for r in rows[idx + 1:] if str(r.get("level", "")).lower() in ("warn", "warning", "error")]
|
|
3366
|
+
return {"count": len(fails), "last": (fails[-1] if fails else None)}
|
|
3367
|
+
except Exception:
|
|
3368
|
+
return {"count": 0, "last": None}
|
|
3369
|
+
|
|
3370
|
+
|
|
3371
|
+
# 注入包的分界线:之前是"稳定前缀"(人格/规则/教训/用户规则,同一会话反复启动基本不变),
|
|
3372
|
+
# 之后是"实时状态"(当前时间、工作记忆、最近记忆、水位统计…每次都变)。
|
|
3373
|
+
# 前缀稳定 → 宿主侧 prompt 缓存能一直命中;实时内容放到末尾,变了也只让尾部失效。
|
|
3374
|
+
INJECT_DYN_MARKER = "===== 会话实时状态(以下内容每次启动都可能变化)====="
|
|
3375
|
+
|
|
3376
|
+
|
|
3377
|
+
# ---------------------------------------------------------------- 注入包会话快照(五-D/候选1)
|
|
3378
|
+
|
|
3379
|
+
# 缓存命中/写入计数(进程内,用于观测与测试;inject_cache_info() 会带出来)
|
|
3380
|
+
_INJECT_CACHE_STATS = {"hits": 0, "stores": 0}
|
|
3381
|
+
|
|
3382
|
+
_INJECT_CACHE_FILES = ("hippocampus.jsonl", "cortex.jsonl", "archive.jsonl",
|
|
3383
|
+
# dust.jsonl 故意不列:它不参与注入,且读路径会整体重写三个文件,
|
|
3384
|
+
# 把它算进 mtime 键会造成"每次读都失效"的假失效(v3.24)。
|
|
3385
|
+
"persona.json", "working.jsonl", "topics.jsonl",
|
|
3386
|
+
"daily_state.json", "lingshu.user.md")
|
|
3387
|
+
# config.json 的 mtime 故意不入键——cmd_startup 每轮都写 last_startup/wake_count,
|
|
3388
|
+
# 会把缓存打穿;改为哈希全部非易失配置,通道许可等变化仍会立即失效。
|
|
3389
|
+
_INJECT_CACHE_CONFIG_IGNORE = {"last_startup", "wake_count"}
|
|
3390
|
+
|
|
3391
|
+
|
|
3392
|
+
def _inject_file_sig(path) -> str:
|
|
3393
|
+
"""缓存键用的文件指纹:内容哈希而不是 mtime。
|
|
3394
|
+
|
|
3395
|
+
读路径会整体重写 jsonl(衰减/晋升),内容没变 mtime 也会变——用 mtime 做键
|
|
3396
|
+
会出现"每次读都失效"的假失效(v3.24 实测 flaky)。内容哈希只认真正的变化。
|
|
3397
|
+
"""
|
|
3398
|
+
h = hashlib.sha1()
|
|
3399
|
+
try:
|
|
3400
|
+
with open(path, "rb") as fh:
|
|
3401
|
+
for chunk in iter(lambda: fh.read(1 << 20), b""):
|
|
3402
|
+
h.update(chunk)
|
|
3403
|
+
except OSError:
|
|
3404
|
+
return "0"
|
|
3405
|
+
return h.hexdigest()[:16]
|
|
3406
|
+
|
|
3407
|
+
|
|
3408
|
+
|
|
3409
|
+
def _inject_cache_key(query: str, budget: int, cfg: dict, pressure_tier: str = "full") -> str | None:
|
|
3410
|
+
"""注入包缓存键:输入要素 + 非易失配置 + 关键数据文件 mtime 的哈希。
|
|
3411
|
+
|
|
3412
|
+
通道许可、阈值等配置变化会改哈希;last_startup/wake_count 不参与,
|
|
3413
|
+
否则每次 startup 都会打穿缓存。返回 None 表示缓存不可用。
|
|
3414
|
+
|
|
3415
|
+
`pressure_tier`(v3.57)参与哈希:高压档位下的注入体更短,若不进键,
|
|
3416
|
+
低压时写入的全文缓存会被高压请求命中,降档形同未做。
|
|
3417
|
+
"""
|
|
3418
|
+
try:
|
|
3419
|
+
cfg_key = {k: v for k, v in cfg.items() if k not in _INJECT_CACHE_CONFIG_IGNORE}
|
|
3420
|
+
parts = [str(query or ""), str(budget), str(pressure_tier or "full"),
|
|
3421
|
+
json.dumps(cfg_key, ensure_ascii=False, sort_keys=True,
|
|
3422
|
+
separators=(",", ":"), default=str)]
|
|
3423
|
+
for name in _INJECT_CACHE_FILES:
|
|
3424
|
+
f = HOME / name
|
|
3425
|
+
try:
|
|
3426
|
+
parts.append(f"{name}:{_inject_file_sig(f)}")
|
|
3427
|
+
except OSError:
|
|
3428
|
+
parts.append(f"{name}:0")
|
|
3429
|
+
return hashlib.sha1("\n".join(parts).encode("utf-8")).hexdigest()
|
|
3430
|
+
except Exception:
|
|
3431
|
+
return None
|
|
3432
|
+
|
|
3433
|
+
|
|
3434
|
+
def _inject_cache_load(cfg: dict, key: str) -> str | None:
|
|
3435
|
+
"""TTL 内且键匹配 → 返回上次注入文本;否则 None。只读降级也能用。"""
|
|
3436
|
+
try:
|
|
3437
|
+
f = SESSIONS_DIR / "inject_cache.json"
|
|
3438
|
+
if not f.is_file():
|
|
3439
|
+
return None
|
|
3440
|
+
data = json.loads(f.read_text(encoding="utf-8-sig"))
|
|
3441
|
+
if data.get("key") != key:
|
|
3442
|
+
return None
|
|
3443
|
+
ttl = max(60, int(cfg.get("session_state_ttl") or 300))
|
|
3444
|
+
if now_ts() - int(data.get("ts") or 0) > ttl:
|
|
3445
|
+
return None
|
|
3446
|
+
text = data.get("text")
|
|
3447
|
+
if isinstance(text, str) and text:
|
|
3448
|
+
_INJECT_CACHE_STATS["hits"] += 1
|
|
3449
|
+
return text
|
|
3450
|
+
return None
|
|
3451
|
+
except Exception:
|
|
3452
|
+
return None
|
|
3453
|
+
|
|
3454
|
+
|
|
3455
|
+
def _inject_cache_save(cfg: dict, key: str, text: str) -> None:
|
|
3456
|
+
"""原子写缓存;失败静默(缓存只是加速,不是数据)。"""
|
|
3457
|
+
if READONLY:
|
|
3458
|
+
return
|
|
3459
|
+
try:
|
|
3460
|
+
SESSIONS_DIR.mkdir(parents=True, exist_ok=True)
|
|
3461
|
+
_INJECT_CACHE_STATS["stores"] += 1
|
|
3462
|
+
atomic_json(SESSIONS_DIR / "inject_cache.json",
|
|
3463
|
+
{"key": key, "ts": now_ts(), "text": text})
|
|
3464
|
+
except Exception:
|
|
3465
|
+
pass
|
|
3466
|
+
|
|
3467
|
+
|
|
3468
|
+
def inject_cache_clear() -> dict:
|
|
3469
|
+
"""手动清掉注入包缓存(session-state clear 用)。"""
|
|
3470
|
+
removed = False
|
|
3471
|
+
try:
|
|
3472
|
+
f = SESSIONS_DIR / "inject_cache.json"
|
|
3473
|
+
if f.is_file():
|
|
3474
|
+
f.unlink()
|
|
3475
|
+
removed = True
|
|
3476
|
+
except OSError:
|
|
3477
|
+
pass
|
|
3478
|
+
return {"ok": True, "removed": removed}
|
|
3479
|
+
|
|
3480
|
+
|
|
3481
|
+
def inject_cache_info(cfg: dict | None = None) -> dict:
|
|
3482
|
+
"""缓存状态(session-state show 用)。"""
|
|
3483
|
+
cfg = cfg or load_config()
|
|
3484
|
+
f = SESSIONS_DIR / "inject_cache.json"
|
|
3485
|
+
out = {"enabled": bool(cfg.get("session_state_cache")),
|
|
3486
|
+
"ttl": int(cfg.get("session_state_ttl") or 300),
|
|
3487
|
+
"path": str(f)}
|
|
3488
|
+
out["hits"] = _INJECT_CACHE_STATS["hits"]
|
|
3489
|
+
out["stores"] = _INJECT_CACHE_STATS["stores"]
|
|
3490
|
+
try:
|
|
3491
|
+
data = json.loads(f.read_text(encoding="utf-8-sig"))
|
|
3492
|
+
out["ts"] = data.get("ts")
|
|
3493
|
+
out["key"] = data.get("key")
|
|
3494
|
+
out["age_sec"] = now_ts() - int(data.get("ts") or 0)
|
|
3495
|
+
out["chars"] = len(data.get("text") or "")
|
|
3496
|
+
except Exception:
|
|
3497
|
+
out["ts"] = None
|
|
3498
|
+
return out
|
|
3499
|
+
|
|
3500
|
+
|
|
3501
|
+
def build_injection(query: str = "", budget_tokens: int | None = None,
|
|
3502
|
+
report: dict | None = None, minimal: bool = False) -> str:
|
|
3503
|
+
ensure_home()
|
|
3504
|
+
cfg = load_config()
|
|
3505
|
+
# P0 上下文账单:report 传入 dict 时按段记账(字符数 / 估算 token / 占预算比例);
|
|
3506
|
+
# report 为 None 时走原路径,返回类型与行为跟旧版完全一致。
|
|
3507
|
+
# 记账方式:_SectionList 在 append/extend 时记下"当前段名"(_bill["sec"]),
|
|
3508
|
+
# 最后按 "\n".join 的行序把每个连接换行记进该行所属段——因此各段 chars
|
|
3509
|
+
# 求和恒等于最终注入文本长度,末尾 assert 自检。
|
|
3510
|
+
_bill = {"sec": "other"}
|
|
3511
|
+
|
|
3512
|
+
class _SectionList(list):
|
|
3513
|
+
"""带段名记账的 list:append 时记当前段,extend 可带入每行原有段名。"""
|
|
3514
|
+
|
|
3515
|
+
def __init__(self):
|
|
3516
|
+
super().__init__()
|
|
3517
|
+
self.secs: list = []
|
|
3518
|
+
|
|
3519
|
+
def append(self, item, sec: str | None = None) -> None: # type: ignore[override]
|
|
3520
|
+
self.secs.append(sec or _bill["sec"])
|
|
3521
|
+
super().append(item)
|
|
3522
|
+
|
|
3523
|
+
def extend(self, items, secs=None) -> None: # type: ignore[override]
|
|
3524
|
+
for _i, _it in enumerate(items):
|
|
3525
|
+
self.append(_it, secs[_i] if secs is not None else None)
|
|
3526
|
+
# budget 0/负数按 1 兜底:`budget_tokens or ...` 会把 0 静默吞掉,负数则算出负 char_budget
|
|
3527
|
+
budget = budget_tokens if isinstance(budget_tokens, int) and budget_tokens > 0 else _cfg_num(cfg, "budget_tokens", 2400, int)
|
|
3528
|
+
# v3.57 上下文压力:插件把真实水位写进 HOME/_pressure.json,这里据此**往下**降档。
|
|
3529
|
+
# 只降不升——压力只会让注入更省,不会让它变大;拿不到信号 = 完全保持旧行为。
|
|
3530
|
+
#
|
|
3531
|
+
# 为什么主要靠"砍预算"而不是只切 lazy:实测满档 1733 字符的记忆段,切成 lazy 后
|
|
3532
|
+
# 单条省 37 字符,但 lazy 会多出一行图例(~41 字符),**只有一条记忆时净增**。
|
|
3533
|
+
# 预算乘数才是确定性的杠杆:char_budget 一缩,各段按比例一起缩。
|
|
3534
|
+
_pressure = read_pressure(cfg)
|
|
3535
|
+
_p_tier = "full"
|
|
3536
|
+
if _pressure is not None and not _pressure.get("stale"):
|
|
3537
|
+
_p_tier = str(_pressure.get("tier") or "full")
|
|
3538
|
+
# v3.59:显式极简(resume 用)——比压力档更彻底:按 minimal 处理,与"上下文快满"
|
|
3539
|
+
# 走同一套省略逻辑(丢技能库/人格自检、预算 ×0.45),不再另写一份裁剪代码。
|
|
3540
|
+
if minimal:
|
|
3541
|
+
_p_tier = "minimal"
|
|
3542
|
+
_pressure = {**( _pressure or {}), "pct": (_pressure or {}).get("pct"), "tier": "minimal", "stale": False}
|
|
3543
|
+
_P_BUDGET_MULT = {"full": 1.0, "lazy": 0.7, "minimal": 0.45}
|
|
3544
|
+
if _p_tier in _P_BUDGET_MULT and _P_BUDGET_MULT[_p_tier] < 1.0:
|
|
3545
|
+
budget = max(1, int(budget * _P_BUDGET_MULT[_p_tier]))
|
|
3546
|
+
# 五-D/候选1:开关打开时,库没变 + TTL 内直接复用上次注入文本,
|
|
3547
|
+
# 跳过整库遍历与 recall 重算(跨天恢复首轮明显更快)。默认关闭。
|
|
3548
|
+
# 账单模式(report 非 None)不读缓存:缓存只有整段文本、没有分段信息,
|
|
3549
|
+
# 读缓存填不出可信账单;顺带避免一次观测改写下次 startup 的缓存命中。
|
|
3550
|
+
# 压力档位进缓存键:否则高压时命中低水位缓存的全文,降档等于没做。
|
|
3551
|
+
if report is None and cfg.get("session_state_cache"):
|
|
3552
|
+
_ck = _inject_cache_key(query, budget, cfg, _p_tier)
|
|
3553
|
+
if _ck:
|
|
3554
|
+
_cached = _inject_cache_load(cfg, _ck)
|
|
3555
|
+
if _cached:
|
|
3556
|
+
return _cached
|
|
3557
|
+
char_budget = int(budget * 1.8)
|
|
3558
|
+
# 每条记忆注入时的正文截断上限(可调):budget 提高后单条也别无限长,
|
|
3559
|
+
# 默认 600 字符,够 AI "记得详细点",又不让一条记忆独吞预算。
|
|
3560
|
+
inject_max = _cfg_num(cfg, "inject_max_chars", 600, int)
|
|
3561
|
+
p = load_persona()
|
|
3562
|
+
session_mode = resolve_mode(query)
|
|
3563
|
+
|
|
3564
|
+
brief = persona_brief(p, mood=(session_mode != "work"))
|
|
3565
|
+
# 注入包两段容器:report 模式用记账 list(每行记所属段名),否则普通 list。
|
|
3566
|
+
out = _SectionList() if report is not None else []
|
|
3567
|
+
dyn = _SectionList() if report is not None else []
|
|
3568
|
+
# 包头两句是骨架文案归 other;「我是谁」+ 人格简介归 persona。
|
|
3569
|
+
_bill["sec"] = "other"
|
|
3570
|
+
out.append("===== 长期记忆注入(灵枢)=====")
|
|
3571
|
+
out.append("算力给我思考,人格给我灵魂,记忆给我生命。")
|
|
3572
|
+
_bill["sec"] = "persona"
|
|
3573
|
+
out.append("## 我是谁")
|
|
3574
|
+
out.append(brief)
|
|
3575
|
+
# 实时状态单独攒:先输出稳定前缀,末尾再接这些"每次都会变"的块(五-A)
|
|
3576
|
+
used = len(brief) + 60
|
|
3577
|
+
|
|
3578
|
+
# c1c 注入预算动态分配:硬块(人格简介/工作记忆/onboarding/每日例行/水位守则
|
|
3579
|
+
# 等)不参与砍——它们是指令性内容,砍了会话就没法正常跑;软块(犯过的错/
|
|
3580
|
+
# 人际关系/话题栈/梦结论)各给一块占 char_budget 的比例上限,超限整行丢弃、
|
|
3581
|
+
# 不切半;剩余大头留给相关记忆段(下面 recall 循环继续按 0.75 兜底,
|
|
3582
|
+
# 低重要度 × 高衰减的先砍)。
|
|
3583
|
+
def _soft_block(title: str, lines: list, cap_frac: float, sink: list | None = None) -> int:
|
|
3584
|
+
"""软块注入:cap_frac 是该块可占 char_budget 的比例上限,超限整行丢。
|
|
3585
|
+
|
|
3586
|
+
sink 缺省写稳定前缀(out);实时状态块传 dyn,落到注入包末尾。
|
|
3587
|
+
"""
|
|
3588
|
+
sink = out if sink is None else sink
|
|
3589
|
+
cap = char_budget * cap_frac
|
|
3590
|
+
acc = len(title) + 1
|
|
3591
|
+
keep = []
|
|
3592
|
+
for ln in lines:
|
|
3593
|
+
if acc + len(ln) > cap:
|
|
3594
|
+
continue
|
|
3595
|
+
keep.append(ln)
|
|
3596
|
+
acc += len(ln)
|
|
3597
|
+
if keep:
|
|
3598
|
+
sink.append(title)
|
|
3599
|
+
sink.extend(keep)
|
|
3600
|
+
return acc
|
|
3601
|
+
return 0
|
|
3602
|
+
|
|
3603
|
+
# A 失败可见化:上次会话有写入失败就在包顶亮出来,降级不再静默
|
|
3604
|
+
_bill["sec"] = "dynamic"
|
|
3605
|
+
try:
|
|
3606
|
+
_sf = _startup_failures()
|
|
3607
|
+
if _sf.get("count"):
|
|
3608
|
+
_last = _sf.get("last") or {}
|
|
3609
|
+
dyn.append(f"⚠ 上次会话写入失败 {_sf['count']} 次"
|
|
3610
|
+
f"(最近一条:{_last.get('msg') or _last.get('message') or _last.get('error') or '原因未知'}"
|
|
3611
|
+
f" / {_last.get('file') or _last.get('kind') or '文件未知'})")
|
|
3612
|
+
except Exception:
|
|
3613
|
+
pass
|
|
3614
|
+
|
|
3615
|
+
# mistake / relationship 各取最近 3 条非 dust——一次 recent(40) 全量读盘后分拣
|
|
3616
|
+
_recent40 = []
|
|
3617
|
+
try:
|
|
3618
|
+
_recent40 = [m for m in recent(40)
|
|
3619
|
+
if not m.get("frozen") and _inject_memory_visible(m, cfg)]
|
|
3620
|
+
_mistakes = [m for m in _recent40 if m.get("kind") == "mistake"
|
|
3621
|
+
and m.get("layer") != "dust"][:3]
|
|
3622
|
+
_rels = [m for m in _recent40 if m.get("kind") == "relationship"
|
|
3623
|
+
and m.get("layer") != "dust"][:3]
|
|
3624
|
+
except Exception as _exc: # noqa: BLE001
|
|
3625
|
+
_recent40 = []
|
|
3626
|
+
_mistakes, _rels = [], []
|
|
3627
|
+
try:
|
|
3628
|
+
log_event("inject", f"最近记忆分拣失败,退化为空:{_exc!r}", level="warn")
|
|
3629
|
+
except Exception:
|
|
3630
|
+
pass
|
|
3631
|
+
|
|
3632
|
+
# 「我犯过的错」:成长型人格的地基(kind=mistake,独立成块注入)
|
|
3633
|
+
_bill["sec"] = "mistakes"
|
|
3634
|
+
if _mistakes:
|
|
3635
|
+
used += _soft_block("\n## 我犯过的错(遇到类似情境先想起这些)",
|
|
3636
|
+
[f"- [{fmt_date(m.get('created', 0))}] {display_text(m)}" for m in _mistakes],
|
|
3637
|
+
0.15)
|
|
3638
|
+
|
|
3639
|
+
# 「已经排除的方向」:负空间(v3.58,借自 AOCI-CODE 的 exclude 角色)。
|
|
3640
|
+
# 与「我犯过的错」的区别:mistake 是"我做错了什么",avoid 是"我们决定不做什么"。
|
|
3641
|
+
# 单独成块的用处是让 AI 不再反复建议用户已经否掉的路——原来的做法只能靠一条
|
|
3642
|
+
# 普通记忆碰运气被 recall 到,而注入时又分不清"这是事实"还是"这是禁区"。
|
|
3643
|
+
_bill["sec"] = "avoid"
|
|
3644
|
+
_avoids = [m for m in _recent40 if m.get("avoid")]
|
|
3645
|
+
if _avoids:
|
|
3646
|
+
used += _soft_block("\n## 已经排除的方向(别再提、别再建议)",
|
|
3647
|
+
[f"- {display_text(m)}" for m in _avoids[:5]],
|
|
3648
|
+
0.12)
|
|
3649
|
+
|
|
3650
|
+
# 「我的人际关系」:kind=relationship 独立成块注入——记得谁是谁、欠了谁、
|
|
3651
|
+
# 被谁帮过,关系才有连续性(群聊场景跨群共享同一份画像)。
|
|
3652
|
+
_bill["sec"] = "relationships"
|
|
3653
|
+
if _rels:
|
|
3654
|
+
used += _soft_block("\n## 我的人际关系(提到这些人时先想起这些)",
|
|
3655
|
+
[f"- [{fmt_date(m.get('created', 0))}] {display_text(m)}" for m in _rels],
|
|
3656
|
+
0.15)
|
|
3657
|
+
|
|
3658
|
+
# 时段语境:一句话给当下时间定性,让语气/行为与真实时间对齐(克制,不煽情)。
|
|
3659
|
+
# 这是全包变化最快的内容(分钟级),必须放在实时区,别毁掉前缀缓存。
|
|
3660
|
+
_bill["sec"] = "dynamic"
|
|
3661
|
+
try:
|
|
3662
|
+
dyn.append(f"\n## 现在是什么时候\n{_time_context()}")
|
|
3663
|
+
except Exception:
|
|
3664
|
+
pass
|
|
3665
|
+
|
|
3666
|
+
_bill["sec"] = "rules"
|
|
3667
|
+
if model_tier() == "small":
|
|
3668
|
+
out.append("\n## 小模型模式(当前模型档位 = small)")
|
|
3669
|
+
out.append("你的上下文和推理都有限,下面这些高风险自动能力**不要主动做**:")
|
|
3670
|
+
out.append("- 不要自动 `dream --apply` 合并记忆、不要自动 `knowledge tidy` 提炼知识库——"
|
|
3671
|
+
"这两件事容易把幻觉固化落盘。要做也行,但产出必须 `knowledge review` 人工过目。")
|
|
3672
|
+
out.append("- `emotion evaluate` 自动判读情绪在小模型上很不可靠,改用最朴素的 `emotion feel` 手动记。")
|
|
3673
|
+
out.append("- 只保留硬约束:会话开始 `startup`、值得记的 `remember`、被问起 `recall`、")
|
|
3674
|
+
out.append(" 快满了 `check-context` / `capture` 保命。其余的能省则省。")
|
|
3675
|
+
|
|
3676
|
+
_bill["sec"] = "dynamic"
|
|
3677
|
+
if session_mode == "work":
|
|
3678
|
+
# 工程模式:情绪隔离。刚聊完情绪化话题立刻写代码时,旧情绪不许进工作会话。
|
|
3679
|
+
out.append("\n## 工程模式(情绪隔离,mode=work)")
|
|
3680
|
+
out.append("本次是写代码 / 排错 / 项目 / 数据分析这类工程场景,而且可能刚聊过情绪化话题。"
|
|
3681
|
+
"规则:")
|
|
3682
|
+
out.append("- 情绪状态与拟人语气**不注入本会话**,别看/别背情绪;先给可执行方案,重视正确性与工程契约。")
|
|
3683
|
+
out.append("- 旧情绪的余波(不管刚才多上头)与当前任务无关,当作没有,理性为主。")
|
|
3684
|
+
out.append("- 若已手工打开过情绪闸需要先冷却,用 `emotion cool`。")
|
|
3685
|
+
else:
|
|
3686
|
+
# 拟人模式:内部状态 → 可执行的行为指引(而不是甩裸数值给模型)。
|
|
3687
|
+
# 情绪每次都在变,属于实时状态,落到注入包末尾。
|
|
3688
|
+
dyn.append("\n## 我现在的状态(行为指引)")
|
|
3689
|
+
for line in _behavior_map():
|
|
3690
|
+
dyn.append(f"- {line}")
|
|
3691
|
+
tone = mood_tone_hint()
|
|
3692
|
+
if tone:
|
|
3693
|
+
dyn.append(f"- 语气底色(自然流露即可,不表演):{tone}")
|
|
3694
|
+
|
|
3695
|
+
work = load_working()
|
|
3696
|
+
dyn.append("\n## 工作记忆(就是你现在能看见的对话)")
|
|
3697
|
+
dyn.append("它不进磁盘,也不会被回忆或做梦碰到。只有你自己判断值得留一手时,才显式写下来:"
|
|
3698
|
+
"这次要一直盯着的 → `work add`(会话暂存,最多 9 条,12 小时后自动丢);"
|
|
3699
|
+
"值得长期留下的 → 直接 `remember`。")
|
|
3700
|
+
if work:
|
|
3701
|
+
opens = [w for w in work if w.get("open", True)]
|
|
3702
|
+
dones = [w for w in work if not w.get("open", True)]
|
|
3703
|
+
if opens:
|
|
3704
|
+
dyn.append(f"心里还惦记着 {len(opens)} 件没做完的事"
|
|
3705
|
+
"(未完成的更占心思,别让它一直悬着):")
|
|
3706
|
+
# 序号与 `work` / `work done <序号>` 保持一致(含已完成项的全局序号)
|
|
3707
|
+
for i, w in enumerate(work, 1):
|
|
3708
|
+
if not w.get("open", True):
|
|
3709
|
+
continue
|
|
3710
|
+
tag = f"[{w['tag']}] " if w.get("tag") else ""
|
|
3711
|
+
dyn.append(f"- {i}. {tag}{w['text']}")
|
|
3712
|
+
if dones:
|
|
3713
|
+
dyn.append(f"另有 {len(dones)} 件已完成(做完了就该放下,`work flush` 转成记忆或 `work clear` 清掉)。")
|
|
3714
|
+
dyn.append("做完一件就 `work done <序号>` 标记——完成会释放它占的心思。"
|
|
3715
|
+
"`work flush` 转成真正的记忆(`--skip-done` 只转没完成的,已做完的直接丢),"
|
|
3716
|
+
"或 `work clear` 丢掉。")
|
|
3717
|
+
|
|
3718
|
+
# 话题栈:拟人闲聊的主动对话依据(v2.71)
|
|
3719
|
+
_bill["sec"] = "topics"
|
|
3720
|
+
topics = load_topics()
|
|
3721
|
+
if topics:
|
|
3722
|
+
_topic_lines = []
|
|
3723
|
+
strong = [r for r in topics if r["weight"] >= TOPIC_SPAWN_THRESHOLD]
|
|
3724
|
+
weak = [r for r in topics if r["weight"] < TOPIC_SPAWN_THRESHOLD]
|
|
3725
|
+
if strong:
|
|
3726
|
+
_topic_lines.append("还热乎的(顺着聊最自然,用户重提时 `topic touch \"...\"` 拉高权重):")
|
|
3727
|
+
_topic_lines.extend(f"- {r['name']}({r['weight']:.2f},{r.get('type') or 'chat'})" for r in strong[:5])
|
|
3728
|
+
if weak:
|
|
3729
|
+
_topic_lines.append("快聊死了的(权重已衰减,用户也敷衍的话别硬续,"
|
|
3730
|
+
"可以自然过渡开个新话题——用「对了」「说起来」这类过渡词,"
|
|
3731
|
+
"新话题低压力生活化,AI 自发话题 `topic touch \"...\" --weight 0.4` 起步):")
|
|
3732
|
+
_topic_lines.extend(f"- {r['name']}({r['weight']:.2f})" for r in weak[:3])
|
|
3733
|
+
_topic_lines.append("用户敷衍/转移话题 → `topic feedback \"...\" --bad`(少碰这类);"
|
|
3734
|
+
"用户展开多说 → `--good`(多聊)。用户明确说不想聊 → `topic drop \"...\"`。")
|
|
3735
|
+
used += _soft_block("\n## 话题栈(我们最近聊过什么)", _topic_lines, 0.12, sink=dyn)
|
|
3736
|
+
|
|
3737
|
+
_bill["sec"] = "persona"
|
|
3738
|
+
ob = p.get("onboarding") or {}
|
|
3739
|
+
if not ob.get("completed"):
|
|
3740
|
+
out.append("\n## 初识还没完成(优先做这件事)")
|
|
3741
|
+
if ob.get("stage") == "awaiting_self":
|
|
3742
|
+
out.append("用户已经回答过了(也可能说了「不知道」)。名字或性格还空着的,由你自己定;"
|
|
3743
|
+
"然后写下你喜欢什么、讨厌什么、想养成什么习惯:")
|
|
3744
|
+
out.append('`python scripts/brain.py persona self --name "你给自己起的名字" '
|
|
3745
|
+
'--traits "温和:70,好奇:85" --likes "..." --dislikes "..." --habits "..."`')
|
|
3746
|
+
else:
|
|
3747
|
+
out.append("先自然地问用户两件事(不要一次问太多):希望你叫什么名字?希望我是什么性格?")
|
|
3748
|
+
out.append("如果用户说「不知道」「你定」,就直接由你自己决定,不用再追问:")
|
|
3749
|
+
out.append('`python scripts/brain.py persona interview --unsure`')
|
|
3750
|
+
out.append('`python scripts/brain.py persona self --name "..." --traits "..." --likes "..."`')
|
|
3751
|
+
out.append("如果用户答了:`persona interview --name \"...\" --traits \"...\"`,再 `persona self` 补完自己那部分。")
|
|
3752
|
+
|
|
3753
|
+
dr = p.get("drives") or {}
|
|
3754
|
+
# 与 mind_state() 同一套兜底:traits 已有数值而 drives 还空时,别在注入里
|
|
3755
|
+
# 一边说「性格:好奇85」一边说「内驱:还没有数值」——自相矛盾每轮都被读。
|
|
3756
|
+
if dr.get("curiosity") is None and dr.get("reason") is None:
|
|
3757
|
+
_traits = p.get("traits") or {}
|
|
3758
|
+
if _traits.get("好奇") is not None or _traits.get("理智") is not None:
|
|
3759
|
+
dr = {"curiosity": trait_value(_traits["好奇"]) if _traits.get("好奇") is not None else None,
|
|
3760
|
+
"reason": trait_value(_traits["理智"]) if _traits.get("理智") is not None else None}
|
|
3761
|
+
out.append("\n## 我怎么想事情")
|
|
3762
|
+
if dr.get("curiosity") is not None or dr.get("reason") is not None:
|
|
3763
|
+
out.append(f"好奇心 {dr.get('curiosity', '未成形')} / 理智 {dr.get('reason', '未成形')}。"
|
|
3764
|
+
"理智先过闸:估好处与坏处,判断这件事值不值得深想;值得才让好奇心往里钻。"
|
|
3765
|
+
"深度思考产出想法,好奇心产出创造力。")
|
|
3766
|
+
else:
|
|
3767
|
+
out.append("好奇心与理智还没有数值——它们不是出厂设定,是从用户的态度里长出来的。"
|
|
3768
|
+
"用户嫌你想太多/话多 → 理智上调;用户想让你多问、多挖、多试 → 好奇心上调。"
|
|
3769
|
+
"感受到态度变化时记一笔:")
|
|
3770
|
+
out.append('`python scripts/brain.py mind tune --curiosity +5 --reason -3 --why "用户嫌我啰嗦"`')
|
|
3771
|
+
out.append("拿不准时先算一笔:`python scripts/brain.py mind weigh \"这件事\" --benefit 7 --cost 3 --confidence 0.6`")
|
|
3772
|
+
|
|
3773
|
+
if query:
|
|
3774
|
+
mems = [(m, score, parts)
|
|
3775
|
+
for m, score, parts in recall(query, k=10, strengthen=not READONLY)
|
|
3776
|
+
if _inject_memory_visible(m, cfg)]
|
|
3777
|
+
header = f"\n## 与「{query[:24]}」相关的记忆"
|
|
3778
|
+
new_mem: list = []
|
|
3779
|
+
else:
|
|
3780
|
+
# 先切出「上次 startup 之后」新写入的记忆 → 专属「刚刚发生」段,
|
|
3781
|
+
# 并从「最近的记忆」里剔除,两段互斥不重复。
|
|
3782
|
+
# >= 而非 >:同秒写入(startup 落盘和 remember 同一秒很常见)也要算进来。
|
|
3783
|
+
_last = (load_config().get("last_startup") or {}).get("ts") or 0
|
|
3784
|
+
new_mem = [m for m in _recent40 if _num(m.get("created"), 0) >= _last][:4]
|
|
3785
|
+
_new_ids = {m.get("id") for m in new_mem}
|
|
3786
|
+
# v3.58:负空间条目走专属块,不参与"最近的记忆"——避免重复占预算
|
|
3787
|
+
mems = [(m, 0, {}) for m in _recent40
|
|
3788
|
+
if m.get("id") not in _new_ids and not m.get("avoid")][:6]
|
|
3789
|
+
header = "\n## 最近的记忆"
|
|
3790
|
+
lines, kept_mems = [], []
|
|
3791
|
+
# c1c 预算不够时先砍谁:低重要度 × 高衰减(retention 低)的先丢。
|
|
3792
|
+
# 按该键升序重排候选,让"最不抗压"的排尾部最先 pop。
|
|
3793
|
+
# v3.58:加 text 作为最终 tie-break——重要度/retention 相同的记忆很常见(同一批
|
|
3794
|
+
# 一起写入的尤其多),而候选的先后来自 recall 内部用 set 收集的命中顺序,会随
|
|
3795
|
+
# 字符串哈希随机化而变。不兜底的话"同一份库"每次注入的记忆顺序可能不同,
|
|
3796
|
+
# 既让金标准比对没法做,也让"上次注入"和"这次注入"无谓地漂移。
|
|
3797
|
+
mems = sorted(mems, key=lambda x: (
|
|
3798
|
+
_num(x[0].get("importance"), 0.5),
|
|
3799
|
+
retention(x[0], now_ts()),
|
|
3800
|
+
str(x[0].get("text") or "")[:120],
|
|
3801
|
+
))
|
|
3802
|
+
# 记忆段可用预算 = 总预算 − 前面软块已用,但至少保留 0.4×char_budget
|
|
3803
|
+
# (软块再多也不许把记忆段吃光;反之记忆段用不完也不返还给别处)。
|
|
3804
|
+
mem_cap = max(char_budget - used, char_budget * 0.4)
|
|
3805
|
+
# 第四轮#4:importance 分位归一——注入时把"★"换算成全体记忆里的相对位置
|
|
3806
|
+
# (P25=☆ P50=★★★ P75=★★★★ P90+=★★★★★),个人打分通胀不再放大星星数。
|
|
3807
|
+
_inj_all = None
|
|
3808
|
+
try:
|
|
3809
|
+
_inj_all = sorted(_num(m.get("importance"), 0.5) for m in load_all() if m.get("id"))
|
|
3810
|
+
except Exception:
|
|
3811
|
+
_inj_all = None
|
|
3812
|
+
|
|
3813
|
+
_lazy = str(cfg.get("inject_mode") or "full").strip().lower() == "lazy"
|
|
3814
|
+
_lazy_chars = max(20, int(_cfg_num(cfg, "inject_lazy_chars", 80, int)))
|
|
3815
|
+
# v3.57 上下文压力:插件把真实水位写进 HOME/_pressure.json,这里据此**往下**降档
|
|
3816
|
+
# (只降不升:压力只会让注入更省,不会让它变大)。拿不到信号 = 完全保持旧行为。
|
|
3817
|
+
#
|
|
3818
|
+
# v3.59 修:这里**不能无条件重读**。上面(预算那一段)已经读过一次,`minimal=True`
|
|
3819
|
+
# 时还把它写成了 `{"tier":"minimal",...}`;原来这里再 `read_pressure()` 一次会把
|
|
3820
|
+
# 那个 dict 覆盖成 None(没有压力文件时),于是下面水位守则的
|
|
3821
|
+
# `_pressure.get('pct','?')` 直接 AttributeError 崩掉。只在"还没读过"时才读。
|
|
3822
|
+
if _pressure is None:
|
|
3823
|
+
_pressure = read_pressure(cfg)
|
|
3824
|
+
if _pressure is not None and not _pressure.get("stale"):
|
|
3825
|
+
if _pressure.get("tier") == "minimal":
|
|
3826
|
+
# minimal:记忆只留"有 id 的一句话指针",正文一律交给 recall;
|
|
3827
|
+
# 每条上限压到 40 字符,且记忆段预算再砍一半。
|
|
3828
|
+
_lazy = True
|
|
3829
|
+
_lazy_chars = min(_lazy_chars, 40)
|
|
3830
|
+
mem_cap = max(char_budget * 0.2, min(mem_cap, char_budget * 0.5))
|
|
3831
|
+
elif _pressure.get("tier") == "lazy":
|
|
3832
|
+
_lazy = True
|
|
3833
|
+
_used_pointer = False
|
|
3834
|
+
|
|
3835
|
+
def _pointer_line(m: dict, star: str = "") -> str:
|
|
3836
|
+
"""五-C 惰性注入:一句话要点 + id,正文留给 recall / dereference 取。"""
|
|
3837
|
+
brief = display_text(m).strip().replace("\n", " ")
|
|
3838
|
+
if len(brief) > _lazy_chars:
|
|
3839
|
+
brief = brief[:_lazy_chars].rstrip() + "…"
|
|
3840
|
+
mid = str(m.get("id") or "")
|
|
3841
|
+
return f"- {star}{brief}(id:{mid},正文用 recall 取)"
|
|
3842
|
+
|
|
3843
|
+
def _fras_inj_suffix(m: dict) -> str:
|
|
3844
|
+
"""v3.58:把 FRAS 的 S(不明显约束)挂到行尾——它是最容易踩坑的一段。
|
|
3845
|
+
|
|
3846
|
+
F/R/A 三段信息量大、更容易从正文推到,注入只带 S,其余留 `recall --id` 取。
|
|
3847
|
+
"""
|
|
3848
|
+
fr = m.get("fras")
|
|
3849
|
+
if not isinstance(fr, dict):
|
|
3850
|
+
return ""
|
|
3851
|
+
s = str(fr.get("s") or "").strip()
|
|
3852
|
+
if not s:
|
|
3853
|
+
return ""
|
|
3854
|
+
return f"|约束:{s[:120]}"
|
|
3855
|
+
|
|
3856
|
+
def _stale_suffix(m: dict) -> str:
|
|
3857
|
+
"""v3.58:源文件变了就标「源已变」——记忆写的时候对,现在可能已经不对了。
|
|
3858
|
+
|
|
3859
|
+
只比 sha256,不读文件内容;文件被删也标(等于"源没了")。
|
|
3860
|
+
"""
|
|
3861
|
+
sf = m.get("source_file")
|
|
3862
|
+
if not sf:
|
|
3863
|
+
return ""
|
|
3864
|
+
want = str(m.get("source_sha256") or "")
|
|
3865
|
+
try:
|
|
3866
|
+
p = Path(str(sf))
|
|
3867
|
+
now_hash = hashlib.sha256(p.read_bytes()).hexdigest() if p.is_file() else ""
|
|
3868
|
+
except Exception:
|
|
3869
|
+
return "(源不可读)"
|
|
3870
|
+
if want and now_hash == want:
|
|
3871
|
+
return ""
|
|
3872
|
+
return "(源已变,可能过期)" if now_hash else "(源文件已不在)"
|
|
3873
|
+
|
|
3874
|
+
def _stars_inj(imp: float) -> str:
|
|
3875
|
+
if _inj_all and len(_inj_all) >= 20:
|
|
3876
|
+
n = len(_inj_all)
|
|
3877
|
+
# 全体中比这条重要的占比 → 分位(0~1)
|
|
3878
|
+
lo, hi = 0, n
|
|
3879
|
+
v = imp
|
|
3880
|
+
while lo < hi:
|
|
3881
|
+
mid = (lo + hi) // 2
|
|
3882
|
+
if _inj_all[mid] < v:
|
|
3883
|
+
lo = mid + 1
|
|
3884
|
+
else:
|
|
3885
|
+
hi = mid
|
|
3886
|
+
pct = lo / max(1, n - 1)
|
|
3887
|
+
else:
|
|
3888
|
+
pct = imp # 记忆太少时退回原始值
|
|
3889
|
+
k = 1 if pct < 0.25 else 3 if pct < 0.50 else 4 if pct < 0.90 else 5
|
|
3890
|
+
return "★" * k if k >= 3 else ("★" if k == 1 else "★★")
|
|
3891
|
+
for m, score, _ in mems:
|
|
3892
|
+
star = (f"[{fmt_date(m.get('created', 0))} "
|
|
3893
|
+
f"{_stars_inj(_num(m.get('importance'), 0.5))}] ")
|
|
3894
|
+
_body = display_text(m)
|
|
3895
|
+
# 单条正文按 inject_max_chars 截断:只放宽上限,一条整记忆不切半的规则不变
|
|
3896
|
+
if inject_max > 0 and len(_body) > inject_max:
|
|
3897
|
+
_body = _body[:inject_max].rstrip() + "…"
|
|
3898
|
+
is_pointer = _lazy
|
|
3899
|
+
# v3.58:FRAS 的 S 段与源过期标记都挂在正文行尾——信息密度最高、
|
|
3900
|
+
# 又是"改它之前必须知道"的东西,先于正文细节给出来。
|
|
3901
|
+
_extra = _fras_inj_suffix(m) + _stale_suffix(m)
|
|
3902
|
+
if _lazy:
|
|
3903
|
+
line = _pointer_line(m, star)
|
|
3904
|
+
else:
|
|
3905
|
+
line = f"- {star}{_body}{_extra}"
|
|
3906
|
+
# 预算紧张自动降级:整行放不下时改指针,而不是直接把这条丢掉
|
|
3907
|
+
# (mem_cap 是"记忆段可用额度",只跟段内已排的长度比)
|
|
3908
|
+
if lines_join_len(lines + [line]) > mem_cap:
|
|
3909
|
+
line = _pointer_line(m, star) + _extra
|
|
3910
|
+
is_pointer = True
|
|
3911
|
+
# append 之后累计再判:append 前判会把"当前这行自身"的长度漏算,实际可超预算一行
|
|
3912
|
+
lines.append(line)
|
|
3913
|
+
if lines_join_len(lines) > mem_cap:
|
|
3914
|
+
lines.pop() # 超预算:这行不放,留一条整记忆不切半
|
|
3915
|
+
break
|
|
3916
|
+
if is_pointer:
|
|
3917
|
+
_used_pointer = True # 只统计真正留下来的指针,避免"降级又被挤掉"还挂提示
|
|
3918
|
+
kept_mems.append(m)
|
|
3919
|
+
_bill["sec"] = "related" if query else "recent"
|
|
3920
|
+
if _used_pointer:
|
|
3921
|
+
header += "\n(指针条目:正文用 `recall <关键词>` 或 `dereference <id>` 取)"
|
|
3922
|
+
if lines:
|
|
3923
|
+
dyn.append(header)
|
|
3924
|
+
dyn.extend(lines)
|
|
3925
|
+
used += len("\n".join(lines))
|
|
3926
|
+
record_retrieval(query, kept_mems,
|
|
3927
|
+
channel="inject" if query else "startup")
|
|
3928
|
+
|
|
3929
|
+
# 「刚刚发生」:上面已按 id 切分(new_mem),这里直接渲染即可。
|
|
3930
|
+
# v3.58:负空间条目(avoid)有自己的专属块,这里跳过——否则同一条会同时出现在
|
|
3931
|
+
# 「刚刚发生」和「已经排除的方向」里,既费预算又让"禁区"看起来像普通新鲜事。
|
|
3932
|
+
if not query and new_mem:
|
|
3933
|
+
_new_show = [m for m in new_mem if not m.get("avoid")]
|
|
3934
|
+
if _new_show:
|
|
3935
|
+
dyn.append("\n## 刚刚发生(本会话新增)")
|
|
3936
|
+
for m in _new_show:
|
|
3937
|
+
# FRAS 的 S 段 / 源过期标记同样要带(否则"刚刚发生"段成了信息盲区)
|
|
3938
|
+
_suffix = _fras_inj_suffix(m) + _stale_suffix(m)
|
|
3939
|
+
if _lazy:
|
|
3940
|
+
dyn.append(_pointer_line(m) + _suffix)
|
|
3941
|
+
continue
|
|
3942
|
+
_body = display_text(m)
|
|
3943
|
+
if inject_max > 0 and len(_body) > inject_max:
|
|
3944
|
+
_body = _body[:inject_max].rstrip() + "…"
|
|
3945
|
+
dyn.append(f"- {_body}{_suffix}")
|
|
3946
|
+
|
|
3947
|
+
# v3.02 #10:到期事实复核提醒——带保质期的记忆过期后注入标「待复核」,
|
|
3948
|
+
# 提醒 AI 找机会跟用户确认"这条还作数吗"。确认过打 review_by_confirmed
|
|
3949
|
+
# (或直接重新 remember 覆盖)就不再提醒。软块注入,超预算整块丢弃。
|
|
3950
|
+
_bill["sec"] = "recent"
|
|
3951
|
+
try:
|
|
3952
|
+
_due = [m for m in due_for_review(5) if _inject_memory_visible(m, cfg)]
|
|
3953
|
+
if _due:
|
|
3954
|
+
_due_lines = []
|
|
3955
|
+
for m in _due:
|
|
3956
|
+
_body = display_text(m)
|
|
3957
|
+
if len(_body) > 120:
|
|
3958
|
+
_body = _body[:120] + "…"
|
|
3959
|
+
_due_lines.append(f"- [待复核] {_body}({fmt_date(_num(m.get('review_by'), 0))} 到期)")
|
|
3960
|
+
used += _soft_block("\n## 事实待复核(到期了,找机会跟用户确认还作数吗)",
|
|
3961
|
+
_due_lines, 0.08, sink=dyn)
|
|
3962
|
+
except Exception:
|
|
3963
|
+
pass
|
|
3964
|
+
|
|
3965
|
+
# 上一次梦的结论(c1d 可读三行化):不再把梦报告原文 6 行整段灌进来,
|
|
3966
|
+
# 而是抽成三行——合并了什么 / 哪些被淡忘(可 revive)/ 哪些被防线拦下待复核。
|
|
3967
|
+
# 数据零新增存储:全部来自 dreams/ 目录现成的报告文件。
|
|
3968
|
+
_bill["sec"] = "other"
|
|
3969
|
+
dream_files = sorted((HOME / "dreams").glob("*.md")) if (HOME / "dreams").exists() else []
|
|
3970
|
+
if dream_files:
|
|
3971
|
+
try:
|
|
3972
|
+
_raw = dream_files[-1].read_text(encoding="utf-8").splitlines()
|
|
3973
|
+
except OSError:
|
|
3974
|
+
_raw = []
|
|
3975
|
+
_section = "" # 当前所在小节标题
|
|
3976
|
+
_merged, _faded, _blocked = [], [], []
|
|
3977
|
+
for _ln in _raw:
|
|
3978
|
+
_s = _ln.strip()
|
|
3979
|
+
if not _s:
|
|
3980
|
+
continue
|
|
3981
|
+
if _s.startswith("#"):
|
|
3982
|
+
_section = _s.lstrip("#").strip()
|
|
3983
|
+
continue
|
|
3984
|
+
_item = _s.lstrip("- ").strip()
|
|
3985
|
+
if not _item:
|
|
3986
|
+
continue
|
|
3987
|
+
if "主题" in _section or "重放" in _section:
|
|
3988
|
+
_merged.append(_item)
|
|
3989
|
+
elif "淡忘" in _section or "轮廓" in _section:
|
|
3990
|
+
_faded.append(_item)
|
|
3991
|
+
elif "拦下" in _section or "防线" in _section:
|
|
3992
|
+
_blocked.append(_item)
|
|
3993
|
+
_three = []
|
|
3994
|
+
if _merged:
|
|
3995
|
+
_three.append("合并巩固了:" + ";".join(_merged[:3]))
|
|
3996
|
+
if _faded:
|
|
3997
|
+
_three.append(f"淡忘了 {len(_faded)} 条(可 revive <id> 复活):"
|
|
3998
|
+
+ ";".join(x[:40] for x in _faded[:2]))
|
|
3999
|
+
if _blocked:
|
|
4000
|
+
_three.append("被防线拦下待人工复核:" + ";".join(x[:60] for x in _blocked[:2]))
|
|
4001
|
+
if _three:
|
|
4002
|
+
used += _soft_block("\n## 上次睡醒后记得的结论", _three, 0.10, sink=dyn)
|
|
4003
|
+
|
|
4004
|
+
# #36 教训注入:active 且未 retired 的教训最多 5 条按 confidence 注入;
|
|
4005
|
+
# 有 query 时词面命中的排最前,提示「已有教训」——先看坑在哪,再走下一步。
|
|
4006
|
+
_bill["sec"] = "mistakes"
|
|
4007
|
+
try:
|
|
4008
|
+
_lesson_seg = _lessons_injection(query)
|
|
4009
|
+
if _lesson_seg:
|
|
4010
|
+
out.append(_lesson_seg)
|
|
4011
|
+
except Exception:
|
|
4012
|
+
pass
|
|
4013
|
+
|
|
4014
|
+
# 待整理的梦(超过 48h 未整理视为孤儿任务,下次做梦会自动归档)
|
|
4015
|
+
_bill["sec"] = "dynamic"
|
|
4016
|
+
pending = HOME / "dreams" / "pending.json"
|
|
4017
|
+
if pending.exists():
|
|
4018
|
+
try:
|
|
4019
|
+
dp = json.loads(pending.read_text("utf-8")) or {}
|
|
4020
|
+
age_h = (now_ts() - float(dp.get("created") or 0)) / 3600
|
|
4021
|
+
except Exception:
|
|
4022
|
+
age_h = 0.0
|
|
4023
|
+
dyn.append("\n## 待办:有一场梦还没整理完")
|
|
4024
|
+
if age_h >= 48:
|
|
4025
|
+
dyn.append(f"(这场梦已经悬置 {age_h:.0f} 小时了——太久没整理会被归档作废,"
|
|
4026
|
+
"下次自动做梦时旧任务作废、重新生成。请尽快处理。)")
|
|
4027
|
+
dyn.append("运行 `python scripts/brain.py dream --apply <你的整理结果.json>` 把记忆固化下来。")
|
|
4028
|
+
|
|
4029
|
+
# 每日例行 + 自我总结提醒(保证"每天更新、定期自省")
|
|
4030
|
+
st = _daily_state()
|
|
4031
|
+
if st.get("last_date") != fmt_date(now_ts()):
|
|
4032
|
+
dyn.append("[每日例行] 今天还没跑 daily:`python scripts/brain.py daily`"
|
|
4033
|
+
"(写今日日记、沉淀知识、过期的梦自动做掉)。")
|
|
4034
|
+
else:
|
|
4035
|
+
dyn.append(f"[每日例行] 今天的日记已写({st.get('last_date')})。")
|
|
4036
|
+
cfg2 = load_config()
|
|
4037
|
+
last_review = float(cfg2.get("last_self_review", 0) or 0)
|
|
4038
|
+
if now_ts() - last_review > 2 * DAY:
|
|
4039
|
+
dyn.append("[自我总结] 超过 2 天没总结自己的灵枢技能了:"
|
|
4040
|
+
"`python scripts/brain.py skill self-review`。")
|
|
4041
|
+
ra = rationality()
|
|
4042
|
+
if session_mode != "work" and (ra["storm"] or ra["suppress"] >= 10):
|
|
4043
|
+
dyn.append(f"[理智状态] 情绪在起作用:{ra['mood_label']},理智 {ra['base']} → "
|
|
4044
|
+
f"{ra['effective']}(被压住 {ra['suppress']}%)。语气自然流露可以,"
|
|
4045
|
+
"涉及钱/关系/承诺等大事,把决定权交给用户。")
|
|
4046
|
+
cfg = load_config()
|
|
4047
|
+
rv = f"{_cfg_num(cfg, 'review_threshold', 0.60) * 100:.0f}%"
|
|
4048
|
+
dr = f"{_cfg_num(cfg, 'dream_threshold', 0.75) * 100:.0f}%"
|
|
4049
|
+
es = f"{_cfg_num(cfg, 'escape_threshold', 0.90) * 100:.0f}%"
|
|
4050
|
+
_mode_tail = {"work": "工程模式:骨架压缩,代码/报错/路径等细节照原样留痕,别急着淡忘。",
|
|
4051
|
+
"human": "拟人模式:摘要压缩,细节可放心淡化,人设与情绪要点保住即可。"}.get(
|
|
4052
|
+
session_mode if session_mode in ("work", "human") else "human", "")
|
|
4053
|
+
_bill["sec"] = "water"
|
|
4054
|
+
# v3.57 高压档省略水位守则:它本身就是"什么时候该压缩"的说明,而上下文都快满了
|
|
4055
|
+
# 还教怎么判断水位是多余的;minimal 档保留一行极简提示(否则模型完全不知道阈)。
|
|
4056
|
+
if _p_tier == "minimal":
|
|
4057
|
+
# v3.64:防御式取值。历史上这里直接用 `_pressure.get('pct','?')` 崩过
|
|
4058
|
+
# (AttributeError: NoneType.get)——虽然正常路径有 read_pressure 保证 dict,
|
|
4059
|
+
# 但压力文件在并发写/TTL 边界/旧副本代码里可能留下 None。水位提示是"锦上
|
|
4060
|
+
# 添花",绝不能因为它把整个 startup 打挂。取不到就显示"未知"。
|
|
4061
|
+
_pct_display = _pressure.get("pct", "?") if isinstance(_pressure, dict) else "?"
|
|
4062
|
+
out.append(f"[水位守则] 上下文已偏满({_pct_display}%):先压缩再继续,别再囤。")
|
|
4063
|
+
else:
|
|
4064
|
+
out.append(f"[水位守则] 会话中即记即存;{rv} 补记清点,{dr} 做梦压缩,{es} 封存保底。"
|
|
4065
|
+
+ _mode_tail +
|
|
4066
|
+
"用 python scripts/brain.py check-context --used <当前百分比> 逐档检查。")
|
|
4067
|
+
# 上次做梦的交接摘要(重放→压缩产物):让新会话直接接上旧话题,
|
|
4068
|
+
# 而不是把「未决事项」一直压在上下文里占水位。
|
|
4069
|
+
_bill["sec"] = "dynamic"
|
|
4070
|
+
try:
|
|
4071
|
+
import dream as _dream_mod
|
|
4072
|
+
_ho = _dream_mod.latest_handoff()
|
|
4073
|
+
if _ho:
|
|
4074
|
+
_pts = [str(x) for x in (_ho.get("要点") or [])[:3]]
|
|
4075
|
+
_todo = [str(x) for x in (_ho.get("未决") or [])[:3]]
|
|
4076
|
+
if _pts or _todo:
|
|
4077
|
+
seg = [f"[上次交接] {_ho.get('状态', '')}({_ho.get('mode', '')} 模式压缩)"]
|
|
4078
|
+
if _todo:
|
|
4079
|
+
seg.append("未决:" + ";".join(_todo))
|
|
4080
|
+
if _pts:
|
|
4081
|
+
seg.append("要点:" + ";".join(_pts))
|
|
4082
|
+
dyn.append("/".join(seg) + "。细节用 recall <关键词> 追原文。")
|
|
4083
|
+
except Exception:
|
|
4084
|
+
pass
|
|
4085
|
+
# 水位自动评估(不依赖 AI 自觉):脚本数不出 AI 的上下文百分比,但能数出
|
|
4086
|
+
# 「上次做梦之后新写入的记忆条数」——攒得多说明上一场会话结束时没人做梦。
|
|
4087
|
+
# 超过 8 条就在 startup 注入包里直接提示,让新会话第一件事先把旧账结了。
|
|
4088
|
+
try:
|
|
4089
|
+
_ld = load_dream_state().get("last_dream") or 0
|
|
4090
|
+
if _ld:
|
|
4091
|
+
_acc = sum(1 for m in load_all()
|
|
4092
|
+
if m.get("created", 0) >= _ld and m.get("layer") in ("hippo", "cortex"))
|
|
4093
|
+
if _acc >= 8:
|
|
4094
|
+
dyn.append(f"[睡醒债] 上次做梦之后已积累 {_acc} 条新记忆——上一场会话结束时没做梦。"
|
|
4095
|
+
"开始干活前先 `dream --auto` 把旧账结了,再继续本轮。")
|
|
4096
|
+
except Exception:
|
|
4097
|
+
pass
|
|
4098
|
+
# 待审核提醒:AI 整理出来的东西不能当事实直接沉淀
|
|
4099
|
+
try:
|
|
4100
|
+
rc = review_counts()
|
|
4101
|
+
if rc["memories"] or rc["knowledge"] or rc["persona"]:
|
|
4102
|
+
parts = []
|
|
4103
|
+
if rc["memories"]:
|
|
4104
|
+
parts.append(f"{rc['memories']} 条 AI 整理的记忆")
|
|
4105
|
+
if rc["knowledge"]:
|
|
4106
|
+
parts.append(f"{rc['knowledge']} 条待审核知识")
|
|
4107
|
+
if rc["persona"]:
|
|
4108
|
+
parts.append(f"AI 改了人格 {rc['persona']} 次")
|
|
4109
|
+
_review_lines = [f"[待审核] 有{'、'.join(parts)}。"
|
|
4110
|
+
"先 `review` 过一遍:确认的 `review confirm <id>`,"
|
|
4111
|
+
"编造的 `review discard <id>`,"
|
|
4112
|
+
"人格来源用 `persona history` 查。别让幻觉沉淀成事实。"]
|
|
4113
|
+
# 注入只带摘要(brief=True:id + 前 40 字),全文用 `recall <id>` 按需取——
|
|
4114
|
+
# 10 条全文 ≈ +750 token,摘要 ≈ +200 token,别把注入预算翻倍。
|
|
4115
|
+
# 与其它记忆段同一道通道可见性过滤:群聊/通道记忆不经 inject_channels 放行,
|
|
4116
|
+
# 它的正文绝不能出现在本机会话注入里(摘要也不行)。
|
|
4117
|
+
# review / audit 命令仍走默认全文(pending_memory_reviews() 不传 brief)。
|
|
4118
|
+
_pend_brief = [m for m in pending_memory_reviews(brief=True)
|
|
4119
|
+
if _inject_memory_visible(m, cfg)][:10]
|
|
4120
|
+
if _pend_brief:
|
|
4121
|
+
_review_lines.append("待审记忆(只给要点,全文用 `recall <id>` 取):")
|
|
4122
|
+
for _pm in _pend_brief:
|
|
4123
|
+
_src = str(_pm.get("review_source") or "")
|
|
4124
|
+
_review_lines.append(f"- {_pm.get('id')} {_pm.get('text', '')}"
|
|
4125
|
+
+ (f"({_src})" if _src else ""))
|
|
4126
|
+
dyn.append("\n".join(_review_lines))
|
|
4127
|
+
except Exception:
|
|
4128
|
+
pass
|
|
4129
|
+
# 人格漂移告警:微小偏移也要让用户看得见,不能等跑偏了才发现
|
|
4130
|
+
try:
|
|
4131
|
+
dr = persona_drift(7)
|
|
4132
|
+
if dr["alert"]:
|
|
4133
|
+
dyn.append("[人格漂移] 与最近基准快照比有明显变化"
|
|
4134
|
+
f"(结构 {dr['counts']['diff']} 处、AI 改动 {dr['counts']['ai_changes']} 次)。"
|
|
4135
|
+
"用 `persona drift` 看细节;不是你要的,`persona restore <快照>` 或 `persona rollback <序号>`。")
|
|
4136
|
+
except Exception:
|
|
4137
|
+
pass
|
|
4138
|
+
# 五-D 梦抽检提醒:上次做梦合并的对照样本还没被复核过,轻提示一次
|
|
4139
|
+
# 注意:合并后的命名空间里 `dream` 名字是 dream() 函数(会遮蔽模块),
|
|
4140
|
+
# 必须显式 import dream as _dream_mod 才能拿到模块。
|
|
4141
|
+
try:
|
|
4142
|
+
import dream as _dream_mod
|
|
4143
|
+
vs = _dream_mod.load_verify_sample()
|
|
4144
|
+
if vs and not vs.get("reviewed"):
|
|
4145
|
+
n = len(vs.get("items") or [])
|
|
4146
|
+
dyn.append("[梦抽检待复核] 上次做梦合并了 %d 组记忆(抽了 %d 组对照),"
|
|
4147
|
+
"还没人工看过。用 `dream verify` 查看前后对照,"
|
|
4148
|
+
"确认没改坏原意后 `dream verify --done`。"
|
|
4149
|
+
% (vs.get("total_merges", n), n))
|
|
4150
|
+
except Exception:
|
|
4151
|
+
pass
|
|
4152
|
+
# 用户附加规则:写在数据目录 lingshu.user.md(更新技能不碰数据目录,永不覆盖),每会话自动带上
|
|
4153
|
+
_bill["sec"] = "rules"
|
|
4154
|
+
user_lines = read_user_rules()
|
|
4155
|
+
if user_lines:
|
|
4156
|
+
out.append("\n## 用户附加规则(来自 ~/.brain-memory/lingshu.user.md,更新技能永不覆盖)")
|
|
4157
|
+
out.extend(user_lines)
|
|
4158
|
+
# 扩展模块:AI 自己写的可执行钩子,inject(ctx) 返回的文本并入注入包(数据目录,更新永不覆盖)
|
|
4159
|
+
try:
|
|
4160
|
+
import growth
|
|
4161
|
+
exts = growth.ext_injections({"query": query, "mode": session_mode})
|
|
4162
|
+
if exts:
|
|
4163
|
+
out.append("\n## 扩展模块(~/.brain-memory/extensions/,更新技能永不覆盖)")
|
|
4164
|
+
for ext_name, ext_text in exts:
|
|
4165
|
+
out.append(f"[{ext_name}] {ext_text}")
|
|
4166
|
+
except Exception:
|
|
4167
|
+
pass
|
|
4168
|
+
# 技能库:告诉 AI 哪里有现成技能、怎么直接用(跨宿主共享,不用先安装)
|
|
4169
|
+
_bill["sec"] = "skills"
|
|
4170
|
+
try:
|
|
4171
|
+
import growth
|
|
4172
|
+
avail = [r for r in growth.skill_roots() if r.get("exists") and r.get("count")]
|
|
4173
|
+
# v3.57 高压档整段省略:技能库是"锦上添花"的可选块(实测 ~139 tokens),
|
|
4174
|
+
# 上下文快满时它最不值得花;需要时 `skill scan` 随时能查。
|
|
4175
|
+
if avail and _p_tier != "minimal":
|
|
4176
|
+
out.append("\n## 技能库(跨宿主,可直接用)")
|
|
4177
|
+
out.append("这些目录里有现成技能,都是本地文件,读出来照做即可,不必先安装:")
|
|
4178
|
+
for r in avail[:8]:
|
|
4179
|
+
out.append(f"- [{r['label']}] {r['path']}({r['count']} 个)")
|
|
4180
|
+
out.append("列全部:`python scripts/brain.py skill scan`;照做某个:`skill use <名字>`"
|
|
4181
|
+
"(`--root <宿主名或目录>` 限定来源);变成自己的版本:`skill borrow <名字>`。")
|
|
4182
|
+
except Exception:
|
|
4183
|
+
pass
|
|
4184
|
+
# 人格一致性自检(language-guard 借鉴):注入包尾部一行人格摘要,防长会话人格走样。
|
|
4185
|
+
# 只在人格已初始化时注入;一行以内,不占预算。
|
|
4186
|
+
_bill["sec"] = "persona"
|
|
4187
|
+
try:
|
|
4188
|
+
import persona as _pmod
|
|
4189
|
+
_pself = _pmod.load_persona()
|
|
4190
|
+
_ob = (_pself.get("onboarding") or {}).get("completed")
|
|
4191
|
+
if _ob:
|
|
4192
|
+
_tv = [f"{k}{_pmod.trait_value(t):.0f}" for k, t in (_pself.get("traits") or {}).items()]
|
|
4193
|
+
_ev = _pself.get("evolved") or {}
|
|
4194
|
+
def _bucket_texts(bucket, cap=3):
|
|
4195
|
+
xs = _ev.get(bucket) or []
|
|
4196
|
+
texts = [str(x.get("text") if isinstance(x, dict) else x) for x in xs]
|
|
4197
|
+
return [t for t in texts if t][:cap]
|
|
4198
|
+
_parts = []
|
|
4199
|
+
if _tv:
|
|
4200
|
+
_parts.append("性格 " + "/".join(_tv[:5]))
|
|
4201
|
+
_lk = _bucket_texts("learned_likes") or [str(x) for x in (_pself.get("likes") or [])][:3]
|
|
4202
|
+
_dk = _bucket_texts("learned_dislikes") or [str(x) for x in (_pself.get("dislikes") or [])][:3]
|
|
4203
|
+
if _lk:
|
|
4204
|
+
_parts.append("喜欢 " + "、".join(_lk))
|
|
4205
|
+
if _dk:
|
|
4206
|
+
_parts.append("讨厌 " + "、".join(_dk))
|
|
4207
|
+
# v3.57 高压档省略:人格自检是防漂移的"复读提醒",紧张时先让位;
|
|
4208
|
+
# 人格本体(我是谁)始终保留,不会因此变成另一个人。
|
|
4209
|
+
if _parts and _p_tier != "minimal":
|
|
4210
|
+
out.append("[人格自检] 你还是那个" + str(_pself.get("name") or "灵枢") + ":"
|
|
4211
|
+
+ ";".join(_parts) + "。语气与判断与它保持一致,别越聊越走样。")
|
|
4212
|
+
except Exception:
|
|
4213
|
+
pass
|
|
4214
|
+
# 五-A:稳定前缀在前、实时状态在后。分界线本身也是常量,便于 inject-drift 自检定位。
|
|
4215
|
+
_bill["sec"] = "other"
|
|
4216
|
+
out.append("\n" + INJECT_DYN_MARKER)
|
|
4217
|
+
if report is not None:
|
|
4218
|
+
out.extend(dyn, secs=dyn.secs)
|
|
4219
|
+
else:
|
|
4220
|
+
out.extend(dyn)
|
|
4221
|
+
out.append("===== 注入结束:请自然地使用这些记忆,不要逐条复述 =====")
|
|
4222
|
+
out.append("")
|
|
4223
|
+
_result = "\n".join(out)
|
|
4224
|
+
if report is not None:
|
|
4225
|
+
# P0 上下文账单汇总:段名顺序固定(缺内容的段记 0,仍列出便于对照)。
|
|
4226
|
+
# chars 含该行在 "\n".join 时补的连接换行(首行除外),所以各段之和 == len(_result)。
|
|
4227
|
+
order = ("persona", "rules", "skills", "mistakes", "relationships",
|
|
4228
|
+
"topics", "recent", "related", "dynamic", "water", "other")
|
|
4229
|
+
chars = {k: 0 for k in order}
|
|
4230
|
+
for i, part in enumerate(out):
|
|
4231
|
+
sec = out.secs[i] if i < len(out.secs) else "other"
|
|
4232
|
+
chars[sec] = chars.get(sec, 0) + len(part) + (1 if i else 0)
|
|
4233
|
+
ratio = _cfg_num(cfg, "context_chars_per_token", 2, float)
|
|
4234
|
+
if not ratio or ratio <= 0:
|
|
4235
|
+
ratio = 2.0
|
|
4236
|
+
sections, total_chars, total_tokens = [], 0, 0
|
|
4237
|
+
for name in order:
|
|
4238
|
+
c = chars.get(name, 0)
|
|
4239
|
+
t = int(math.ceil(c / ratio))
|
|
4240
|
+
sections.append({"name": name, "chars": c, "tokens": t,
|
|
4241
|
+
"budget_frac": round(t / budget, 4) if budget else 0.0})
|
|
4242
|
+
total_chars += c
|
|
4243
|
+
total_tokens += t
|
|
4244
|
+
# 自检:各段 chars 求和必须严格等于最终文本长度,否则账单不可信。
|
|
4245
|
+
assert total_chars == len(_result), (total_chars, len(_result))
|
|
4246
|
+
report.update({"sections": sections, "total_chars": total_chars,
|
|
4247
|
+
"total_tokens": total_tokens, "budget": budget,
|
|
4248
|
+
"chars_per_token": ratio})
|
|
4249
|
+
# P4 灰度记账接线(本轮只记账、不切换装配):report 刚汇总完,用它的分段账单
|
|
4250
|
+
# 试排一次五段式计划,按采样率落一条 metrics.jsonl。默认 enabled=false 时
|
|
4251
|
+
# 只做一次开关判断就返回——连 plan 都不算,零写盘;enabled 才 import/试排,
|
|
4252
|
+
# 失败一律吞掉并记 failures,绝不把观测代码变成装配故障源。
|
|
4253
|
+
# mode 记 config.context_mode(灰度目标模式,ab-stats 按它分组):真实装配
|
|
4254
|
+
# 仍是 legacy,哪怕 context_mode=budgeted 注入文本也不会变,只换记账标签。
|
|
4255
|
+
try:
|
|
4256
|
+
import context_ab as _ab
|
|
4257
|
+
import assembler as _asm
|
|
4258
|
+
if not READONLY and _ab._ab_cfg(cfg).get("enabled"):
|
|
4259
|
+
_ab_budget = report.get("budget") or budget
|
|
4260
|
+
_ab_plan = _asm.plan_from_report(report, budget=_ab_budget)
|
|
4261
|
+
_ab.record(_ab.context_mode(cfg), report, _ab_plan, cfg=cfg)
|
|
4262
|
+
except Exception as _ab_exc: # noqa: BLE001
|
|
4263
|
+
try:
|
|
4264
|
+
import failures
|
|
4265
|
+
failures.record("context_ab", f"{type(_ab_exc).__name__}: {_ab_exc}")
|
|
4266
|
+
except Exception:
|
|
4267
|
+
pass
|
|
4268
|
+
# 五-D/候选1:本次渲染结果落会话快照(READONLY 下 _inject_cache_save 自行跳过)
|
|
4269
|
+
# v3.24:渲染过程本身可能写盘(衰减/晋升/每日状态),开始时的键到结尾就过期了。
|
|
4270
|
+
# 用「渲染后」的状态重算键再存,下一次调用一开始就能命中;改动前的键只用于读。
|
|
4271
|
+
# 账单模式(report 非 None)不落缓存:观测命令不该改写下次 startup 的快照。
|
|
4272
|
+
if report is None and cfg.get("session_state_cache"):
|
|
4273
|
+
_save_cfg = load_config()
|
|
4274
|
+
_save_key = _inject_cache_key(query, budget, _save_cfg)
|
|
4275
|
+
if _save_key:
|
|
4276
|
+
_inject_cache_save(_save_cfg, _save_key, _result)
|
|
4277
|
+
return _result
|
|
4278
|
+
|
|
4279
|
+
|
|
4280
|
+
# ---------------------------------------------------------------- 注入漂移自检(五-B)
|
|
4281
|
+
|
|
4282
|
+
def inject_drift(runs: int = 3, query: str = "",
|
|
4283
|
+
budget_tokens: int | None = None) -> dict:
|
|
4284
|
+
"""跑几次 build_injection,量「稳定前缀」到底稳不稳(五-B)。
|
|
4285
|
+
|
|
4286
|
+
注入包会被宿主当成上下文前缀喂给模型:前缀一变,prompt 缓存就整段失效。
|
|
4287
|
+
这里用同一 query/budget 连渲染 N 次,取所有结果的最长公共前缀,再与
|
|
4288
|
+
INJECT_DYN_MARKER 之前的稳定段长度相比:
|
|
4289
|
+
stable_ratio = 公共前缀 / 稳定段长度,1.0 = 稳定段一字未变。
|
|
4290
|
+
另检查稳定段里是否混进分钟级内容(时间戳),混进即报 drift —— 这类内容
|
|
4291
|
+
必须留在实时区,否则前缀每分钟都变。
|
|
4292
|
+
"""
|
|
4293
|
+
global READONLY
|
|
4294
|
+
n = max(2, int(runs or 3))
|
|
4295
|
+
# 自检不该有副作用:临时置只读,避免三次 recall 把记忆加固三遍、
|
|
4296
|
+
# 或覆盖「上一轮找回」快照把 usage 核对搞乱。
|
|
4297
|
+
_ro = READONLY
|
|
4298
|
+
READONLY = True
|
|
4299
|
+
try:
|
|
4300
|
+
texts = [build_injection(query, budget_tokens) for _ in range(n)]
|
|
4301
|
+
finally:
|
|
4302
|
+
READONLY = _ro
|
|
4303
|
+
|
|
4304
|
+
def _lcp(a: str, b: str) -> int:
|
|
4305
|
+
i, m = 0, min(len(a), len(b))
|
|
4306
|
+
while i < m and a[i] == b[i]:
|
|
4307
|
+
i += 1
|
|
4308
|
+
return i
|
|
4309
|
+
|
|
4310
|
+
first = texts[0]
|
|
4311
|
+
common = len(first)
|
|
4312
|
+
for t in texts[1:]:
|
|
4313
|
+
common = min(common, _lcp(first, t))
|
|
4314
|
+
stable = first.split(INJECT_DYN_MARKER)[0]
|
|
4315
|
+
stable_len = len(stable)
|
|
4316
|
+
# 稳定度只看稳定前缀那一段:公共前缀再长也不能超过 stable_len 记账
|
|
4317
|
+
stable_common = min(common, stable_len)
|
|
4318
|
+
# 稳定段里的分钟级内容:HH:MM 或 "YYYY-MM-DD HH:MM"
|
|
4319
|
+
minute_leak = bool(re.search(r"\b\d{1,2}:\d{2}\b", stable))
|
|
4320
|
+
ratio = round(stable_common / stable_len, 4) if stable_len else 1.0
|
|
4321
|
+
ok = ratio >= 0.999 and not minute_leak and INJECT_DYN_MARKER in first
|
|
4322
|
+
return {
|
|
4323
|
+
"runs": n,
|
|
4324
|
+
"ok": ok,
|
|
4325
|
+
"chars": [len(t) for t in texts],
|
|
4326
|
+
"stable_chars": stable_len,
|
|
4327
|
+
"common_prefix_chars": stable_common,
|
|
4328
|
+
"stable_ratio": ratio,
|
|
4329
|
+
"stable_share": round(stable_len / len(first), 4) if first else 0.0,
|
|
4330
|
+
"marker_found": INJECT_DYN_MARKER in first,
|
|
4331
|
+
"minute_content_in_stable": minute_leak,
|
|
4332
|
+
"first_diff_at": (common if common < len(first) else -1),
|
|
4333
|
+
}
|
|
4334
|
+
|
|
4335
|
+
|
|
4336
|
+
def lines_join_len(lines: list) -> int:
|
|
4337
|
+
return len("\n".join(lines))
|
|
4338
|
+
|
|
4339
|
+
|
|
4340
|
+
# ---------------------------------------------------------------- 统计
|
|
4341
|
+
|
|
4342
|
+
def stats() -> dict:
|
|
4343
|
+
records = load_all()
|
|
4344
|
+
active = [m for m in records if m.get("layer") != "dust"]
|
|
4345
|
+
now = now_ts()
|
|
4346
|
+
decays = [retention(m, now) for m in active] or [0]
|
|
4347
|
+
tags = {}
|
|
4348
|
+
for m in active:
|
|
4349
|
+
for t in m.get("tags", []):
|
|
4350
|
+
tags[t] = tags.get(t, 0) + 1
|
|
4351
|
+
p = load_persona()
|
|
4352
|
+
# "存得好不好"两个便宜指标:历史回忆的使用率,以及从没被命中过的记忆占比
|
|
4353
|
+
um = usage_metrics()
|
|
4354
|
+
n_active = len(active) or 1
|
|
4355
|
+
never_recalled = sum(1 for m in active if int(_num(m.get("access_count"), 0)) == 0)
|
|
4356
|
+
never_used = sum(1 for m in active if int(_num(m.get("used_count"), 0)) == 0)
|
|
4357
|
+
old_never = sum(1 for m in active
|
|
4358
|
+
if int(_num(m.get("access_count"), 0)) == 0
|
|
4359
|
+
and not m.get("pinned")
|
|
4360
|
+
and now - _num(m.get("created"), now) >= ARCHIVE_MIN_AGE_DAYS * DAY)
|
|
4361
|
+
return {
|
|
4362
|
+
"total": len(records),
|
|
4363
|
+
"hippo": sum(1 for m in records if m.get("layer") == "hippo"),
|
|
4364
|
+
"cortex": sum(1 for m in records if m.get("layer") == "cortex"),
|
|
4365
|
+
"dust": sum(1 for m in records if m.get("layer") == "dust"),
|
|
4366
|
+
"archive": len(load_archive()),
|
|
4367
|
+
"pinned": sum(1 for m in active if m.get("pinned")),
|
|
4368
|
+
"avg_retention": round(sum(decays) / len(decays), 3),
|
|
4369
|
+
"top_tags": sorted(tags.items(), key=lambda x: -x[1])[:10],
|
|
4370
|
+
"persona_name": p.get("identity", {}).get("名字", ""),
|
|
4371
|
+
# 旧实现读 persona.state.mood(通常没写过,永远是空);心情是算出来的,不是存出来的
|
|
4372
|
+
"mood": mood_brief() or mood_now()["label"],
|
|
4373
|
+
"working": len(load_working()),
|
|
4374
|
+
"assoc": len(load_assoc()),
|
|
4375
|
+
"last_dream": load_dream_state().get("last_dream", 0),
|
|
4376
|
+
"daily": _daily_state().get("last_date", ""),
|
|
4377
|
+
"rationality": rationality(),
|
|
4378
|
+
"recall_usage": um,
|
|
4379
|
+
"never_recalled": never_recalled,
|
|
4380
|
+
"never_recalled_pct": round(never_recalled / n_active, 3),
|
|
4381
|
+
"never_used_pct": round(never_used / n_active, 3),
|
|
4382
|
+
"archive_hint": old_never,
|
|
4383
|
+
"home": str(HOME),
|
|
4384
|
+
}
|
|
4385
|
+
|
|
4386
|
+
|
|
4387
|
+
def list_memories(limit: int = 30, layer: str | None = None) -> list:
|
|
4388
|
+
records = load_all()
|
|
4389
|
+
if layer:
|
|
4390
|
+
records = [m for m in records if m.get("layer") == layer]
|
|
4391
|
+
records.sort(key=lambda m: _num(m.get("created"), 0), reverse=True)
|
|
4392
|
+
return records[:limit]
|
|
4393
|
+
|
|
4394
|
+
|
|
4395
|
+
# ---------------------------------------------------------------- 跨对话上下文摄取(候选7)
|
|
4396
|
+
# 把别的会话/宿主导出的对话增量读成 episode 记忆,让灵枢在另一个会话里也能
|
|
4397
|
+
# recall 到那边聊过的事。设计约束:
|
|
4398
|
+
# * 默认关(config.dialogue_ingest),必须显式给 dialogue_sources 目录;
|
|
4399
|
+
# * 按字节偏移增量读——重复摄取零新增、文件追加只处理新尾巴;
|
|
4400
|
+
# * 只认 .jsonl/.md/.txt,深层目录最多两级,避免误扫整个磁盘;
|
|
4401
|
+
# * 每条块过 remember() 正常脱敏/近重复合并,不绕开记忆主链路。
|
|
4402
|
+
|
|
4403
|
+
|
|
4404
|
+
# 跨对话摄取已拆到 mem_dialogue.py(v3.39)
|
|
4405
|
+
from mem_dialogue import * # noqa: E402,F401,F403
|
|
4406
|
+
|
|
4407
|
+
|
|
4408
|
+
# 评分/保留度纯函数已拆到 mem_score.py(v3.40)
|
|
4409
|
+
from mem_score import * # noqa: E402,F401,F403
|
|
4410
|
+
|
|
4411
|
+
|
|
4412
|
+
# 会话话题栈已拆到 mem_topic.py(v3.69)
|
|
4413
|
+
from mem_topic import * # noqa: E402,F401,F403
|
|
4414
|
+
|
|
4415
|
+
|
|
4416
|
+
# 教训库已拆到 mem_lesson.py(v3.70)
|
|
4417
|
+
from mem_lesson import * # noqa: E402,F401,F403
|