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.
Files changed (135) hide show
  1. package/CHANGELOG.md +2605 -0
  2. package/LICENSE +21 -0
  3. package/README.md +698 -3
  4. package/SKILL-lite.md +45 -0
  5. package/SKILL-tiny.md +37 -0
  6. package/SKILL.md +379 -0
  7. package/assets/panel.html +5616 -0
  8. package/cordis-plugin/lingshu-cron/cordis.patch.yml +3 -0
  9. package/cordis-plugin/lingshu-cron/index.js +4 -0
  10. package/cordis-plugin/lingshu-cron/package.json +34 -0
  11. package/cordis-plugin/lingshu-cron/plugin.js +1040 -0
  12. package/cordis-plugin/lingshu-guard/plugin.js +473 -0
  13. package/cordis-plugin/lingshu-im/plugin.js +635 -0
  14. package/cordis-plugin/lingshu-startup/README.md +123 -0
  15. package/cordis-plugin/lingshu-startup/cordis.patch.yml +3 -0
  16. package/cordis-plugin/lingshu-startup/index.js +4 -0
  17. package/cordis-plugin/lingshu-startup/package.json +25 -0
  18. package/cordis-plugin/lingshu-startup/plugin.js +352 -0
  19. package/cordis.patch.yml +3 -0
  20. package/docs/commands.md +243 -0
  21. package/docs/mechanics.md +610 -0
  22. package/docs/models.md +52 -0
  23. package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +49 -0
  24. package/docs/panel-api.md +198 -0
  25. package/docs/recovery.md +90 -0
  26. package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +53 -0
  27. package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +804 -0
  28. package/index.js +102 -0
  29. package/package.json +52 -6
  30. package/scripts/_panel_smoke_v299.py +27 -0
  31. package/scripts/_smoke_v299.py +31 -0
  32. package/scripts/_sync_trae_cn.py +34 -0
  33. package/scripts/assembler.py +197 -0
  34. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +53 -0
  35. package/scripts/astrbot_plugin_lingshu/PATCH_NOTES.md +28 -0
  36. package/scripts/astrbot_plugin_lingshu/README.md +58 -0
  37. package/scripts/astrbot_plugin_lingshu/_conf_schema.json +92 -0
  38. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +2605 -0
  39. package/scripts/astrbot_plugin_lingshu/engine/README.md +698 -0
  40. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +45 -0
  41. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +37 -0
  42. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +379 -0
  43. package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +5616 -0
  44. package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +243 -0
  45. package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -0
  46. package/scripts/astrbot_plugin_lingshu/engine/docs/models.md +52 -0
  47. package/scripts/astrbot_plugin_lingshu/engine/docs/panel-api.md +198 -0
  48. package/scripts/astrbot_plugin_lingshu/engine/docs/recovery.md +90 -0
  49. package/scripts/astrbot_plugin_lingshu/engine/scripts/_panel_smoke_v299.py +27 -0
  50. package/scripts/astrbot_plugin_lingshu/engine/scripts/_smoke_v299.py +31 -0
  51. package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +34 -0
  52. package/scripts/astrbot_plugin_lingshu/engine/scripts/assembler.py +197 -0
  53. package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +280 -0
  54. package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +192 -0
  55. package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +46 -0
  56. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +55 -0
  57. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +215 -0
  58. package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +165 -0
  59. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +4867 -0
  60. package/scripts/astrbot_plugin_lingshu/engine/scripts/context_ab.py +260 -0
  61. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2028 -0
  62. package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +1137 -0
  63. package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +1180 -0
  64. package/scripts/astrbot_plugin_lingshu/engine/scripts/failures.py +107 -0
  65. package/scripts/astrbot_plugin_lingshu/engine/scripts/fallback_embed.py +114 -0
  66. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +4745 -0
  67. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth_parts.py +263 -0
  68. package/scripts/astrbot_plugin_lingshu/engine/scripts/insights.py +131 -0
  69. package/scripts/astrbot_plugin_lingshu/engine/scripts/make_dsh_tgz.py +92 -0
  70. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +242 -0
  71. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +159 -0
  72. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_lesson.py +160 -0
  73. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +210 -0
  74. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_topic.py +177 -0
  75. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +4417 -0
  76. package/scripts/astrbot_plugin_lingshu/engine/scripts/npm_prepack.py +31 -0
  77. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +115 -0
  78. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +609 -0
  79. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +2703 -0
  80. package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +591 -0
  81. package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2309 -0
  82. package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +195 -0
  83. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +368 -0
  84. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +736 -0
  85. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +228 -0
  86. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +123 -0
  87. package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +252 -0
  88. package/scripts/astrbot_plugin_lingshu/main.py +703 -0
  89. package/scripts/astrbot_plugin_lingshu/make_checksums.py +87 -0
  90. package/scripts/astrbot_plugin_lingshu/metadata.yaml +7 -0
  91. package/scripts/behavior_baseline.py +280 -0
  92. package/scripts/bench.py +192 -0
  93. package/scripts/brain.py +46 -0
  94. package/scripts/check_pressure_sync.py +55 -0
  95. package/scripts/check_tag.py +215 -0
  96. package/scripts/check_version.py +265 -0
  97. package/scripts/checkpoint.py +165 -0
  98. package/scripts/cli.py +4867 -0
  99. package/scripts/context_ab.py +260 -0
  100. package/scripts/core.py +2028 -0
  101. package/scripts/dream.py +1137 -0
  102. package/scripts/emotion.py +1180 -0
  103. package/scripts/failures.py +107 -0
  104. package/scripts/fallback_embed.py +114 -0
  105. package/scripts/growth.py +4745 -0
  106. package/scripts/growth_parts.py +263 -0
  107. package/scripts/hooks/pre-commit +18 -0
  108. package/scripts/hooks/pre-push +20 -0
  109. package/scripts/insights.py +131 -0
  110. package/scripts/make_dsh_tgz.py +92 -0
  111. package/scripts/make_manifest.py +254 -0
  112. package/scripts/make_plugin_zip.py +88 -0
  113. package/scripts/mem_dialogue.py +242 -0
  114. package/scripts/mem_embed.py +159 -0
  115. package/scripts/mem_lesson.py +160 -0
  116. package/scripts/mem_score.py +210 -0
  117. package/scripts/mem_topic.py +177 -0
  118. package/scripts/memory.py +4417 -0
  119. package/scripts/npm_prepack.py +31 -0
  120. package/scripts/panel_build.py +115 -0
  121. package/scripts/panel_cloud.py +609 -0
  122. package/scripts/panel_server.py +2703 -0
  123. package/scripts/panels.py +591 -0
  124. package/scripts/persona.py +2309 -0
  125. package/scripts/recreate_push.ps1 +117 -0
  126. package/scripts/retriever.py +195 -0
  127. package/scripts/run_tests.py +91 -0
  128. package/scripts/safety.py +368 -0
  129. package/scripts/session_import.py +736 -0
  130. package/scripts/session_rag.py +228 -0
  131. package/scripts/session_summary.py +123 -0
  132. package/scripts/summarizer.py +252 -0
  133. package/scripts/sync_engine.py +139 -0
  134. package/scripts/update_dsh_copy.ps1 +107 -0
  135. package/start-panel.bat +60 -0
@@ -0,0 +1,2028 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """灵枢 —— 类脑记忆引擎(纯标准库,零依赖)
4
+
5
+ 分层结构(对照人脑):
6
+ 工作记忆 = 当前上下文(AI 自己维护,默认不进磁盘;work add 只是会话级暂存)
7
+ 短期记忆 = hippocampus.jsonl 海马体,快速编码、易衰减
8
+ 长期记忆 = cortex.jsonl 新皮层,经"睡眠巩固"后稳定存储
9
+ 核心记忆 = persona.json 人格/身份,常驻注入
10
+ 淡忘区 = dust.jsonl 已遗忘但保留轮廓的旧记忆
11
+
12
+ 关键机制:
13
+ * 遗忘曲线 R(t) = exp(-Δt / S),每次回忆会提升稳定度 S(测试效应/再巩固)
14
+ * 模糊回忆 IDF 加权字符二元组相似度 + 时间衰减 + 重要性 + 联想扩散
15
+ * 做梦巩固 上下文将满/定时触发:重放 → 压缩 → 巩固 → 情绪整合 → 遗忘
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import hashlib
22
+ import json
23
+ import math
24
+ import os
25
+ import re
26
+ import shutil
27
+ import socket
28
+ import sys
29
+ import threading
30
+ import time
31
+ import zipfile
32
+ from contextlib import contextmanager, nullcontext
33
+ from datetime import datetime
34
+ from pathlib import Path
35
+
36
+ # Windows 控制台默认 GBK,中文输出会变乱码(鐏垫灑)。无条件 reconfigure 成 UTF-8,
37
+ # 用户不用再手动设 PYTHONIOENCODING。errors="replace" 让无法编码的字符降级成 ?,
38
+ # 不再抛 UnicodeEncodeError;流不支持 reconfigure(重定向/被替换/老版本)时静默跳过。
39
+ for _s in (sys.stdout, sys.stderr):
40
+ try:
41
+ _s.reconfigure(encoding="utf-8", errors="replace")
42
+ except AttributeError:
43
+ pass
44
+
45
+ # ---------------------------------------------------------------- 基础环境
46
+
47
+ import safety # noqa: E402 —— 数据目录护栏(无依赖、不反向 import core)
48
+
49
+ def _default_home() -> Path:
50
+ """数据目录三级解析:环境变量 > 指针文件 ~/.brain-memory/.home > 默认位置。
51
+
52
+ 指针文件让"改数据目录"不依赖系统环境变量(面板设置一次即永久生效,
53
+ 跨终端/跨面板都认)。环境变量优先级更高,可随时覆盖指针。
54
+ """
55
+ env = os.environ.get("BRAIN_MEMORY_HOME")
56
+ if env:
57
+ return Path(env)
58
+ # v3.61:`BRAIN_MEMORY_HOME` **存在但为空**几乎只有一种成因——PowerShell 里
59
+ # 写了 `$home = ...`,而 `$HOME` 是只读自动变量,赋值静默失败,于是
60
+ # `$env:BRAIN_MEMORY_HOME = $home` 把环境变量设成了空串。此时不能再静默回落到
61
+ # 真实用户目录:v3.52 验证时就因此对真实库跑了一次备份,产出 1.45 GB 半截 zip。
62
+ # 这里显式告警(不改行为,避免破坏已有调用),让操作者一眼看到。
63
+ if env is not None and not env.strip():
64
+ sys.stderr.write(
65
+ "[警告] BRAIN_MEMORY_HOME 被设为空值,已忽略并回落到默认目录 "
66
+ f"{Path.home() / '.brain-memory'}。\n"
67
+ " 若是 PowerShell 里赋值,注意 `$HOME` 是只读自动变量,"
68
+ "请改用其它变量名(如 $memHome)。\n"
69
+ )
70
+ try:
71
+ ptr = Path.home() / ".brain-memory" / ".home"
72
+ if ptr.is_file():
73
+ target = ptr.read_text(encoding="utf-8").strip()
74
+ if target:
75
+ return Path(target).expanduser()
76
+ except OSError:
77
+ pass
78
+ return Path.home() / ".brain-memory"
79
+
80
+
81
+ HOME = _default_home()
82
+
83
+ # #24 多宿主可见:锁文件里除了 pid 还记主机名,共享盘上能看出"另一台机器在写"。
84
+ # 提前定义,_locked 与 lock_writers 都引用它。
85
+ _HOSTNAME = (socket.gethostname() or "unknown").strip() or "unknown"
86
+
87
+ # 只读降级:能读不能写(沙箱写盘被拒、或迁移前临时挂载已有库时用)。
88
+ # 触发方式:环境变量 BRAIN_MEMORY_READONLY=1、命令行 --ro,或运行前自动探测到 HOME 不可写。
89
+ # BRAIN_MEMORY_READONLY=0 反向手动覆盖:确认目录可写但自动探测被环境干扰误报时,
90
+ # 用它跳过探测强制可写。
91
+ # READONLY_FORCED(v3.76):区分"用户显式强制只读"与"自动探测降级只读"。
92
+ # 面板长驻进程的自愈逻辑只看 READONLY——原来强制只读(--ro/环境变量)也会被
93
+ # 写请求的复探摘掉,等于用户的只读承诺被静默违反。现在强制只读时禁止自愈。
94
+ READONLY = os.environ.get("BRAIN_MEMORY_READONLY") == "1"
95
+ READONLY_FORCED = READONLY
96
+
97
+ DAY = 86400
98
+ HOUR = 3600
99
+
100
+ # ---------------------------------------------------------------- 库 schema 版本(v3.02 #16)
101
+ # 记忆库结构版本号落在 HOME/_meta.json。当前代码只认 1;读到更高版本说明
102
+ # 数据是被更新版本写出的,盲写可能破坏未知字段——降级只读并留痕,由用户升级程序。
103
+ SCHEMA_VERSION = 1
104
+
105
+ # —— 空库熔断(v3.45):上次见到库里有东西、这次全是空/消失 → 疑似被清空。
106
+ # 事故复盘:记忆库被整片删掉,但灵枢照常"从零开始"跑,没人发现——
107
+ # 直到用户问"你还记得吗"。这里把"突然变空"变成一个显式告警。
108
+ # 只比文件字节数(O(1)),不数行:_check_meta 每次写都会跑,不能拖慢。
109
+ WIPE_ALERT: dict | None = None
110
+
111
+ # 参与"空库"判定的数据文件(全部消失/归零 = 库被清空)。
112
+ _WIPE_WATCH = ("persona.json", "config.json", "hippocampus.jsonl",
113
+ "cortex.jsonl", "dust.jsonl", "knowledge.jsonl", "notes.jsonl",
114
+ "emotions.jsonl", "desires.json", "working.jsonl", "topics.jsonl")
115
+
116
+
117
+ def _watch_sizes() -> tuple[dict[str, int], int]:
118
+ """当前数据文件的字节数快照 + 总量。"""
119
+ sizes: dict[str, int] = {}
120
+ total = 0
121
+ for name in _WIPE_WATCH:
122
+ try:
123
+ n = (HOME / name).stat().st_size
124
+ except OSError:
125
+ n = 0
126
+ sizes[name] = n
127
+ total += n
128
+ return sizes, total
129
+
130
+
131
+ def newest_backup_hint() -> str | None:
132
+ """最近的可用备份包(备份目录候选里按 mtime 取最新)。找不到返回 None。"""
133
+ try:
134
+ import safety
135
+ dirs = safety.backup_dir_candidates(HOME)
136
+ except Exception:
137
+ dirs = [HOME / "backups"]
138
+ best: tuple[float, str] | None = None
139
+ for d in dirs:
140
+ try:
141
+ if not d.is_dir():
142
+ continue
143
+ for p in d.glob("brain-memory_*.zip*"):
144
+ try:
145
+ m = p.stat().st_mtime
146
+ except OSError:
147
+ continue
148
+ if best is None or m > best[0]:
149
+ best = (m, str(p))
150
+ except OSError:
151
+ continue
152
+ return best[1] if best else None
153
+
154
+
155
+ def schema_version() -> int:
156
+ """当前支持的记忆库 schema 版本(brain.py 命名空间合并后即 brain.schema_version())。"""
157
+ return SCHEMA_VERSION
158
+
159
+
160
+ def _check_meta() -> None:
161
+ """初始化/校验 HOME/_meta.json:老库没有就静默创建(向后兼容);
162
+ schema_version 高于当前支持版本则只读降级 + 日志警告。绝不抛异常。"""
163
+ global READONLY, WIPE_ALERT
164
+ if READONLY:
165
+ return # 只读降级:不写 _meta.json,已有文件照样可读
166
+ path = HOME / "_meta.json"
167
+ try:
168
+ if path.exists():
169
+ meta = json.loads(path.read_text(encoding="utf-8-sig"))
170
+ ver = int(meta.get("schema_version", 0) or 0)
171
+ if ver > SCHEMA_VERSION:
172
+ READONLY = True
173
+ _sync_state()
174
+ log_event("schema", f"记忆库 schema 版本 {ver} 高于当前支持的 {SCHEMA_VERSION},"
175
+ "已降级只读(请升级灵枢后再写)", level="warn")
176
+ return
177
+ meta["updated"] = now_ts()
178
+ meta.setdefault("schema_version", SCHEMA_VERSION)
179
+ meta.setdefault("created", now_ts())
180
+ else:
181
+ ts = now_ts()
182
+ meta = {"schema_version": SCHEMA_VERSION, "created": ts, "updated": ts}
183
+ # —— 空库熔断:和上一次见到的快照比,从"有"变成"全空"就记一笔 ——
184
+ prev_seen = meta.get("seen") or {}
185
+ try:
186
+ sizes, total = _watch_sizes()
187
+ except Exception:
188
+ sizes, total = {}, 0
189
+ prev_total = int(prev_seen.get("bytes") or 0)
190
+ prev_sizes = prev_seen.get("sizes") or {}
191
+ persona_lost = bool(prev_sizes.get("persona.json")) and not sizes.get("persona.json")
192
+ if (prev_total > 0 and total == 0) or persona_lost:
193
+ WIPE_ALERT = {
194
+ "prev_bytes": prev_total,
195
+ "prev_ts": prev_seen.get("ts"),
196
+ "now_bytes": total,
197
+ "persona_lost": persona_lost,
198
+ "backup": newest_backup_hint(),
199
+ }
200
+ log_event("wipe", f"疑似记忆库被清空:上次 {prev_total} 字节 / 现在 {total} 字节"
201
+ f"{',人格档案消失' if persona_lost else ''}", level="error")
202
+ meta["seen"] = {"ts": now_ts(), "bytes": total, "sizes": sizes}
203
+ atomic_json(path, meta)
204
+ except Exception:
205
+ pass # _meta.json 是元数据不是数据本身,读写失败都不拦正常流程
206
+
207
+ DEFAULT_STABILITY = 2 * DAY
208
+ MAX_STABILITY = 240 * DAY
209
+ RETENTION_FLOOR = 0.10
210
+
211
+ # 人格漂移防线(做梦微调 traits 用):
212
+ # 同一方向的微调先在 state.trait_drift 账本上累积,不满门限不动真格——
213
+ # 防止单场对话/一次梦把人格带偏;过了门限也只按 EMA 比例兑现一部分。
214
+ TRAIT_DRIFT_GATE = 5 # 账面倾向累计满 ±5 才真正改人格
215
+ TRAIT_DRIFT_EMA = 0.6 # 兑现比例:账面 6 分只改 3.6 分,余款下次接着用
216
+
217
+ # "mistake":错误/失误/判断偏差类记录(成长型人格的地基——注入时独立成块)。
218
+ # "relationship":人际关系类记录(A 和我是什么关系、Ta 在意什么、欠了谁/被谁帮过——
219
+ # 注入时独立成块,跨群共享画像的基础)。
220
+ KINDS = ("episode", "fact", "preference", "emotion", "insight", "identity", "habit",
221
+ "mistake", "relationship")
222
+ LAYERS = ("hippo", "cortex", "dust")
223
+
224
+ # 冷热归档层:长期没被想起、保留度极低的沉眠记忆雪藏到这里。
225
+ # 与 dust(淡忘:细节模糊、include_dust 才查)不同,archive 原文完整保留、永不删,
226
+ # 只是移出 recall 的热遍历集合——记忆上万条后,热集只扫活跃记忆,冷数据按需 archive search 捞。
227
+ # 触发:dream 时顺带自动归档(零额外遍历成本),或 `archive run` 手动。
228
+ ARCHIVE_LAYER = "archive"
229
+ ARCHIVE_MIN_AGE_DAYS = 30 # 新记忆至少满月才可能被归档,给足被想起的机会
230
+ ARCHIVE_MAX_IMPORTANCE = 0.5 # 重要度高于此不自动归档(怕误伤用户在意的事)
231
+ ARCHIVE_RETENTION = 0.20 # 保留度低于此才考虑(长期没访问自然衰减到很低)
232
+ ARCHIVE_IDLE_DAYS = 180 # 被想起过的记忆,还需静置超过半年
233
+
234
+ # 运行日志:锁冲突 / 内部异常 / 解析报错留痕,面板「日志」页可看
235
+ LOG_FILE = HOME / "lingshu.log"
236
+
237
+ # 会话级 state 快照目录(五-D/候选1):startup 注入包缓存落这里。
238
+ # 键 = 输入要素(query/budget)+ 关键文件 mtime 的哈希;库没变 + TTL 内直接复用,
239
+ # 跨天恢复首轮不再整库遍历。默认关闭,config.session_state_cache 打开。
240
+ SESSIONS_DIR = HOME / "sessions"
241
+
242
+ # 工作记忆:当前上下文本身就是工作记忆,默认不落盘。
243
+ # 只有 AI 自己决定留一手时才写 working.jsonl(会话级暂存,容量 7±2,过期即弃)。
244
+ WORKING_FILE = HOME / "working.jsonl"
245
+ WORKING_CAPACITY = 9
246
+ WORKING_TTL = 12 * HOUR
247
+
248
+ # 话题栈:会话里聊过的话题与权重(topics.jsonl)。
249
+ # 拟人闲聊用:权重随轮次指数衰减、用户重提拉高、敷衍负反馈拉低,
250
+ # 衰减到阈值以下 + 用户敷衍 → 允许 AI 主动开新话题(spawn_new)。
251
+ TOPIC_FILE = HOME / "topics.jsonl"
252
+ TOPIC_CAPACITY = 12 # 最多同时记住 12 个话题,最旧的先挤出
253
+ TOPIC_DECAY = 0.85 # 每轮未重提,权重 ×0.85(指数衰减)
254
+ TOPIC_SPAWN_THRESHOLD = 0.30 # 权重低于此 + 用户敷衍 → 满足自发话题条件
255
+ TOPIC_TTL = 7 * 24 * HOUR # 7 天没被重提的话题彻底退栈
256
+
257
+ DEFAULT_CONFIG = {
258
+ "budget_tokens": 2400,
259
+ # 每条记忆注入时的正文截断上限(字符):放宽默认值让 AI 记得"再详细点"。
260
+ # 用户嫌注入太短时调大即可;budget_tokens 仍是总量硬约束,超了照样截行。
261
+ "inject_max_chars": 600,
262
+ # 记忆正文注入模式(五-C):
263
+ # full = 直接带正文(默认,体感最"记得住")
264
+ # lazy = 只带一句要点 + id,正文按需用 recall / dereference 取(省 token)
265
+ "inject_mode": "full",
266
+ "inject_lazy_chars": 80, # lazy 模式下每条要点最多留多少字符
267
+ # 会话摘要(附录 C P2):触发规则 + 外部模型(默认关=离线抽取式)
268
+ "summary_turns": 8, # 每 N 轮触发一次摘要
269
+ "summary_pct": 0.60, # 水位 ≥60% 触发
270
+ "summary": { # 模型配置;enabled=false 时全走离线抽取
271
+ "enabled": False,
272
+ "base_url": "",
273
+ "model": "",
274
+ "api_key_env": "",
275
+ "timeout": 30,
276
+ },
277
+ # 检索接入(附录 C P3):session-rag 服务;留空回退灵枢本地召回
278
+ "session_rag": {"url": "", "timeout": 3, "budget_tokens": 800, "select_model": False},
279
+ # 上下文装配模式(附录 C P4 灰度):legacy = 现有整段注入(默认,行为完全不变);
280
+ # budgeted = 五段式预算裁剪(assembler.plan_from_report;灰度期只试排、不改实际注入)。
281
+ "context_mode": "legacy",
282
+ # P4 A/B 采样记账(scripts/context_ab.py):enabled=false 时完全不计算、不落盘;
283
+ # sample = 采样率(0-1,默认 0.1);log=false 时只算对比、不写 metrics.jsonl。
284
+ "context_ab": {"enabled": False, "sample": 0.1, "log": True},
285
+ # remember 写入时的正文截断上限(字符):单条记忆原文最长保留多少。
286
+ "remember_max_chars": 1200,
287
+ # 上下文水位三级防线(比例,0-1):
288
+ # review 清点:先补记本轮漏掉的,不急着压缩
289
+ # dream 做梦:重放→压缩→巩固
290
+ # escape 逃生:上下文快满,必须原样封存,保证不丢
291
+ "review_threshold": 0.60,
292
+ "dream_threshold": 0.75,
293
+ "escape_threshold": 0.90,
294
+ # 永久记忆排序权重:recency 减半(不再让"多久没被想起"压过"语义对不对"),
295
+ # importance 提升(用户/AI 标记的重要性是永久信号),core_bias 给 persona
296
+ # 核心规则命中额外加权(避免长期被临时记录挤下去)。primacy 保留首因效应小权重。
297
+ "weights": {"relevance": 0.55, "recency": 0.10, "importance": 0.35,
298
+ "core_bias": 0.20, "primacy": 0.03},
299
+ "panel_port": 8765,
300
+ # 模型档位:auto 不干预;small 时注入"小模型模式"提示,劝退高风险自动能力
301
+ # (dream --apply 自动合并 / knowledge tidy 提炼 / emotion evaluate 自动判读)。
302
+ "model_tier": "auto",
303
+ # 情绪注入三道闸(借鉴 dsh-feiyu-mood,防情绪复读/漂移):
304
+ # mood_inject_change_delta = True 时,情绪签名(标签+强度档)没变就不重复注入;
305
+ # mood_inject_per_day = 每天最多注入 N 次心情摘要,0 = 不限额。
306
+ "mood_inject_change_delta": True,
307
+ "mood_inject_per_day": 6,
308
+ # v3.55:extract(即记即存)封存对话后顺带做一次极轻量情绪评价(纯词表,
309
+ # 强度封顶 0.35、每次最多 1 条),让心情跟着对话走;false = 完全关闭。
310
+ "emotion_auto_extract": True,
311
+ # 五-D/候选1 会话级 state 快照:startup 注入包缓存(默认关)。
312
+ # 开启后,库文件 mtime 未变 + TTL 内的重复 startup 直接复用上次注入文本,
313
+ # 跳过整库遍历与 recall 重算(跨天恢复首轮明显更快)。
314
+ # 记忆/人格文件与非易失配置哈希都会入缓存键;TTL 只作最后兜底。
315
+ "session_state_cache": False,
316
+ "session_state_ttl": 300,
317
+ # 候选7 跨对话上下文摄取:把别的会话/宿主导出的对话(.jsonl/.md/.txt)
318
+ # 增量读成 episode 记忆,让灵枢在另一个会话里也能"想起"那边聊过的事。
319
+ # 默认关(跨会话隐私);开启需同时给 dialogue_sources 目录,绝不自动扫描全盘。
320
+ "dialogue_ingest": False,
321
+ "dialogue_sources": [],
322
+ "dialogue_ingest_max_files": 50, # 单次最多扫多少个文件
323
+ "dialogue_ingest_max_chars": 700, # 单条摄取记忆(一个对话块)的字符上限
324
+ "dialogue_ingest_auto": False, # startup 时顺带增量摄取(近实时;只 stat,没新内容不开销)
325
+ # 本机注入默认排除群聊/私聊通道记忆;这里只放显式允许的 channel,"*" 为全部放开。
326
+ "inject_channels": [],
327
+ # 会话模式:auto = 按场景自动切换;work = 恒为工程模式(情绪隔离、理性优先);
328
+ # human = 恒为拟人模式(情绪照常注入)。用于解决"刚聊完情绪化话题立刻写代码"。
329
+ "mode": "auto",
330
+ # 聊天平台通道(QQ/微信/钉钉群聊)鉴权白名单:
331
+ # owners = 主人账号(channel:id 形如 "qq:10001"),可执行一切敏感命令
332
+ # admins = 管理员,权限低于 owner(owner 天然包含 admin 权限)
333
+ # 纯本机命令行不带 --user 调用不受限(本机默认信任)。
334
+ "owners": [],
335
+ "admins": [],
336
+ # 会话模式判定信号词(I-09/F-13:词表外置 config,定制不用改源码)。
337
+ # analyze_topic 会把这里的词与代码内置表合并;留空即用内置表。
338
+ "topic_signals": {
339
+ "work": [], # 额外的工作/工程信号词,如 ["推理", "微调"]
340
+ "human": [], # 额外的情绪/寒暄信号词
341
+ },
342
+ # —— P1 永久记忆:可选 embedding(不装 Ollama 自动退回纯关键词)——
343
+ # LINGSHU_EMBED_URL 环境变量优先;config.json 里 embed.url 兜底。
344
+ # 任一为空白即禁用 Dense 召回,完全不破坏零依赖定位。
345
+ "embed": {
346
+ "url": "", # 例:http://localhost:11434/api/embeddings
347
+ "model": "nomic-embed-text",
348
+ "timeout_sec": 30, # 单次调用超时(v3.65:模型冷加载实测要 10.5s,8s 必降级)
349
+ "max_chars": 3000, # 超过就截断(长记忆全文 embed 慢)
350
+ "batch_size": 8, # 异步批量写 embedding 时的条数
351
+ # 连不上嵌入服务时,冷却 N 秒内不再重试:否则每次 recall 都要等满 timeout
352
+ # 并往 lingshu.log 刷一条 warn(Ollama 没起时最明显)。
353
+ "fail_cooldown_sec": 300,
354
+ # —— 纯 Python 降级向量兜底(零依赖 hash trick,见 fallback_embed.py)——
355
+ # Ollama 不可用/未配置时自动接管,给语义召回一个纯 stdlib 的 Dense 通道
356
+ "fallback": {
357
+ "enabled": True,
358
+ "dims": 256,
359
+ },
360
+ },
361
+ # reranker(可选):LINGSHU_RERANK_URL / config.rerank.url 配了才用
362
+ "rerank": {
363
+ "url": "",
364
+ "model": "qwen3-reranker-0.6b",
365
+ "timeout_sec": 8,
366
+ "top_n": 20, # 只对粗排前 N 条做精排
367
+ },
368
+ }
369
+
370
+ # ---------------------------------------------------------------- 工具函数
371
+
372
+ def now_ts() -> int:
373
+ return int(time.time())
374
+
375
+
376
+ def fmt_time(ts: int) -> str:
377
+ return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M")
378
+
379
+
380
+ def fmt_date(ts: int) -> str:
381
+ return datetime.fromtimestamp(ts).strftime("%Y-%m-%d")
382
+
383
+
384
+ def check_wipe() -> dict | None:
385
+ """跑一次元数据检查,返回「疑似被清空」告警(没有就 None)。
386
+
387
+ startup / doctor / 面板概览都用它:宁可误报一次,也不要让库被清空后
388
+ 安安静静地假装一切正常。写盘失败不影响返回值。
389
+ """
390
+ try:
391
+ _check_meta()
392
+ except Exception:
393
+ pass
394
+ return WIPE_ALERT
395
+
396
+
397
+ def ensure_home() -> None:
398
+ # 第一道闸:盘符根/用户主目录/用户库文件夹(桌面、文档、下载…)一律拒绝当记忆库。
399
+ # 事故里的清空就是发生在这些目录上——库放进去等于把自己绑在同一颗炸弹上。
400
+ safety.assert_safe_home(HOME, action="初始化")
401
+ if READONLY:
402
+ return # 只读降级:不建目录、不补默认文件,已有文件照样可读
403
+ HOME.mkdir(parents=True, exist_ok=True)
404
+ if not (HOME / "config.json").exists():
405
+ atomic_json(HOME / "config.json", DEFAULT_CONFIG)
406
+ if not (HOME / "persona.json").exists():
407
+ compile_persona()
408
+ (HOME / "dreams").mkdir(parents=True, exist_ok=True)
409
+ (HOME / "skills").mkdir(parents=True, exist_ok=True) # 面板「技能根目录」显示此目录,提前建好免得显示"不存在"
410
+ _check_meta() # v3.02 #16:_meta.json 创建与 schema 版本校验(老库首次静默创建)
411
+
412
+
413
+ def load_config() -> dict:
414
+ path = HOME / "config.json"
415
+ cfg = dict(DEFAULT_CONFIG)
416
+ if path.exists():
417
+ try:
418
+ cfg.update(json.loads(path.read_text(encoding="utf-8-sig")))
419
+ except Exception:
420
+ pass
421
+ cfg["weights"] = dict(DEFAULT_CONFIG["weights"], **(cfg.get("weights") or {}))
422
+ # —— v2.95 永久记忆:旧默认权重自动升级——
423
+ # 旧默认(v2.94 及以前):relevance=0.55, recency=0.25, importance=0.20, primacy=0.03
424
+ # 新默认(v2.95):recency 0.10, importance 0.35, 新增 core_bias 0.20
425
+ # 迁移条件严格:只有 weights 完全等于旧默认时才升级,用户手改过的保留。
426
+ _W_OLD = {"relevance": 0.55, "recency": 0.25, "importance": 0.20, "primacy": 0.03}
427
+ # 注意:_cur_w 是与 DEFAULT_CONFIG 合并后的字典,新默认里已含 core_bias,
428
+ # 所以"有没有 core_bias"必须看用户 config.json 的原始 weights,否则迁移永远不触发。
429
+ _user_w = {}
430
+ try:
431
+ _user_w = json.loads(path.read_text(encoding="utf-8-sig")).get("weights") or {}
432
+ except Exception:
433
+ pass
434
+ _cur_w = cfg["weights"]
435
+ if (_cur_w.get("recency") == _W_OLD["recency"]
436
+ and _cur_w.get("importance") == _W_OLD["importance"]
437
+ and "core_bias" not in _user_w):
438
+ # 只在完全匹配旧默认时升级;recency/importance 被用户改过就不动
439
+ _upgraded = dict(_cur_w)
440
+ _upgraded["recency"] = DEFAULT_CONFIG["weights"]["recency"]
441
+ _upgraded["importance"] = DEFAULT_CONFIG["weights"]["importance"]
442
+ _upgraded["core_bias"] = DEFAULT_CONFIG["weights"]["core_bias"]
443
+ cfg["weights"] = _upgraded
444
+ # 回写 config.json(原子),下次启动就是新值;回写前先确认不是 READONLY。
445
+ # P6 #27:原来直接 atomic_json 无锁,与面板并发写 config.json 会互相覆盖。
446
+ # 现在在锁内**重读一次**并确认 weights 仍是旧默认才写(避免覆盖并发改动)。
447
+ if not READONLY:
448
+ try:
449
+ with _locked(path):
450
+ _fresh = {}
451
+ try:
452
+ _fresh = json.loads(path.read_text(encoding="utf-8-sig"))
453
+ except Exception:
454
+ pass
455
+ _fresh_w = _fresh.get("weights") or {}
456
+ if (_fresh_w.get("recency") == _W_OLD["recency"]
457
+ and _fresh_w.get("importance") == _W_OLD["importance"]
458
+ and "core_bias" not in _fresh_w):
459
+ _fresh["weights"] = dict(_fresh_w, **_upgraded)
460
+ atomic_json(path, _fresh)
461
+ except Exception:
462
+ pass # 写不动就跳过,内存里用新值也够
463
+ return cfg
464
+
465
+
466
+ # ---------------------------------------------------------------- 脱敏(v3.02 #1/#3)
467
+
468
+ # 常见密钥/凭据形态:命中后替换为 [REDACTED:类型],保留首尾 3 字符便于人工辨认。
469
+ # 顺序敏感:具名前缀(npm_/sk-/ghp_/github_pat_/xox/AKIA)先扫,泛化兜底(kv/Bearer)后扫,
470
+ # 否则泛化规则会把具名 token 先吃掉一半、留下前缀导致具名规则扫不到。
471
+ _REDACT_PATTERNS: list[tuple[str, re.Pattern]] = [
472
+ # npm 2026 granular token:npm_ + 36 位(本会话实测裸 token 贴进对话被
473
+ # capture 原文落盘——泛化 kv-secret 只认 "token=" 形态,裸发漏网,补具名规则)
474
+ ("npm-token", re.compile(r"npm_[A-Za-z0-9]{30,}")),
475
+ ("api-key", re.compile(r"sk-[A-Za-z0-9]{20,}")),
476
+ ("github-pat", re.compile(r"github_pat_[A-Za-z0-9_]{20,}")),
477
+ ("github-token", re.compile(r"ghp_[A-Za-z0-9]{20,}")),
478
+ ("slack-token", re.compile(r"xox[baprs]-[A-Za-z0-9-]{10,}")),
479
+ ("aws-key", re.compile(r"AKIA[0-9A-Z]{16}")),
480
+ ("bearer", re.compile(r"(?i)bearer\s+[A-Za-z0-9._\-]{20,}")),
481
+ ("kv-secret", re.compile(r"(?i)(password|passwd|token|secret|api_key|apikey|access_key)\s*[=:]\s*\S+")),
482
+ ]
483
+
484
+ _REDACT_KEEP = 3 # 保留首尾 3 字符(不足 8 字符全遮)
485
+
486
+
487
+ def redact(text: str) -> str:
488
+ """把文本里的疑似密钥/凭据替换成 [REDACTED:类型]。
489
+
490
+ 用于记忆写入(capture/remember)与运行日志(log_event):
491
+ 任何入口都不落盘明文密钥。纯函数、绝不抛异常——脱敏失败时返回原文
492
+ 比让记忆/日志写入崩掉更合理。
493
+ """
494
+ if not text or not isinstance(text, str):
495
+ return text
496
+ try:
497
+ for label, pat in _REDACT_PATTERNS:
498
+ def _sub(m, _label=label):
499
+ s = m.group(0)
500
+ if len(s) <= 8:
501
+ return f"[REDACTED:{_label}]"
502
+ return f"{s[:_REDACT_KEEP]}[REDACTED:{_label}]{s[-_REDACT_KEEP:]}"
503
+ text = pat.sub(_sub, text)
504
+ return text
505
+ except Exception:
506
+ return text
507
+
508
+
509
+ def log_event(kind: str, message: str, level: str = "info", **extra) -> None:
510
+ """轻量运行日志(lingshu.log):锁冲突、内部异常、解析报错等留痕,面板「日志」页可看。
511
+
512
+ 约束:日志本身绝不当崩溃源——写失败静默跳过,不进写锁、不抛异常。
513
+ """
514
+ if READONLY:
515
+ return
516
+ try:
517
+ LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
518
+ row = {"ts": now_ts(), "kind": kind, "level": level,
519
+ "msg": redact(str(message))[:500]} # 日志统一脱敏(v3.02 #3)
520
+ if extra:
521
+ for k, v in list(extra.items())[:4]:
522
+ if not isinstance(v, (str, int, float, bool, type(None))):
523
+ try:
524
+ v = json.dumps(v, ensure_ascii=False)[:200]
525
+ except Exception:
526
+ v = str(v)[:200]
527
+ row[k] = v
528
+ # v3.02 #4:超过 1MB 轮转 log → log.1 → log.2 → log.3(最旧的 .3 丢弃)。
529
+ # 写入前先滚(否则先写后滚会让刚写的这条跟着旧文件一起被 rename 走,
530
+ # 主日志文件一度消失)。多进程同时滚动:用 lingshu.log 自己的写锁串行化
531
+ # (抢不到锁就这轮不滚,下次写入再试)。不再"截半保留"——半截日志既丢历史又难读。
532
+ try:
533
+ if LOG_FILE.stat().st_size > 1024 * 1024:
534
+ try:
535
+ with _locked(LOG_FILE, timeout=1.0):
536
+ if LOG_FILE.stat().st_size > 1024 * 1024:
537
+ for i in (2, 1): # 从旧往新挪,避免覆盖
538
+ src = LOG_FILE.with_suffix(LOG_FILE.suffix + f".{i}")
539
+ dst = LOG_FILE.with_suffix(LOG_FILE.suffix + f".{i + 1}")
540
+ if src.exists():
541
+ dst.unlink(missing_ok=True)
542
+ src.rename(dst)
543
+ LOG_FILE.rename(LOG_FILE.with_suffix(LOG_FILE.suffix + ".1"))
544
+ except TimeoutError:
545
+ pass # 别的进程正在滚:这轮跳过,下次写入再检查
546
+ except OSError:
547
+ pass
548
+ with open(LOG_FILE, "a", encoding="utf-8", newline="\n") as f:
549
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
550
+ except Exception:
551
+ pass
552
+
553
+
554
+ def audit_log(actor: str, action: str, target: str, detail: str = "") -> None:
555
+ """审计日志(v4 #32):敏感写/删/导出操作追加一行到 HOME/audit.jsonl。
556
+
557
+ 只读模式静默跳过;写失败只 warn 不抛——审计绝不当崩溃源。
558
+ 超过 5000 条时裁剪保留最新 4000 条(与 metrics/log 同样的防膨胀思路)。
559
+ detail 只记简短摘要,不落记忆全文。
560
+ """
561
+ if READONLY:
562
+ return
563
+ try:
564
+ f = HOME / "audit.jsonl"
565
+ try:
566
+ if f.exists() and sum(1 for _ in open(f, "r", encoding="utf-8-sig")) > 5000:
567
+ with _locked(f):
568
+ lines = [x for x in f.read_text(encoding="utf-8-sig").splitlines() if x.strip()]
569
+ if len(lines) > 5000:
570
+ keep = [json.loads(x) for x in lines[-4000:]]
571
+ write_jsonl(f, keep)
572
+ except Exception:
573
+ pass # 裁剪失败不影响本次记录
574
+ _append_jsonl(f, {"ts": now_ts(), "actor": actor, "action": action,
575
+ "target": str(target)[:200], "detail": str(detail)[:300]})
576
+ except Exception as e:
577
+ try:
578
+ log_event("audit", f"审计日志写入失败: {e}", level="warn")
579
+ except Exception:
580
+ pass
581
+
582
+
583
+ def clear_logs(ts=None, kind: str | None = None, msg: str | None = None) -> int:
584
+ """清理运行日志:不给条件就全清;给 ts/kind/msg 就只删匹配的那条。
585
+
586
+ 返回删掉的条数。只读模式下不删(返回 0)。日志清理本身绝不当崩溃源。
587
+ """
588
+ if READONLY or not LOG_FILE.exists():
589
+ return 0
590
+ try:
591
+ lines = [x for x in LOG_FILE.read_text(encoding="utf-8-sig").splitlines() if x.strip()]
592
+ except OSError:
593
+ return 0
594
+ if ts is None and kind is None and msg is None:
595
+ n = len(lines)
596
+ try:
597
+ LOG_FILE.write_text("", encoding="utf-8")
598
+ except OSError:
599
+ return 0
600
+ return n
601
+ keep, removed = [], 0
602
+ for ln in lines:
603
+ try:
604
+ r = json.loads(ln)
605
+ except Exception:
606
+ keep.append(ln) # 解析不了的畸形行:全清以外的操作不动它,别误删
607
+ continue
608
+ hit = True
609
+ if ts is not None:
610
+ try:
611
+ hit = hit and int(r.get("ts") or 0) == int(ts)
612
+ except (TypeError, ValueError):
613
+ hit = False
614
+ if kind is not None:
615
+ hit = hit and str(r.get("kind") or "") == str(kind)
616
+ if msg is not None:
617
+ hit = hit and str(r.get("msg") or "") == str(msg)
618
+ if hit:
619
+ removed += 1
620
+ else:
621
+ keep.append(ln)
622
+ if removed:
623
+ try:
624
+ LOG_FILE.write_text("\n".join(keep) + ("\n" if keep else ""), encoding="utf-8")
625
+ except OSError:
626
+ return 0
627
+ return removed
628
+
629
+
630
+ def read_logs(limit: int = 200, level: str | None = None, kind: str | None = None) -> list:
631
+ """读最近 N 条运行日志(最新在前)。level/kind 任一匹配即保留。
632
+
633
+ v3.02 #4:日志按 1MB 轮转出 .1/.2/.3,这里按 新→旧 合并读取,凑满 limit 即停。
634
+ """
635
+ rows = []
636
+ for suffix in ("", ".1", ".2", ".3"):
637
+ p = LOG_FILE.with_suffix(LOG_FILE.suffix + suffix)
638
+ if not p.exists():
639
+ continue
640
+ try:
641
+ lines = [x for x in p.read_text(encoding="utf-8-sig").splitlines() if x.strip()]
642
+ except OSError:
643
+ continue
644
+ # 新→旧顺序追加;当前文件里越靠后越新,轮转文件里越靠后越新(写序)
645
+ for ln in reversed(lines):
646
+ if len(rows) >= limit * 2:
647
+ break
648
+ rows.append(ln)
649
+ if len(rows) >= limit * 2:
650
+ break
651
+ _lv_rank = {"debug": 0, "info": 1, "warn": 2, "warning": 2, "error": 3}
652
+ want = _lv_rank.get(str(level).lower(), 1) if level else None
653
+ out = []
654
+ for ln in rows:
655
+ try:
656
+ r = json.loads(ln)
657
+ except Exception:
658
+ continue
659
+ if want is not None and _lv_rank.get(str(r.get("level", "info")).lower(), 1) < want:
660
+ continue
661
+ if kind and r.get("kind") != kind:
662
+ continue
663
+ out.append(r)
664
+ return out[:limit]
665
+
666
+
667
+ def _slurp_json(path, default=None):
668
+ """读本地 JSON:兼容 BOM(记事本存的档带 BOM,裸 utf-8 会解析失败);坏了返回 default,
669
+ 绝不当作"档案丢了"去覆盖写盘。"""
670
+ p = Path(path)
671
+ if not p.exists():
672
+ return default
673
+ try:
674
+ return json.loads(p.read_text(encoding="utf-8-sig"))
675
+ except Exception:
676
+ return default
677
+
678
+
679
+ def load_loose_json(path, label: str = "JSON") -> dict | list:
680
+ """读取(可能由大模型生成的)JSON 文件,尽量容错。
681
+
682
+ 模型常把 JSON 包在 ```json 代码块里、或前后夹带说明文字、或行尾漏了括号。
683
+ 这里先按原样解析;失败再去掉代码围栏;再失败就截取第一个配平的 {...} 或 [...]。
684
+ 全都不行抛 ValueError(带上路径与开头片段),不让"静默失败 / 一堆 traceback"吞掉问题。
685
+ """
686
+ p = Path(path)
687
+ raw = p.read_text(encoding="utf-8-sig")
688
+ try:
689
+ return json.loads(raw)
690
+ except Exception:
691
+ pass
692
+ text = raw.strip()
693
+ m = re.search(r"```(?:json)?\s*(.+?)```", text, re.S | re.I)
694
+ if m:
695
+ try:
696
+ return json.loads(m.group(1).strip())
697
+ except Exception:
698
+ pass
699
+ for open_ch, close_ch in (("{", "}"), ("[", "]")):
700
+ start = text.find(open_ch)
701
+ if start < 0:
702
+ continue
703
+ depth = 0
704
+ for i in range(start, len(text)):
705
+ if text[i] == open_ch:
706
+ depth += 1
707
+ elif text[i] == close_ch:
708
+ depth -= 1
709
+ if depth == 0:
710
+ try:
711
+ return json.loads(text[start:i + 1])
712
+ except Exception:
713
+ break
714
+ snippet = raw[:120].replace("\n", " ")
715
+ log_event("parse", f"{label}解析失败:{p.name} 不是合法 JSON", level="warn", path=p.name)
716
+ raise ValueError(f"{label}解析失败:{p} 不是合法 JSON(开头:{snippet}…)。"
717
+ "模型输出里多半混了说明文字或代码块——请只保留 JSON 主体再试。")
718
+
719
+
720
+ _NUMERIC_CONFIG_KEYS = {"budget_tokens", "review_threshold", "dream_threshold",
721
+ "escape_threshold", "panel_port",
722
+ "inject_max_chars", "remember_max_chars"}
723
+ _BOOLEAN_CONFIG_KEYS = {"extensions_enabled"} # 布尔开关:值能当 JSON 布尔解析,或 true/false/1/0 文本
724
+
725
+
726
+ def config_set(key: str, value: str) -> dict:
727
+ """改一项配置(值能当 JSON 解析就当 JSON,否则按字符串存)。"""
728
+ try:
729
+ val = json.loads(value)
730
+ except Exception:
731
+ val = value
732
+ # 布尔开关:只接受 true/false(含 1/0),存成真正的 JSON 布尔,别存字符串
733
+ if key in _BOOLEAN_CONFIG_KEYS:
734
+ if isinstance(val, bool):
735
+ pass
736
+ elif isinstance(val, str) and val.strip().lower() in ("true", "1", "yes", "on"):
737
+ val = True
738
+ elif isinstance(val, str) and val.strip().lower() in ("false", "0", "no", "off"):
739
+ val = False
740
+ else:
741
+ raise ValueError(f"{key} 是布尔开关,只接受 true/false,收到:{value!r}")
742
+ # 数值型配置做校验:否则一条坏值会让 startup/inject 在解析时崩掉、还被误报成"未初始化"
743
+ if key in _NUMERIC_CONFIG_KEYS:
744
+ try:
745
+ num = float(val)
746
+ except (TypeError, ValueError):
747
+ raise ValueError(f"{key} 需要是数字,收到:{value!r}")
748
+ if key in ("review_threshold", "dream_threshold", "escape_threshold"):
749
+ if not (0.0 <= num <= 1.0):
750
+ raise ValueError(f"{key} 需要在 0~1 之间,收到:{value!r}")
751
+ val = num
752
+ elif key in ("budget_tokens", "inject_max_chars", "remember_max_chars"):
753
+ num = int(num)
754
+ if num <= 0:
755
+ raise ValueError(f"{key} 需要是正整数,收到:{value!r}")
756
+ val = num
757
+ elif key == "panel_port":
758
+ num = int(num)
759
+ if not (1 <= num <= 65535):
760
+ raise ValueError(f"panel_port 需要在 1~65535 之间,收到:{value!r}")
761
+ val = num
762
+ ensure_home()
763
+ with _locked(HOME / "config.json"):
764
+ cfg = load_config()
765
+ cfg[key] = val
766
+ atomic_json(HOME / "config.json", cfg)
767
+ return cfg
768
+
769
+
770
+ def config_unset(key: str) -> dict:
771
+ ensure_home()
772
+ with _locked(HOME / "config.json"):
773
+ cfg = load_config()
774
+ cfg.pop(key, None)
775
+ atomic_json(HOME / "config.json", cfg)
776
+ return cfg
777
+
778
+
779
+ def _cfg_num(cfg: dict, key: str, default, cast=float):
780
+ """从配置里安全取一个数字:坏值/手改错时回退默认,绝不让注入崩掉。"""
781
+ try:
782
+ return cast(cfg.get(key, default))
783
+ except (TypeError, ValueError):
784
+ return default
785
+
786
+
787
+ def model_tier() -> str:
788
+ """当前模型档位:auto / small / large。"""
789
+ return str(load_config().get("model_tier", "auto") or "auto").lower()
790
+
791
+
792
+ def _whitelist(key: str) -> list:
793
+ """读鉴权白名单(owners / admins),坏值容错成空列表。"""
794
+ val = load_config().get(key) or []
795
+ return [str(x) for x in val if isinstance(x, (str, int)) and str(x).strip()]
796
+
797
+
798
+ def is_owner(user) -> bool:
799
+ """user("channel:id",如 "qq:10001")是否是主人账号。owner 天然包含 admin 权限。"""
800
+ if not user:
801
+ return False
802
+ return str(user).strip() in _whitelist("owners")
803
+
804
+
805
+ # 群友隐私保护:consent.json 记录「用户主动授权 bot 对外分享关于自己的记忆」。
806
+ # {"qq:10001": {"granted": true, "ts": 123}}
807
+ # 规则:本人可查自己;第三人查他人需目标本人 grant 过;owner/admin 也不豁免(刻意的,
808
+ # 隐私不同于系统级命令——主人可以删库备份,但不能替群友决定「我的记忆给谁看」)。
809
+ CONSENT_FILE = HOME / "consent.json"
810
+
811
+
812
+ def load_consent() -> dict:
813
+ """读授权表(坏文件容错成空表,绝不当作「没人授权过」去覆盖写盘)。"""
814
+ return _slurp_json(CONSENT_FILE, default={}) or {}
815
+
816
+
817
+ def save_consent(data: dict) -> None:
818
+ ensure_home()
819
+ atomic_json(CONSENT_FILE, data)
820
+
821
+
822
+ def consent_grant(user: str, channel: str = "", group: str = "", expires_days: int = 0) -> dict:
823
+ """用户主动授权:允许 bot 对外分享关于自己的记忆(只能由本人调用)。
824
+
825
+ 授权作用域:带 group 时仅授权该群可见;不带 group 记为 "*"(全域,本机默认)。
826
+ 老格式记录(无 groups 字段)视为全域授权,向后兼容。
827
+ expires_days > 0 时记录过期时间(默认 0 = 永久),过期后 _consented 视为未授权。
828
+ """
829
+ user = str(user or "").strip()
830
+ if not user:
831
+ raise ValueError("grant 需要用户标识,形如 qq:10001")
832
+ with _locked(CONSENT_FILE):
833
+ data = load_consent()
834
+ rec = data.get(user)
835
+ if not isinstance(rec, dict):
836
+ rec = {}
837
+ rec["granted"] = True
838
+ rec["ts"] = now_ts()
839
+ try:
840
+ days = int(expires_days)
841
+ except (TypeError, ValueError):
842
+ days = 0
843
+ if days > 0:
844
+ rec["expires"] = rec["ts"] + days * 86400
845
+ else:
846
+ rec.pop("expires", None)
847
+ groups = rec.get("groups")
848
+ if not isinstance(groups, dict):
849
+ groups = {}
850
+ groups[str(group).strip() or "*"] = rec["ts"]
851
+ rec["groups"] = groups
852
+ data[user] = rec
853
+ save_consent(data)
854
+ return data[user]
855
+
856
+
857
+ def consent_revoke(user: str) -> dict | None:
858
+ """撤销授权(只能由本人调用)。本来就没授权时返回 None。"""
859
+ user = str(user or "").strip()
860
+ with _locked(CONSENT_FILE):
861
+ data = load_consent()
862
+ rec = data.pop(user, None)
863
+ if rec is not None:
864
+ save_consent(data)
865
+ return rec
866
+
867
+
868
+ def _consented(user, group: str | None = None) -> bool:
869
+ """user 是否已授权对外分享关于自己的记忆。
870
+
871
+ group 给出时按群作用域校验:记录带 groups 字段则要求当前群在列
872
+ 或有 "*" 全域授权;无 groups 字段的老记录视为全域(向后兼容)。
873
+ """
874
+ if not user:
875
+ return False
876
+ rec = load_consent().get(str(user).strip())
877
+ if not (rec and rec.get("granted")):
878
+ return False
879
+ # 过期字段:带 expires 的授权到期后视为未授权(过期即失效,fail-closed)
880
+ try:
881
+ exp = float(rec.get("expires") or 0)
882
+ except (TypeError, ValueError):
883
+ exp = 0
884
+ if exp > 0 and now_ts() >= exp:
885
+ return False
886
+ groups = rec.get("groups")
887
+ if group is None or not isinstance(groups, dict) or not groups:
888
+ return True
889
+ return "*" in groups or str(group) in groups
890
+
891
+
892
+ def consent_capture_set(user: str, on: bool) -> dict:
893
+ """自动写回授权(与分享授权分离):on=True 允许宿主自动记录本人发言。
894
+
895
+ 只改 capture 字段,不动分享授权;revoke(整条删除)会一并撤掉 capture。
896
+ """
897
+ user = str(user or "").strip()
898
+ if not user:
899
+ raise ValueError("capture 授权需要用户标识,形如 qq:10001")
900
+ with _locked(CONSENT_FILE):
901
+ data = load_consent()
902
+ rec = data.get(user)
903
+ if not isinstance(rec, dict):
904
+ rec = {"granted": False, "ts": now_ts()}
905
+ rec["capture"] = bool(on)
906
+ rec["capture_ts"] = now_ts()
907
+ data[user] = rec
908
+ save_consent(data)
909
+ return data[user]
910
+
911
+
912
+ def consent_capture_allowed(user) -> bool:
913
+ """自动写回是否被本人显式允许(默认不允许:未表态 ≠ 同意被记录)。"""
914
+ if not user:
915
+ return False
916
+ rec = load_consent().get(str(user).strip())
917
+ return bool(rec and rec.get("capture"))
918
+
919
+
920
+ def is_admin(user) -> bool:
921
+ """user 是否是管理员(owner 也算,权限向下包含)。"""
922
+ if not user:
923
+ return False
924
+ u = str(user).strip()
925
+ return u in _whitelist("owners") or u in _whitelist("admins")
926
+
927
+
928
+ # ---------------------------------------------------------------- 会话模式
929
+
930
+ # 工程场景信号词(分组,便于在面板/CLI 里解释"为什么判定成工程模式")
931
+ _WORK_SIGNALS = {
932
+ "编程": ("代码", "报错", "bug", "调试", "编译", "函数", "变量", "接口", "重构", "单元测试",
933
+ "python", "javascript", "typescript", "java", "sql", "shell", "docker", "git",
934
+ "脚本", "算法", "爬虫", "部署", "上线", "排错", "依赖", "仓库"),
935
+ "数据": ("数据", "表格", "excel", "csv", "数据库", "统计", "报表", "查询语句"),
936
+ "工程": ("项目", "工程", "服务器", "接口文档", "运维", "自动化", "配置文件", "性能优化"),
937
+ }
938
+ # 拟人 / 情绪场景信号词
939
+ _HUMAN_SIGNALS = {
940
+ "情绪": ("难过", "开心", "生气", "委屈", "焦虑", "好烦", "累", "崩溃", "压力", "害怕",
941
+ "失望", "孤独", "想你", "谢谢", "对不起", "抱歉", "安慰", "emo"),
942
+ "关系": ("喜欢", "讨厌", "爱你", "朋友", "家人", "恋人", "分手", "在一起", "陪伴"),
943
+ "寒暄": ("哈哈", "晚安", "早安", "好久不见", "在吗", "聊聊", "陪我", "聊天", "心情"),
944
+ }
945
+
946
+
947
+ def analyze_topic(query: str = "") -> dict:
948
+ """auto 模式的话题判定:打分制 + 命中依据(解释"为什么切到 work/human")。
949
+
950
+ 比单纯"命中任一关键词就 work"稳:混合话题(一边聊天一边写代码)也能给出
951
+ 工程/情绪两边的命中数与置信度,面板和 CLI 可把判定依据摊开给人看。
952
+ """
953
+ q = (query or "").strip().lower()
954
+ if not q:
955
+ return {"mode": "human", "confidence": 0.0, "work_score": 0.0, "human_score": 0.0,
956
+ "work_hits": [], "human_hits": [], "mixed": False,
957
+ "reason": "没有话题内容,默认拟人模式"}
958
+ # I-09/F-13:config.topic_signals 允许用户追加自定义信号词(不改源码即可定制)
959
+ extra = (load_config().get("topic_signals") or {}) if not READONLY else {}
960
+ work_words = {w.lower() for w in extra.get("work") or [] if str(w).strip()}
961
+ human_words = {w.lower() for w in extra.get("human") or [] if str(w).strip()}
962
+ for _cat, words in _WORK_SIGNALS.items():
963
+ work_words.update(w.lower() for w in words)
964
+ for _cat, words in _HUMAN_SIGNALS.items():
965
+ human_words.update(w.lower() for w in words)
966
+ work_hits, human_hits = [], []
967
+ for w in sorted(work_words):
968
+ if w in q:
969
+ work_hits.append(w)
970
+ for w in sorted(human_words):
971
+ if w in q:
972
+ human_hits.append(w)
973
+ work_hits = list(dict.fromkeys(work_hits))
974
+ human_hits = list(dict.fromkeys(human_hits))
975
+ work_score, human_score = float(len(work_hits)), float(len(human_hits))
976
+ mixed = bool(work_hits) and bool(human_hits)
977
+ total = work_score + human_score
978
+ if total == 0:
979
+ return {"mode": "human", "confidence": 0.0, "work_score": 0.0, "human_score": 0.0,
980
+ "work_hits": [], "human_hits": [], "mixed": False,
981
+ "reason": "没命中工程或情绪信号,按日常对话处理(human)"}
982
+ # 工程优先:写代码时情绪隔离更安全;混合话题(势均力敌)也归 work,但标注 mixed
983
+ if work_score >= human_score:
984
+ mode = "work"
985
+ confidence = work_score / total
986
+ else:
987
+ mode = "human"
988
+ confidence = human_score / total
989
+ if mixed:
990
+ reason = (f"混合话题:工程信号 {len(work_hits)} 个({'、'.join(work_hits[:5])})"
991
+ f" vs 情绪信号 {len(human_hits)} 个({'、'.join(human_hits[:5])}),"
992
+ f"按工程优先 → {mode}")
993
+ elif mode == "work":
994
+ reason = f"命中工程信号:{'、'.join(work_hits[:6])}"
995
+ else:
996
+ reason = f"命中情绪/关系信号:{'、'.join(human_hits[:6])}"
997
+ return {"mode": mode, "confidence": round(confidence, 2),
998
+ "work_score": work_score, "human_score": human_score,
999
+ "work_hits": work_hits, "human_hits": human_hits,
1000
+ "mixed": mixed, "reason": reason}
1001
+
1002
+
1003
+ def _looks_like_work(query: str) -> bool:
1004
+ """工程/工作场景粗判(保留兼容;内部走打分判定)。"""
1005
+ return analyze_topic(query)["mode"] == "work"
1006
+
1007
+
1008
+ def resolve_mode(query: str = "") -> str:
1009
+ """当前会话模式:work(工程,情绪隔离)还是 human(拟人)。
1010
+
1011
+ config 的 mode:auto = 用 query 自动判定;work/human = 用户明确固定。
1012
+ """
1013
+ m = str(load_config().get("mode", "auto") or "auto").lower()
1014
+ if m in ("work", "human"):
1015
+ return m
1016
+ return analyze_topic(query)["mode"]
1017
+
1018
+
1019
+ def resolve_mode_detail(query: str = "") -> dict:
1020
+ """带判定依据的模式结果(面板 / CLI 用):fixed=用户固定,否则 auto 打分。"""
1021
+ m = str(load_config().get("mode", "auto") or "auto").lower()
1022
+ if m in ("work", "human"):
1023
+ return {"mode": m, "fixed": True, "confidence": 1.0,
1024
+ "work_score": 0.0, "human_score": 0.0, "work_hits": [], "human_hits": [],
1025
+ "mixed": False, "reason": f"用户固定为 {m} 模式"}
1026
+ d = analyze_topic(query)
1027
+ d["fixed"] = False
1028
+ return d
1029
+
1030
+
1031
+ def _behavior_map() -> list:
1032
+ """内部状态 → 说话方式的具体映射。
1033
+
1034
+ 把裸数值翻译成模型能直接照着做的行为约束(而不是只给它看数字)。
1035
+ """
1036
+ m = mood_now()
1037
+ dr = mind_state()
1038
+ cur = dr["curiosity"] if dr["curiosity"] is not None else 50
1039
+ rea = dr["reason"] if dr["reason"] is not None else 50
1040
+ act = []
1041
+ lab, intensity, storm = m.get("label", "平静"), m.get("intensity", 0), m.get("storm")
1042
+ if storm or intensity >= 0.55:
1043
+ act.append(f"现在情绪是「{lab}」且强度 {intensity:.0%}:语气可以自然流露,"
1044
+ "但涉及钱/关系/承诺等大事,把决定权交给用户,别顺着情绪替他拍板。")
1045
+ elif intensity >= 0.25:
1046
+ act.append(f"当前情绪偏「{lab}」({intensity:.0%}):表达可以带底色,但别让它扭曲事实。")
1047
+ else:
1048
+ act.append("情绪平稳:就正常说话。")
1049
+ if not dr["formed"]:
1050
+ act.append("好奇与理智还没成形:多留意用户态度,别急着定性。")
1051
+ else:
1052
+ if cur >= 70:
1053
+ act.append("好奇心正旺:遇到新东西多问一层、多挖一下,别满足于表面答案。")
1054
+ elif cur <= 30:
1055
+ act.append("好奇心偏低:按部就班做事,少发散。")
1056
+ if rea >= 70:
1057
+ act.append("理智在线:先权衡再说,涉及取舍给出明确的利弊。")
1058
+ elif rea <= 30:
1059
+ act.append("理智正在低谷:别做重大决定,拿不准就交给用户。")
1060
+ return act
1061
+
1062
+
1063
+ def _tmp_path(path: Path) -> Path:
1064
+ """临时文件名带 pid + 纳秒,避免多线程/多进程同时写同一文件时互相截断。"""
1065
+ return path.with_name(f"{path.name}.{os.getpid()}.{time.time_ns()}.tmp")
1066
+
1067
+
1068
+ def atomic_json(path: Path, obj) -> None:
1069
+ path.parent.mkdir(parents=True, exist_ok=True)
1070
+ tmp = _tmp_path(path)
1071
+ with open(tmp, "w", encoding="utf-8", newline="\n") as f:
1072
+ json.dump(obj, f, ensure_ascii=False, indent=2)
1073
+ f.flush()
1074
+ os.fsync(f.fileno())
1075
+ _replace_retry(tmp, path)
1076
+
1077
+
1078
+ def atomic_bytes(path: Path, data: bytes) -> None:
1079
+ """二进制原子写:先写临时文件再替换(download zip / 截图缓存用)。"""
1080
+ path.parent.mkdir(parents=True, exist_ok=True)
1081
+ tmp = _tmp_path(path)
1082
+ with open(tmp, "wb") as f:
1083
+ f.write(data)
1084
+ _replace_retry(tmp, path)
1085
+
1086
+
1087
+ # ---------------------------------------------------------------- 上下文压力(v3.57)
1088
+ #
1089
+ # 为什么需要:注入体是固定成本——实测满档约 1214 tokens(`startup` 1922 字符),
1090
+ # 不管上下文还剩多少都照旧注入。上下文快满时这笔开销最不该花:既挤占窗口,又
1091
+ # 让每一轮都更贵。
1092
+ #
1093
+ # 跨进程通道:插件(cordis-plugin/lingshu-cron)在每步 pre-step 能拿到**真实**
1094
+ # 水位(宿主 usage),CLI/引擎拿不到——所以由插件在跨档时把水位写进
1095
+ # `HOME/_pressure.json`,注入侧读它来降档。与 `_meta.json` 同一套"外部可读写状态
1096
+ # 文件"的先例。
1097
+ #
1098
+ # 设计约束:
1099
+ # 1. **读侧永不抛异常**:文件缺失/损坏/过期一律当作"没有压力",注入行为与旧版
1100
+ # 完全一致(默认零行为变化)。
1101
+ # 2. **只降不升**:压力只能让注入更省,不能让注入变大;档位单调,不会来回抖。
1102
+ # 3. 过期保护:超过 `_PRESSURE_TTL` 秒没更新就忽略(进程崩溃留下的陈旧水位不能
1103
+ # 永久压着注入档位)。
1104
+
1105
+ _PRESSURE_FILE = "_pressure.json"
1106
+ _PRESSURE_TTL = 600 # 10 分钟没有新水位即视为失效
1107
+
1108
+ # 档位阈值(百分比)。config 的 pressure 段可覆盖:
1109
+ # {"lazy_at": 70, "minimal_at": 85, "hard_at": 95, "force_at": 98}
1110
+ PRESSURE_DEFAULTS = {"lazy_at": 70, "minimal_at": 85, "hard_at": 95, "force_at": 98}
1111
+
1112
+
1113
+ def pressure_thresholds(cfg: dict | None = None) -> dict:
1114
+ """读 pressure 段的阈值,字段类型不对一律回退默认(宁可不生效也不猜)。"""
1115
+ cfg = cfg if isinstance(cfg, dict) else {}
1116
+ seg = cfg.get("pressure")
1117
+ seg = seg if isinstance(seg, dict) else {}
1118
+ out = dict(PRESSURE_DEFAULTS)
1119
+ for key in PRESSURE_DEFAULTS:
1120
+ val = seg.get(key)
1121
+ if isinstance(val, bool):
1122
+ continue
1123
+ if isinstance(val, (int, float)) and 1 <= float(val) <= 100:
1124
+ out[key] = float(val)
1125
+ # 保证单调,避免用户配出 lazy_at > minimal_at 这种自相矛盾的档位
1126
+ out["minimal_at"] = max(out["minimal_at"], out["lazy_at"])
1127
+ out["hard_at"] = max(out["hard_at"], out["minimal_at"])
1128
+ out["force_at"] = max(out["force_at"], out["hard_at"])
1129
+ return out
1130
+
1131
+
1132
+ def read_pressure(cfg: dict | None = None) -> dict | None:
1133
+ """读当前上下文压力。返回 None 表示"没有压力信号"。
1134
+
1135
+ 返回形状:`{"pct": 78.0, "at": 1795240000, "stale": False, "tier": "lazy"|"minimal"|"full", ...}`
1136
+ """
1137
+ try:
1138
+ path = HOME / _PRESSURE_FILE
1139
+ if not path.exists():
1140
+ return None
1141
+ raw = json.loads(path.read_text(encoding="utf-8-sig"))
1142
+ if not isinstance(raw, dict):
1143
+ return None
1144
+ pct = raw.get("pct")
1145
+ if isinstance(pct, bool) or not isinstance(pct, (int, float)):
1146
+ return None
1147
+ pct = float(pct)
1148
+ if pct < 0 or pct > 100:
1149
+ return None
1150
+ at = raw.get("at")
1151
+ at = float(at) if isinstance(at, (int, float)) and not isinstance(at, bool) else 0.0
1152
+ stale = bool(at and (now_ts() - at > _PRESSURE_TTL))
1153
+ if stale:
1154
+ return {"pct": pct, "at": at, "stale": True, "tier": "full"}
1155
+ th = pressure_thresholds(cfg if cfg is not None else load_config())
1156
+ if pct >= th["minimal_at"]:
1157
+ tier = "minimal"
1158
+ elif pct >= th["lazy_at"]:
1159
+ tier = "lazy"
1160
+ else:
1161
+ tier = "full"
1162
+ return {"pct": pct, "at": at, "stale": False, "tier": tier,
1163
+ "thresholds": th, "source": raw.get("source") if isinstance(raw.get("source"), str) else ""}
1164
+ except Exception:
1165
+ # 坏文件绝不能让注入挂掉:当作没有压力
1166
+ return None
1167
+
1168
+
1169
+ def write_pressure(pct: float, source: str = "") -> None:
1170
+ """写上下文压力(由插件调用;CLI 侧一般不用,留给测试与手工标定)。"""
1171
+ if READONLY:
1172
+ return
1173
+ try:
1174
+ atomic_json(HOME / _PRESSURE_FILE, {
1175
+ "pct": round(float(pct), 1),
1176
+ "at": now_ts(),
1177
+ "source": source or "cli",
1178
+ })
1179
+ except Exception as exc:
1180
+ log_event("pressure", f"写上下文压力失败:{exc}", level="warn")
1181
+
1182
+
1183
+ def clear_pressure() -> None:
1184
+ """清掉压力标记(回到满档)。"""
1185
+ if READONLY:
1186
+ return
1187
+ try:
1188
+ (HOME / _PRESSURE_FILE).unlink(missing_ok=True)
1189
+ except Exception:
1190
+ pass
1191
+
1192
+
1193
+ def _brace_balance(line: str) -> int:
1194
+ """估算一行的括号净深度(忽略字符串内的括号),用于把多行 JSON 块拼回整条。"""
1195
+ depth, in_str, esc = 0, False, False
1196
+ for ch in line:
1197
+ if in_str:
1198
+ if esc:
1199
+ esc = False
1200
+ elif ch == "\\":
1201
+ esc = True
1202
+ elif ch == '"':
1203
+ in_str = False
1204
+ elif ch == '"':
1205
+ in_str = True
1206
+ elif ch in "{[":
1207
+ depth += 1
1208
+ elif ch in "}]":
1209
+ depth -= 1
1210
+ return depth
1211
+
1212
+
1213
+ # 本线程当前持有的写锁:read_jsonl 自愈时若"本线程"已持锁直接修,避免重复抢锁/超时。
1214
+ # 必须带上线程 id:面板是多线程的,同一进程里 A 线程持锁、B 线程来读时不能误以为
1215
+ # "自己也持锁"就跳过互斥直接整文件替换,否则 B 用旧快照覆盖 A 正在写的盘 → 丢数据。
1216
+ _HELD_LOCKS: set = set() # 元素为 (锁文件路径, 线程 id)
1217
+
1218
+
1219
+ def _held(lock: Path) -> bool:
1220
+ return (str(lock), threading.get_ident()) in _HELD_LOCKS
1221
+
1222
+
1223
+ # Windows 瞬时占用类错误:杀软/搜索索引器会在文件刚写完的瞬间短暂持有句柄,
1224
+ # 读操作被拒通常是瞬时的(短退避重试即过),不能当成"文件不存在"或直接放弃。
1225
+ # 5=拒绝访问 32=共享冲突 33=锁冲突 145=目录非空(清理/替换竞态时的表象)。
1226
+ _TRANSIENT_IO_WINERRORS = frozenset({5, 32, 33, 145})
1227
+ _READ_RETRY_ATTEMPTS = 3 # 读重试次数:3 次短退避,最坏约 0.15s,不拖慢正常读
1228
+ _READ_RETRY_DELAY = 0.05 # 首次退避(秒),之后翻倍、封顶 0.5s
1229
+
1230
+
1231
+ def _is_transient_io_error(exc: BaseException) -> bool:
1232
+ """是否属于 Windows 瞬时占用类错误(值得重试);其余错误不重试。"""
1233
+ if isinstance(exc, PermissionError):
1234
+ return True
1235
+ if isinstance(exc, OSError):
1236
+ return getattr(exc, "winerror", None) in _TRANSIENT_IO_WINERRORS
1237
+ return False
1238
+
1239
+
1240
+ def _read_jsonl_text(path: Path, attempts: int | None = None,
1241
+ delay: float | None = None) -> str | None:
1242
+ """读 JSONL 原文:判存在性与读取都带瞬时占用重试。
1243
+
1244
+ 返回 None 只代表"文件确实不存在";"读不到"(瞬时占用重试耗尽)抛异常。
1245
+ 旧实现 `if not path.exists(): return []` 会把 Windows 上 stat 被拒的瞬时错误
1246
+ 当成文件不存在 → 上层静默读到空库;这里两者必须分开,绝不降级成空列表。
1247
+ """
1248
+ attempts = _READ_RETRY_ATTEMPTS if attempts is None else max(1, int(attempts))
1249
+ delay = _READ_RETRY_DELAY if delay is None else max(0.0, float(delay))
1250
+ last_exc: OSError | None = None
1251
+ for attempt in range(attempts):
1252
+ try:
1253
+ if not path.exists():
1254
+ return None
1255
+ # utf-8-sig:兼容 Windows 编辑器 / 脚本写出的带 BOM 文件,BOM 不该把首行变成"坏行"
1256
+ return path.read_text(encoding="utf-8-sig")
1257
+ except OSError as exc:
1258
+ if not _is_transient_io_error(exc):
1259
+ raise # 非瞬时错误(文件被删/读取异常等):原样抛,不掩盖
1260
+ last_exc = exc
1261
+ if attempt + 1 >= attempts:
1262
+ break
1263
+ time.sleep(delay)
1264
+ delay = min(delay * 2, 0.5)
1265
+ # 重试耗尽:仍然是"读不到",明确抛出并记日志;返回 [] 等于把故障伪装成空库。
1266
+ assert last_exc is not None
1267
+ try:
1268
+ log_event("io", f"读 {path.name} 失败:瞬时占用重试 {attempts} 次仍无果"
1269
+ f"({last_exc}),不当作空库", level="error", path=path.name)
1270
+ except Exception:
1271
+ pass # 日志失败不能盖住真正的读错误
1272
+ raise last_exc
1273
+
1274
+
1275
+ def read_jsonl(path: Path) -> list:
1276
+ raw = _read_jsonl_text(path)
1277
+ if raw is None:
1278
+ return []
1279
+ out, bad_blocks = [], []
1280
+ # 只读环境(E-06):修不了坏块也无法写 .corrupt,同一坏块每次读取都会重报。
1281
+ # 模块级按 (文件名, 块内容) 去重,同一坏块只告警一次。
1282
+ _corrupt_reported: set = getattr(read_jsonl, "_corrupt_reported", None)
1283
+ if _corrupt_reported is None:
1284
+ _corrupt_reported = read_jsonl._corrupt_reported = set()
1285
+ lines = raw.splitlines()
1286
+ i, n = 0, len(lines)
1287
+ while i < n:
1288
+ line = lines[i].strip()
1289
+ if not line:
1290
+ i += 1
1291
+ continue
1292
+ try:
1293
+ out.append(json.loads(line))
1294
+ i += 1
1295
+ continue
1296
+ except Exception:
1297
+ pass
1298
+ # 单行解析失败:可能是多行格式化 JSON。按括号配对把整块累积起来再试,
1299
+ # 避免把一条跨行合法记录当成坏行丢掉。
1300
+ block = [lines[i]]
1301
+ depth = _brace_balance(lines[i])
1302
+ i += 1
1303
+ while i < n and depth > 0 and len(block) < 200:
1304
+ block.append(lines[i])
1305
+ depth += _brace_balance(lines[i])
1306
+ i += 1
1307
+ joined = "\n".join(block).strip()
1308
+ try:
1309
+ obj = json.loads(joined)
1310
+ if isinstance(obj, dict):
1311
+ out.append(obj)
1312
+ continue
1313
+ except Exception:
1314
+ pass
1315
+ bad_blocks.append(joined)
1316
+ if bad_blocks:
1317
+ # E-06:只读环境修不了,内存内去重——同一坏块每次读取只告警一次
1318
+ fresh_blocks = [b for b in bad_blocks
1319
+ if (path.name, b.rstrip()) not in _corrupt_reported]
1320
+ for b in bad_blocks:
1321
+ _corrupt_reported.add((path.name, b.rstrip()))
1322
+ if not fresh_blocks:
1323
+ return out
1324
+ # 有损坏块:好记录写回,坏块原样(可含多行)挪到 .corrupt 备份,
1325
+ # 绝不静默当作没发生、也不让后续保存把它们永久抹掉。
1326
+ log_event("parse", f"{path.name} 有 {len(fresh_blocks)} 个坏块,已挪到 .corrupt 备份",
1327
+ level="warn", path=path.name)
1328
+ # v3.76(#23):**只读环境下,读路径绝不写盘**。原来这里无条件
1329
+ # append .corrupt + os.replace 覆盖原文件——用户 --ro 时"读"竟会改写
1330
+ # 记忆库;且下面的 try/except pass 吞掉一切失败。只读时仅告警返回。
1331
+ if READONLY:
1332
+ try:
1333
+ log_event("parse", f"{path.name} 只读环境,坏块仅告警不落盘(原文件保留)",
1334
+ level="warn", path=path.name)
1335
+ except Exception:
1336
+ pass
1337
+ return out
1338
+ try:
1339
+ corrupt = path.with_name(path.name + ".corrupt")
1340
+ tmp = _tmp_path(path)
1341
+ lock = path.with_name(path.name + ".lock")
1342
+ # 自愈=替代整文件。下面的 raw 来自函数开头(抢锁前)的读取——若期间
1343
+ # 别的进程写了新数据,直接 replace 会把新数据覆盖丢(丢更新)。
1344
+ # v3.76(#23):**replace 前在锁内重读盘上内容**,与开头读到的不一致
1345
+ # 就放弃本次自愈(.corrupt 也不写,坏块下次还能被识别重试)。
1346
+ def _replace_if_unchanged():
1347
+ current = _read_jsonl_text(path)
1348
+ if current != raw:
1349
+ try:
1350
+ os.unlink(tmp)
1351
+ except OSError:
1352
+ pass
1353
+ log_event("parse", f"{path.name} 自愈时文件已变,跳过覆盖(避免丢更新)",
1354
+ level="warn", path=path.name)
1355
+ return False
1356
+ # 确认要覆盖了才把坏块挪进 .corrupt:否则去重表会记住"已报过",
1357
+ # 而原文件没修,坏块就再也不会被处理。
1358
+ try:
1359
+ existing = corrupt.read_text(encoding="utf-8", errors="ignore") if corrupt.exists() else ""
1360
+ except OSError:
1361
+ existing = ""
1362
+ fresh = [b for b in bad_blocks if b.rstrip() not in existing]
1363
+ if fresh:
1364
+ with open(corrupt, "a", encoding="utf-8", newline="\n") as cf:
1365
+ for b in fresh:
1366
+ cf.write(b.rstrip() + "\n---\n")
1367
+ with open(tmp, "w", encoding="utf-8", newline="\n") as f:
1368
+ for r in out:
1369
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
1370
+ os.replace(tmp, path)
1371
+ return True
1372
+
1373
+ if not _held(lock):
1374
+ try:
1375
+ with _locked(path, timeout=0.5):
1376
+ _replace_if_unchanged()
1377
+ except TimeoutError:
1378
+ try:
1379
+ os.unlink(tmp)
1380
+ except OSError:
1381
+ pass
1382
+ else:
1383
+ _replace_if_unchanged()
1384
+ except Exception as exc:
1385
+ # v3.76(#23):自愈失败不再静默——坏块仍在原文件里、没丢数据,但
1386
+ # 必须留痕,否则永远不知道坏块为什么一直没修好。
1387
+ try:
1388
+ log_event("parse", f"{path.name} 坏块自愈失败(原文件保留):{exc}",
1389
+ level="warn", path=path.name)
1390
+ except Exception:
1391
+ pass
1392
+ return out
1393
+
1394
+
1395
+ def write_text_atomic(path: Path, text: str) -> None:
1396
+ """整文件文本写入走 tmp + os.replace:直接 write_text 中途崩溃/被占用
1397
+ 会留半截文件(梦境报告、AGENTS.md 这类被宿主解析的文件半截更糟)。"""
1398
+ path.parent.mkdir(parents=True, exist_ok=True)
1399
+ tmp = _tmp_path(path)
1400
+ with open(tmp, "w", encoding="utf-8", newline="\n") as f:
1401
+ f.write(text)
1402
+ _replace_retry(tmp, path)
1403
+
1404
+
1405
+ def _replace_retry(tmp: Path, path: Path) -> None:
1406
+ """os.replace 覆盖,遇 Windows 文件占用按指数退避重试;最终失败则清掉 tmp 并抛出。
1407
+
1408
+ Windows 上 os.replace 覆盖"正被别的进程打开读取"的文件会抛 PermissionError。
1409
+ 写方之间有锁互斥,但读方(stats/recall/面板)不加锁;退避等待读句柄释放。
1410
+ 指数退避:0.05s 起步每次翻倍,封顶 0.6s,总预算约 10s——实测防病毒/索引器
1411
+ 持读句柄能超过 4s,固定 12×短间隔的重试扛不住这种长占用。
1412
+ """
1413
+ delay = 0.05
1414
+ deadline = time.time() + 10.0
1415
+ attempt = 0
1416
+ while True:
1417
+ try:
1418
+ os.replace(tmp, path)
1419
+ return
1420
+ except PermissionError:
1421
+ attempt += 1
1422
+ if time.time() >= deadline:
1423
+ log_event("io", f"写 {path.name} 失败:文件被占用,重试 {attempt} 次"
1424
+ f"(约 10s)仍无果,可能有进程长期持有读句柄",
1425
+ level="error", path=path.name)
1426
+ try:
1427
+ os.unlink(tmp)
1428
+ except OSError:
1429
+ pass
1430
+ raise
1431
+ time.sleep(delay)
1432
+ delay = min(delay * 2, 0.6)
1433
+
1434
+
1435
+ def write_jsonl(path: Path, rows: list) -> None:
1436
+ path.parent.mkdir(parents=True, exist_ok=True)
1437
+ tmp = _tmp_path(path)
1438
+ try:
1439
+ # v3.02 #25:只有记忆层文件封哈希链——write_jsonl 还服务 history/knowledge 等,
1440
+ # 无差别封链会往别的文件里塞 h/p_h。非记忆文件、桥接前(无 _seal_chain)都跳过。
1441
+ if path.name in ("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl", "archive.jsonl"):
1442
+ _seal_chain(rows)
1443
+ except NameError:
1444
+ pass
1445
+ with open(tmp, "w", encoding="utf-8", newline="\n") as f:
1446
+ for r in rows:
1447
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
1448
+ _replace_retry(tmp, path)
1449
+
1450
+
1451
+ def _append_jsonl(path: Path, row: dict) -> None:
1452
+ """追加一行 JSONL(v3.02 #5 metrics.jsonl 用):写锁防多进程交错半行。"""
1453
+ path.parent.mkdir(parents=True, exist_ok=True)
1454
+ with _locked(path):
1455
+ with open(path, "a", encoding="utf-8", newline="\n") as f:
1456
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
1457
+
1458
+
1459
+ @contextmanager
1460
+ def _locked(path: Path, timeout: float = 10.0):
1461
+ """跨进程写锁:用独占创建 lock 文件互斥,带超时与陈旧锁清理。
1462
+
1463
+ 没有锁时两个进程同时 read-modify-write 会互相覆盖(后写者赢,先写者丢)。
1464
+ Windows 上没有 flock,用 O_CREAT|O_EXCL 保证只有一个进程能创建锁文件。
1465
+ 锁文件里写持有者 pid:解锁时只删自己那把,避免「持锁超时被接管后,
1466
+ 自己退出时把接管者的锁删掉」——那会让第三个进程立刻挤进来一起写。
1467
+ """
1468
+ lock = path.with_name(path.name + ".lock")
1469
+ if _held(lock):
1470
+ # 本线程已持锁:重入,避免 update_persona → save_persona 这类嵌套把自己锁死
1471
+ yield
1472
+ return
1473
+ # 父目录不存在时 os.open 会抛 FileNotFoundError(新 HOME/测试隔离环境常见);
1474
+ # 锁是"写盘前最后一步",这里补建目录比让调用方炸掉更合适。
1475
+ try:
1476
+ lock.parent.mkdir(parents=True, exist_ok=True)
1477
+ except OSError:
1478
+ pass
1479
+ deadline = time.time() + timeout
1480
+ acquired = False
1481
+ _owns = False
1482
+ try:
1483
+ while True:
1484
+ try:
1485
+ fd = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
1486
+ # #24 多宿主可见:锁里同时记 pid 与主机名(空格分隔)。
1487
+ # _lock_owner 只取 split()[0],旧格式/新格式都兼容;
1488
+ # 记忆库放在网盘/共享目录时,能看出是"另一台机器"在写。
1489
+ os.write(fd, f"{os.getpid()} {_HOSTNAME}".encode())
1490
+ os.close(fd)
1491
+ _HELD_LOCKS.add((str(lock), threading.get_ident())) # 记住"本线程已持锁",read_jsonl 自愈时避免重复抢锁
1492
+ acquired = True
1493
+ break
1494
+ except FileExistsError:
1495
+ # 陈旧锁(持锁进程已死):久到不可能是正常写盘(正常持锁 <2s)才接管。
1496
+ # 阈值别设太小:dream 整理记忆时持锁会久一点,抢早了就是两个进程同时写。
1497
+ try:
1498
+ if time.time() - lock.stat().st_mtime > STALE_LOCK_SECONDS:
1499
+ # 再加一道 pid 探活:持锁进程还活着就别抢(work_flush/dream 可能持锁较久)。
1500
+ # 同进程(含本进程其它线程)持有的锁一律视为"活着",绝不接管。
1501
+ owner = _lock_owner(lock)
1502
+ if owner is not None and _pid_alive(owner):
1503
+ pass # 活着的持锁者:继续等,不接管
1504
+ else:
1505
+ try:
1506
+ lock.unlink()
1507
+ except OSError:
1508
+ pass
1509
+ continue
1510
+ except OSError:
1511
+ pass
1512
+ if time.time() > deadline:
1513
+ log_event("lock", f"等不到写锁:{path.name}({timeout:.0f}s 超时)", level="error", path=path.name)
1514
+ raise TimeoutError(f"等不到写锁:{path}")
1515
+ time.sleep(0.05)
1516
+ yield
1517
+ finally:
1518
+ # 持锁登记必须覆盖所有路径:正常释放、超时、异常都会回到这里。
1519
+ # 只要登记过就清掉,避免长跑进程的锁表缓慢累积、同线程后续 _held()
1520
+ # 误判"自己还持着锁"而跳过互斥。超时发生在登记之前(还没拿到锁),
1521
+ # 此时没有登记可清;放进同一 try/finally 是为了让"登记→清理"边界不依赖后续改动。
1522
+ if acquired:
1523
+ _HELD_LOCKS.discard((str(lock), threading.get_ident()))
1524
+ # 只在"自己成功创建或接管了锁(写入了自己 pid)"时才释放。
1525
+ # 锁文件已不存在(被陈旧锁接管流程删掉)→ 直接跳过,不留告警也不误删。
1526
+ # 注意:finally 里不能再 return——那会把调用方正在向上抛的异常一起吞掉。
1527
+ if acquired and lock.exists():
1528
+ # _lock_owner 读不到内容返回 None 时不删——那可能是其他进程刚接管/正在写
1529
+ # 锁文件,误删会让第三个进程立刻挤进来一起写。
1530
+ if _lock_owner(lock) == os.getpid():
1531
+ _owns = True # 锁文件里确实记着自己是持有者
1532
+ if _owns:
1533
+ try:
1534
+ lock.unlink()
1535
+ except FileNotFoundError:
1536
+ pass # 锁文件刚被别的流程删掉:无需处理
1537
+ except OSError:
1538
+ pass
1539
+ else:
1540
+ log_event("lock", f"释放跳过:锁 {path.name} 不归本进程(pid 不符或读不到持有者)", path=path.name)
1541
+
1542
+
1543
+ STALE_LOCK_SECONDS = 30.0
1544
+
1545
+
1546
+ def _pid_alive(pid: int) -> bool:
1547
+ """探测 pid 是否还活着(Windows/POSIX 通用)。拿不到权限等异常时保守认为"活着",
1548
+ 以免把别人的活锁当陈旧锁抢走。"""
1549
+ if pid <= 0:
1550
+ return False
1551
+ try:
1552
+ if os.name == "nt":
1553
+ import ctypes
1554
+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
1555
+ kernel32 = ctypes.windll.kernel32
1556
+ h = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
1557
+ if not h:
1558
+ # 打不开句柄(权限拒绝/跨会话):保守视为存活,避免误判陈旧锁抢走别人的锁
1559
+ return True
1560
+ code = ctypes.c_ulong()
1561
+ ok = kernel32.GetExitCodeProcess(h, ctypes.byref(code))
1562
+ kernel32.CloseHandle(h)
1563
+ return bool(ok) and code.value == 259 # STILL_ACTIVE
1564
+ os.kill(pid, 0)
1565
+ return True
1566
+ except ProcessLookupError:
1567
+ return False
1568
+ except PermissionError:
1569
+ return True # 探测被拒绝(跨会话等):保守视为存活
1570
+ except (OSError, Exception):
1571
+ return True
1572
+
1573
+
1574
+ def _lock_owner(lock: Path) -> int | None:
1575
+ """读锁文件里记录的持有者 pid;读不到/格式不对返回 None。"""
1576
+ try:
1577
+ raw = lock.read_text(encoding="utf-8", errors="ignore").strip()
1578
+ return int(raw.split()[0]) if raw else None
1579
+ except (OSError, ValueError, IndexError):
1580
+ return None
1581
+
1582
+
1583
+ def lock_writers() -> list[dict]:
1584
+ """#24 列出当前持锁的写入者(文件 / pid / 主机名 / 是否活着)。
1585
+
1586
+ 记忆库放在共享盘时,同一份数据可能被多台机器同时写;这里把锁文件里
1587
+ 记下的 host 读出来,让面板和 `status` 能直接看见"谁在写"。
1588
+ """
1589
+ rows = []
1590
+ try:
1591
+ locks = sorted(HOME.glob("*.lock"))
1592
+ except OSError:
1593
+ return rows
1594
+ for lock in locks:
1595
+ try:
1596
+ raw = lock.read_text(encoding="utf-8", errors="ignore").strip().lstrip("\ufeff")
1597
+ except OSError:
1598
+ continue
1599
+ if not raw:
1600
+ continue
1601
+ parts = raw.split()
1602
+ try:
1603
+ pid = int(parts[0])
1604
+ except (ValueError, IndexError):
1605
+ continue
1606
+ host = parts[1] if len(parts) > 1 else ""
1607
+ rows.append({
1608
+ "file": lock.name[:-5] if lock.name.endswith(".lock") else lock.name,
1609
+ "pid": pid,
1610
+ "host": host,
1611
+ "alive": _pid_alive(pid) and (not host or host == _HOSTNAME),
1612
+ })
1613
+ return rows
1614
+
1615
+
1616
+
1617
+ def _persona_txn(fn):
1618
+ """把「读人格 → 改 → 写回」整段放进 persona.json 的写锁里。
1619
+ 否则两个并发的改动各自 load 一份旧档、后写者把先写者的字段覆盖回旧值。
1620
+ 锁对同线程可重入,所以内部再调 save_persona 不会自锁。"""
1621
+ def wrapper(*args, **kwargs):
1622
+ with _locked(HOME / "persona.json"):
1623
+ return fn(*args, **kwargs)
1624
+ wrapper.__name__ = getattr(fn, "__name__", "persona_txn")
1625
+ wrapper.__doc__ = fn.__doc__
1626
+ return wrapper
1627
+
1628
+
1629
+ def _locked_save_all(records: list) -> None:
1630
+ """save_all 的加锁版:并发写记忆不丢更新。"""
1631
+ with _locked(HOME / "hippocampus.jsonl"):
1632
+ existing = load_all()
1633
+ by_id = {}
1634
+ no_id = [] # 缺 id 的畸形记录也原样保留,不能因为无法索引就悄悄丢掉
1635
+ for m in existing:
1636
+ mid = m.get("id")
1637
+ if mid:
1638
+ by_id[mid] = m
1639
+ else:
1640
+ no_id.append(m)
1641
+ for r in records:
1642
+ mid = r.get("id")
1643
+ if mid:
1644
+ by_id[mid] = r
1645
+ merged = list(by_id.values()) + no_id
1646
+ save_all(merged)
1647
+
1648
+
1649
+ def _strengthen_write(touched: list) -> None:
1650
+ """recall 强化后的定向写回:只重写被"想起"记忆所在的层文件。
1651
+
1652
+ 上万条记忆时,旧实现(_locked_save_all 整库 merge + 全量重写 3 个文件)让每次
1653
+ recall 都背上整库 I/O;这里按层分组、只 patch 命中的行,开销与命中数成正比。
1654
+
1655
+ 注意只 patch 强化字段:touched 里的记录是 recall 开头无锁读的旧快照,
1656
+ 若整条 update 回去,会把期间别人并发写入的 review/layer/tags 用旧值覆盖掉
1657
+ (例:刚 review confirm 的记忆被 recall 一碰又回到 pending)。
1658
+
1659
+ 跨层竞态防护:recall 锁外读快照后,dream/archive 可能已把记忆迁移层。
1660
+ 所以锁内以旧快照的 layer 为起点重读目标文件做定向 patch——若 id 不在
1661
+ 旧 layer,按 hippo→cortex→dust 顺序在其他层找它的实际位置再 patch;
1662
+ 全找不到(可能已被归档/删除)则放弃并留日志,绝不往旧 layer 写回去。
1663
+ """
1664
+ if READONLY or not touched:
1665
+ return
1666
+ patch_fields = ("access_count", "stability", "last_access",
1667
+ "used_count", "used_at", "used_hits")
1668
+ # detail 特殊处理:不能用锁外旧快照回写(会把 dream 的淡化抵消掉),
1669
+ # 改成 patch 时以盘上现值为基点重算巩固(0.9 保留 + 0.1 回升),
1670
+ # 公式与 memory.recall 的强化逻辑保持一致,落盘结果与快照值无关。
1671
+ DETAIL_CONSOLIDATE = ("detail", lambda v: min(1.0, _num(v, 1.0) * 0.9 + 0.1))
1672
+ # detail 以盘上现值重算巩固(详见上面 DETAIL_CONSOLIDATE 注释);
1673
+ # 旧注释保留历史背景:快照 detail 确实不可直接回写。
1674
+ with _locked(HOME / "hippocampus.jsonl"):
1675
+ updates: dict = {}
1676
+ for m in touched:
1677
+ if m.get("layer") == ARCHIVE_LAYER:
1678
+ continue # 归档记忆只读展示,不给强化(需要时 archive restore 回热)
1679
+ if not m.get("id"):
1680
+ continue # 畸形记录(缺 id)没法强化
1681
+ updates[m["id"]] = m
1682
+ if not updates:
1683
+ return
1684
+ fname = {"hippo": "hippocampus.jsonl", "cortex": "cortex.jsonl", "dust": "dust.jsonl"}
1685
+ order = ("hippo", "cortex", "dust")
1686
+ # 每层文件只读一次:patch 该层命中的 id,并把别的层没找到的记到这里
1687
+ remaining = dict(updates)
1688
+ for layer in order:
1689
+ if not remaining:
1690
+ break
1691
+ p = HOME / fname[layer]
1692
+ rows = read_jsonl(p)
1693
+ hit_ids = set()
1694
+ for r in rows:
1695
+ u = remaining.get(r.get("id"))
1696
+ if u:
1697
+ hit_ids.add(r["id"])
1698
+ for f in patch_fields:
1699
+ if f in u:
1700
+ r[f] = u[f]
1701
+ # detail:以盘上现值巩固,而非快照旧值(不抵消 dream 淡化)
1702
+ fname_, fn = DETAIL_CONSOLIDATE
1703
+ r[fname_] = round(fn(r.get(fname_)), 4)
1704
+ if hit_ids:
1705
+ write_jsonl(p, rows)
1706
+ for mid in hit_ids:
1707
+ del remaining[mid]
1708
+ for mid in remaining:
1709
+ log_event("strengthen", f"放弃强化 {mid}:三层都找不到(可能已归档/删除)", path=fname["hippo"])
1710
+
1711
+
1712
+ def _patch_memory_fields(rec: dict) -> bool:
1713
+ """v3.02 #10:定向 patch 保质期字段(review_by/review_by_confirmed/ttl_days)。
1714
+
1715
+ 与 _strengthen_write 同一套锁内按层找 id 的套路,但只写保质期相关字段,
1716
+ 不碰强化计数字段——语义不同的事各走各的补丁,互不覆盖。
1717
+ 找不到(已归档/删除)返回 False 并留日志。
1718
+ """
1719
+ if READONLY or not rec.get("id"):
1720
+ return False
1721
+ patch_fields = ("ttl_days", "review_by", "review_by_confirmed")
1722
+ fname = {"hippo": "hippocampus.jsonl", "cortex": "cortex.jsonl", "dust": "dust.jsonl",
1723
+ ARCHIVE_LAYER: "archive.jsonl"}
1724
+ for layer in ("hippo", "cortex", "dust", ARCHIVE_LAYER):
1725
+ p = HOME / fname[layer]
1726
+ rows = read_jsonl(p)
1727
+ for r in rows:
1728
+ if r.get("id") == rec["id"]:
1729
+ for f in patch_fields:
1730
+ if f in rec:
1731
+ r[f] = rec[f]
1732
+ write_jsonl(p, rows)
1733
+ return True
1734
+ log_event("memory", f"放弃复核确认 {rec['id']}:各层都找不到", level="warn")
1735
+ return False
1736
+
1737
+
1738
+ # ---------------------------------------------------------------- 回忆使用反馈
1739
+ # "存得好不好"不能只看条数:注入的记忆到底有没有被用上、哪些记忆从没被命中过,
1740
+ # 这两个便宜计数才能回答"分层 + 遗忘曲线"是否真的让记忆更准。
1741
+ RETRIEVAL_FILE = HOME / "last_retrieval.json"
1742
+ USAGE_FILE = HOME / "recall_usage.jsonl"
1743
+ USAGE_MIN_SHARED = 2 # 与回复共享的关键词元至少 2 个
1744
+ USAGE_MIN_RATIO = 0.08 # 且至少覆盖记忆词元的 8%(粗判,不追求精确)
1745
+
1746
+ # 常用虚词二元组:它们在哪句话里都出现,不能算"用上了这条记忆"
1747
+ _USAGE_STOP = {
1748
+ "我们", "你们", "他们", "这个", "那个", "就是", "什么", "因为", "所以",
1749
+ "但是", "可以", "已经", "不是", "没有", "一个", "自己", "现在", "时候",
1750
+ "这样", "如果", "还是", "然后", "觉得", "知道", "需要", "应该", "一下",
1751
+ "一些", "的话", "真的", "非常", "比较", "而且", "或者", "不过", "其中",
1752
+ "以及", "对于", "关于", "之后", "之前", "这种", "那种", "一直", "可能",
1753
+ }
1754
+
1755
+
1756
+ def _home_writable(max_attempts: int = 3) -> bool:
1757
+ """探测 HOME 是否可写:mkdir + 探针文件。失败即只读降级。
1758
+
1759
+ 重试 max_attempts 次(间隔 150ms):Windows 杀软/搜索索引常短暂占用目录
1760
+ 句柄,单次探测失败就降级会把整个进程误判成只读——AI 会话里表现为
1761
+ "能读不能写",而目录实际完全可写。
1762
+
1763
+ 注意:探针文件清理失败**不能**算作不可写。Windows 上杀毒/索引服务常会在
1764
+ 文件刚写完的瞬间持有句柄,unlink 抛 PermissionError——旧实现把这一步失败
1765
+ 也当成只读,导致面板一启动就误挂「只读模式」横幅(实际目录完全可写)。
1766
+ 写入成功即证明可写,清理只是尽力而为。
1767
+ """
1768
+ last_exc = None
1769
+ for attempt in range(max(1, int(max_attempts))):
1770
+ probe = None
1771
+ try:
1772
+ HOME.mkdir(parents=True, exist_ok=True)
1773
+ # 唯一文件名:避免并发实例(面板 + CLI)共用同一个探针互相踩
1774
+ probe = HOME / f".write-probe-{os.getpid()}-{int(time.time() * 1000)}"
1775
+ probe.write_text("ok", encoding="utf-8")
1776
+ return True
1777
+ except Exception as exc:
1778
+ last_exc = exc
1779
+ if attempt + 1 < max(1, int(max_attempts)):
1780
+ time.sleep(0.15)
1781
+ finally:
1782
+ if probe is not None:
1783
+ try:
1784
+ probe.unlink(missing_ok=True)
1785
+ except OSError:
1786
+ pass # 清理失败不影响可写性判定
1787
+ # 最终失败的原因留痕:区分沙箱拒写 / 杀软占用 / 真权限问题,免得排查靠猜
1788
+ try:
1789
+ log_event("core", f"HOME 不可写,只读降级(重试 {max_attempts} 次均失败):{last_exc}",
1790
+ level="warn")
1791
+ except Exception:
1792
+ pass
1793
+ return False
1794
+
1795
+
1796
+ def _resolve_readonly(forced: bool = False) -> None:
1797
+ """确定最终只读状态:--ro 或 BRAIN_MEMORY_READONLY=1 强制只读;
1798
+ BRAIN_MEMORY_READONLY=0 强制可写(跳过探测——确认目录可写、但自动探测
1799
+ 被环境干扰误报时用手动覆盖);否则自动探测。"""
1800
+ global READONLY, READONLY_FORCED
1801
+ env = os.environ.get("BRAIN_MEMORY_READONLY", "").strip()
1802
+ if forced or env == "1":
1803
+ READONLY = True
1804
+ READONLY_FORCED = True
1805
+ elif env == "0":
1806
+ READONLY = False
1807
+ READONLY_FORCED = False
1808
+ else:
1809
+ READONLY = not _home_writable()
1810
+ READONLY_FORCED = False # 自动降级,面板可自愈
1811
+ _sync_state()
1812
+
1813
+
1814
+ def _extract_ro(argv: list) -> tuple:
1815
+ """从参数里挑出 --ro/--no-write,返回 (剩余参数, 是否强制只读)。"""
1816
+ out, forced = [], False
1817
+ for a in argv:
1818
+ if a in ("--ro", "--no-write", "-r"):
1819
+ forced = True
1820
+ else:
1821
+ out.append(a)
1822
+ return out, forced
1823
+
1824
+
1825
+ def _rebind_paths() -> None:
1826
+ """按当前 HOME 重算所有派生路径常量(纯赋值,不触发跨模块同步)。"""
1827
+ global LOG_FILE, WORKING_FILE, VERBATIM_DIR, ASSOC_FILE, PERSONA_SNAP_DIR, DAILY_FILE
1828
+ global RETRIEVAL_FILE, USAGE_FILE, CONSENT_FILE, TOPIC_FILE, SESSIONS_DIR
1829
+ LOG_FILE = HOME / "lingshu.log"
1830
+ WORKING_FILE = HOME / "working.jsonl"
1831
+ TOPIC_FILE = HOME / "topics.jsonl"
1832
+ VERBATIM_DIR = HOME / "verbatim"
1833
+ ASSOC_FILE = HOME / "assoc.jsonl"
1834
+ PERSONA_SNAP_DIR = HOME / "persona_snapshots"
1835
+ DAILY_FILE = HOME / "daily_state.json"
1836
+ RETRIEVAL_FILE = HOME / "last_retrieval.json"
1837
+ USAGE_FILE = HOME / "recall_usage.jsonl"
1838
+ CONSENT_FILE = HOME / "consent.json"
1839
+ SESSIONS_DIR = HOME / "sessions"
1840
+
1841
+
1842
+ def _recompute_paths() -> None:
1843
+ """集中重算由 HOME 派生的路径,再同步给各子模块(--home 切换后必须调用)。"""
1844
+ _rebind_paths()
1845
+ _sync_state()
1846
+
1847
+
1848
+ # ---------------------------------------------------------------- 只读回放支撑(候选5)
1849
+
1850
+ _FINGERPRINT_FILES = ("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl", "archive.jsonl",
1851
+ "persona.json", "persona_snapshots.jsonl", "emotions.jsonl",
1852
+ "topics.jsonl", "working.jsonl", "assoc.jsonl",
1853
+ "lingshu.user.md", "config.json", "verbatim")
1854
+
1855
+
1856
+ def data_fingerprint() -> str:
1857
+ """数据目录关键文件的轻量指纹(只读回放前后一致性校验用)。
1858
+
1859
+ 只看数据文件,不看日志(lingshu.log 会被正常操作追加)。
1860
+ 用 size+mtime_ns 而非全文哈希:回放只读时两者都不变,足够判"没写库"。
1861
+ """
1862
+ h = hashlib.sha1()
1863
+ for name in _FINGERPRINT_FILES:
1864
+ f = HOME / name
1865
+ try:
1866
+ if f.is_dir():
1867
+ for sub in sorted(f.rglob("*")):
1868
+ if sub.is_file():
1869
+ st = sub.stat()
1870
+ h.update(f"{sub.relative_to(HOME)}:{st.st_size}:{st.st_mtime_ns}\n".encode())
1871
+ elif f.is_file():
1872
+ st = f.stat()
1873
+ h.update(f"{name}:{st.st_size}:{st.st_mtime_ns}\n".encode())
1874
+ except OSError:
1875
+ pass
1876
+ return h.hexdigest()
1877
+
1878
+
1879
+ @contextmanager
1880
+ def readonly_scope():
1881
+ """临时只读:期间所有按 READONLY 判断的写入路径被跳过(回放/自检用)。
1882
+
1883
+ 拆分后每个子模块各持一份 READONLY 副本,必须经 _sync_state() 统一回灌;
1884
+ 退出时恢复原值(原本就只读时保持只读)。
1885
+ """
1886
+ prev = READONLY
1887
+ globals()["READONLY"] = True
1888
+ _sync_state()
1889
+ try:
1890
+ yield
1891
+ finally:
1892
+ globals()["READONLY"] = prev
1893
+ _sync_state()
1894
+
1895
+
1896
+ def _override_home(argv: list) -> list:
1897
+ """提取 --home <目录>/--home=<目录>,全局切换数据目录(任意位置均可)。
1898
+ 同时写入环境变量,保证之后 import 的 growth 子系统读到同一个 HOME。"""
1899
+ global HOME
1900
+ out, i, home = [], 0, None
1901
+ while i < len(argv):
1902
+ a = argv[i]
1903
+ if a == "--home" and i + 1 < len(argv):
1904
+ home = argv[i + 1]
1905
+ i += 2
1906
+ continue
1907
+ if a.startswith("--home="):
1908
+ home = a.split("=", 1)[1]
1909
+ i += 1
1910
+ continue
1911
+ out.append(a)
1912
+ i += 1
1913
+ if home:
1914
+ HOME = Path(home).expanduser()
1915
+ _recompute_paths()
1916
+ os.environ["BRAIN_MEMORY_HOME"] = str(HOME)
1917
+ return out
1918
+
1919
+
1920
+ # ---------------------------------------------------------------- 拆分后状态同步
1921
+ # v2.22 起代码按领域拆到 memory/emotion/persona/dream/cli,各模块在 import 时
1922
+ # 从 core 复制了一份 HOME/READONLY/派生路径。--home / --ro 切换后必须把 core 的
1923
+ # 最新状态回灌给所有子模块,否则它们仍在读写旧目录(单文件时天然共享,拆分后不会)。
1924
+ _SYNC_TARGETS: list = []
1925
+
1926
+
1927
+ def _sync_state() -> None:
1928
+ """把 core 的当前全局状态同步到各子模块(brain.py 启动时登记同步目标)。
1929
+
1930
+ 先按当前 HOME 重算派生路径:这样调用方只改了 core.HOME 再调本函数时
1931
+ (测试/宿主/面板迁移都会这么用)也不会把旧目录的路径同步出去。
1932
+ """
1933
+ _rebind_paths()
1934
+ if not _SYNC_TARGETS:
1935
+ return
1936
+ snap = {k: v for k, v in dict(globals()).items() if not k.startswith("__")}
1937
+ for m in _SYNC_TARGETS:
1938
+ m.__dict__.update(snap)
1939
+ # growth.py 不在 _SYNC_TARGETS(它在 brain 之后 import brain,会形成循环导入),
1940
+ # 但它缓存了 HOME 与一批派生路径常量;这里 import 一次并调用它的重算入口,
1941
+ # 让 --home 切换后 growth 的 knowledge/notes/skills 等路径也指向新目录
1942
+ # (已在 sys.modules 里则零开销,首次 import 只是延后到现在,链路不变)。
1943
+ try:
1944
+ import growth # noqa: E402
1945
+ growth._recompute_home()
1946
+ except Exception:
1947
+ pass # growth 未部署/导入失败:沿用原值,不影响记忆主链路
1948
+
1949
+
1950
+ # ---------------------------------------------------------------- 可选 embedding / rerank(P1)
1951
+ # 零依赖铁律:这两个能力"装了 Ollama 才启用,没装自动退回纯 IDF 关键词"。
1952
+ # 配置来源:环境变量 LINGSHU_EMBED_URL / LINGSHU_RERANK_URL 优先,config.json 的
1953
+ # embed.url / rerank.url 兜底;任一为空白即整体禁用,调用方拿到 None 走原逻辑。
1954
+ # 网络调用全部用标准库 urllib,任何超时/异常一律静默返回 None,绝不阻断主链路。
1955
+ #
1956
+ # embedding 主体(_embed_cfg / fallback_encode_cached / embed_texts)已拆到
1957
+ # mem_embed.py,本模块末尾 `from mem_embed import *` 保留全部调用面。
1958
+ # 熔断状态仍留在 core:它是进程内可变全局,insights 面板与测试按
1959
+ # core._EMBED_DOWN_UNTIL 直接读写,mem_embed 里也经 core.* 访问同一份值。
1960
+ _EMBED_DOWN_UNTIL = 0.0
1961
+
1962
+
1963
+ def _rerank_cfg() -> dict | None:
1964
+ """读 rerank 配置;url 空白(未配置)返回 None。"""
1965
+ url = os.environ.get("LINGSHU_RERANK_URL", "").strip()
1966
+ try:
1967
+ cfg = load_config().get("rerank") or {}
1968
+ except Exception:
1969
+ cfg = {}
1970
+ if not url:
1971
+ url = str(cfg.get("url") or "").strip()
1972
+ if not url:
1973
+ return None
1974
+ return {
1975
+ "url": url,
1976
+ "model": str(cfg.get("model") or "qwen3-reranker-0.6b"),
1977
+ "timeout_sec": float(cfg.get("timeout_sec") or 8),
1978
+ "top_n": int(cfg.get("top_n") or 20),
1979
+ }
1980
+
1981
+
1982
+ def rerank_docs(query: str, docs: list, top_n: int | None = None) -> list | None:
1983
+ """调外部 reranker 给 docs 精排,返回 [(doc_index, score), ...] 按分数降序。
1984
+
1985
+ 未配置/失败返回 None(调用方走简单加权合并)。兼容两种常见响应形态:
1986
+ 1) {"scores": [float, ...]} —— 与 docs 等长
1987
+ 2) {"results": [{"index": i, "relevance_score": s}, ...]} —— cohere 风格
1988
+ """
1989
+ cfg = _rerank_cfg()
1990
+ if not cfg or not docs:
1991
+ return None
1992
+ import urllib.request
1993
+ n = min(int(top_n or cfg["top_n"]), len(docs))
1994
+ try:
1995
+ body = json.dumps({
1996
+ "model": cfg["model"],
1997
+ "query": str(query or ""),
1998
+ "documents": [str(d or "") for d in docs[:n]],
1999
+ }).encode("utf-8")
2000
+ req = urllib.request.Request(
2001
+ cfg["url"], data=body,
2002
+ headers={"Content-Type": "application/json"}, method="POST")
2003
+ with urllib.request.urlopen(req, timeout=cfg["timeout_sec"]) as resp:
2004
+ data = json.loads(resp.read().decode("utf-8"))
2005
+ pairs = []
2006
+ if isinstance(data.get("scores"), list):
2007
+ for i, s in enumerate(data["scores"][:n]):
2008
+ pairs.append((i, float(s)))
2009
+ elif isinstance(data.get("results"), list):
2010
+ for r in data["results"]:
2011
+ pairs.append((int(r.get("index", 0)),
2012
+ float(r.get("relevance_score", r.get("score", 0.0)))))
2013
+ if not pairs:
2014
+ return None
2015
+ pairs.sort(key=lambda x: x[1], reverse=True)
2016
+ return pairs
2017
+ except Exception as exc:
2018
+ log_event("rerank", f"reranker 调用失败,退回加权合并:{exc}", level="warn")
2019
+ return None
2020
+
2021
+
2022
+ # ---------------------------------------------------------------- 拆分模块 re-export
2023
+ # embedding 实现已拆到 mem_embed.py:star-import 回来,保持 core.embed_texts /
2024
+ # core._embed_cfg / `from core import *` 的调用面完全不变(下划线名字靠
2025
+ # mem_embed.__all__ 显式导出,否则 star-import 不会带过去)。
2026
+ from mem_embed import * # noqa: E402,F401,F403
2027
+
2028
+ __all__ = [k for k in dict(globals()) if not k.startswith("__")]