lingshu-skill 0.0.0-stage → 3.79.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/CHANGELOG.md +2571 -0
  2. package/LICENSE +21 -0
  3. package/README.md +698 -3
  4. package/SKILL-lite.md +45 -0
  5. package/SKILL-tiny.md +37 -0
  6. package/SKILL.md +379 -0
  7. package/assets/panel.html +5616 -0
  8. package/cordis-plugin/lingshu-cron/cordis.patch.yml +3 -0
  9. package/cordis-plugin/lingshu-cron/index.js +4 -0
  10. package/cordis-plugin/lingshu-cron/package.json +34 -0
  11. package/cordis-plugin/lingshu-cron/plugin.js +1040 -0
  12. package/cordis-plugin/lingshu-guard/plugin.js +473 -0
  13. package/cordis-plugin/lingshu-im/plugin.js +635 -0
  14. package/cordis-plugin/lingshu-startup/README.md +123 -0
  15. package/cordis-plugin/lingshu-startup/cordis.patch.yml +3 -0
  16. package/cordis-plugin/lingshu-startup/index.js +4 -0
  17. package/cordis-plugin/lingshu-startup/package.json +25 -0
  18. package/cordis-plugin/lingshu-startup/plugin.js +352 -0
  19. package/cordis.patch.yml +3 -0
  20. package/docs/commands.md +243 -0
  21. package/docs/mechanics.md +610 -0
  22. package/docs/models.md +52 -0
  23. package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +49 -0
  24. package/docs/panel-api.md +198 -0
  25. package/docs/recovery.md +90 -0
  26. package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +53 -0
  27. package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +802 -0
  28. package/index.js +102 -0
  29. package/package.json +52 -6
  30. package/scripts/_panel_smoke_v299.py +27 -0
  31. package/scripts/_smoke_v299.py +31 -0
  32. package/scripts/_sync_trae_cn.py +34 -0
  33. package/scripts/assembler.py +197 -0
  34. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +53 -0
  35. package/scripts/astrbot_plugin_lingshu/PATCH_NOTES.md +28 -0
  36. package/scripts/astrbot_plugin_lingshu/README.md +58 -0
  37. package/scripts/astrbot_plugin_lingshu/_conf_schema.json +92 -0
  38. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +2571 -0
  39. package/scripts/astrbot_plugin_lingshu/engine/README.md +698 -0
  40. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +45 -0
  41. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +37 -0
  42. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +379 -0
  43. package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +5616 -0
  44. package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +243 -0
  45. package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -0
  46. package/scripts/astrbot_plugin_lingshu/engine/docs/models.md +52 -0
  47. package/scripts/astrbot_plugin_lingshu/engine/docs/panel-api.md +198 -0
  48. package/scripts/astrbot_plugin_lingshu/engine/docs/recovery.md +90 -0
  49. package/scripts/astrbot_plugin_lingshu/engine/scripts/_panel_smoke_v299.py +27 -0
  50. package/scripts/astrbot_plugin_lingshu/engine/scripts/_smoke_v299.py +31 -0
  51. package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +34 -0
  52. package/scripts/astrbot_plugin_lingshu/engine/scripts/assembler.py +197 -0
  53. package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +280 -0
  54. package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +192 -0
  55. package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +46 -0
  56. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +55 -0
  57. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +215 -0
  58. package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +165 -0
  59. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +4850 -0
  60. package/scripts/astrbot_plugin_lingshu/engine/scripts/context_ab.py +260 -0
  61. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2025 -0
  62. package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +1137 -0
  63. package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +1180 -0
  64. package/scripts/astrbot_plugin_lingshu/engine/scripts/failures.py +107 -0
  65. package/scripts/astrbot_plugin_lingshu/engine/scripts/fallback_embed.py +114 -0
  66. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +4745 -0
  67. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth_parts.py +263 -0
  68. package/scripts/astrbot_plugin_lingshu/engine/scripts/insights.py +131 -0
  69. package/scripts/astrbot_plugin_lingshu/engine/scripts/make_dsh_tgz.py +92 -0
  70. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +242 -0
  71. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +159 -0
  72. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_lesson.py +160 -0
  73. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +210 -0
  74. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_topic.py +177 -0
  75. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +4352 -0
  76. package/scripts/astrbot_plugin_lingshu/engine/scripts/npm_prepack.py +31 -0
  77. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +115 -0
  78. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +609 -0
  79. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +2703 -0
  80. package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +591 -0
  81. package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2309 -0
  82. package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +195 -0
  83. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +368 -0
  84. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +736 -0
  85. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +228 -0
  86. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +123 -0
  87. package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +252 -0
  88. package/scripts/astrbot_plugin_lingshu/main.py +703 -0
  89. package/scripts/astrbot_plugin_lingshu/make_checksums.py +87 -0
  90. package/scripts/astrbot_plugin_lingshu/metadata.yaml +7 -0
  91. package/scripts/behavior_baseline.py +280 -0
  92. package/scripts/bench.py +192 -0
  93. package/scripts/brain.py +46 -0
  94. package/scripts/check_pressure_sync.py +55 -0
  95. package/scripts/check_tag.py +215 -0
  96. package/scripts/check_version.py +265 -0
  97. package/scripts/checkpoint.py +165 -0
  98. package/scripts/cli.py +4850 -0
  99. package/scripts/context_ab.py +260 -0
  100. package/scripts/core.py +2025 -0
  101. package/scripts/dream.py +1137 -0
  102. package/scripts/emotion.py +1180 -0
  103. package/scripts/failures.py +107 -0
  104. package/scripts/fallback_embed.py +114 -0
  105. package/scripts/growth.py +4745 -0
  106. package/scripts/growth_parts.py +263 -0
  107. package/scripts/hooks/pre-commit +18 -0
  108. package/scripts/hooks/pre-push +20 -0
  109. package/scripts/insights.py +131 -0
  110. package/scripts/make_dsh_tgz.py +92 -0
  111. package/scripts/make_manifest.py +254 -0
  112. package/scripts/make_plugin_zip.py +88 -0
  113. package/scripts/mem_dialogue.py +242 -0
  114. package/scripts/mem_embed.py +159 -0
  115. package/scripts/mem_lesson.py +160 -0
  116. package/scripts/mem_score.py +210 -0
  117. package/scripts/mem_topic.py +177 -0
  118. package/scripts/memory.py +4352 -0
  119. package/scripts/npm_prepack.py +31 -0
  120. package/scripts/panel_build.py +115 -0
  121. package/scripts/panel_cloud.py +609 -0
  122. package/scripts/panel_server.py +2703 -0
  123. package/scripts/panels.py +591 -0
  124. package/scripts/persona.py +2309 -0
  125. package/scripts/recreate_push.ps1 +117 -0
  126. package/scripts/retriever.py +195 -0
  127. package/scripts/run_tests.py +91 -0
  128. package/scripts/safety.py +368 -0
  129. package/scripts/session_import.py +736 -0
  130. package/scripts/session_rag.py +228 -0
  131. package/scripts/session_summary.py +123 -0
  132. package/scripts/summarizer.py +252 -0
  133. package/scripts/sync_engine.py +139 -0
  134. package/scripts/update_dsh_copy.ps1 +107 -0
  135. package/start-panel.bat +60 -0
@@ -0,0 +1,242 @@
1
+ # -*- coding: utf-8 -*-
2
+ """跨对话上下文摄取(v3.39 从 memory.py 拆出)。
3
+
4
+ 依赖约定:
5
+ - 可变全局(HOME/锁/原子写/日志)走 `core.*`,不复制值;
6
+ - 需要 memory 的读写(remember/load_all)在调用时取模块,避免导入期循环。
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import re
13
+ from pathlib import Path
14
+
15
+ import core
16
+ from core import * # noqa: F401,F403 (now_ts/_num/_cfg_num 等纯函数)
17
+
18
+
19
+ def _mem():
20
+ import memory
21
+ return memory
22
+
23
+
24
+ _DIALOGUE_EXTS = (".jsonl", ".md", ".txt")
25
+ _DIALOGUE_MAX_DEPTH = 2
26
+ _DIALOGUE_READ_CAP = 8 * 1024 * 1024 # 单次最多读 8MB;大文件按完整行分批推进偏移
27
+
28
+
29
+ def _dialogue_offsets_path() -> Path:
30
+ return core.HOME / "dialogue_offsets.json"
31
+
32
+
33
+ def _dialogue_load_offsets() -> dict:
34
+ p = _dialogue_offsets_path()
35
+ if not p.exists():
36
+ return {}
37
+ try:
38
+ d = json.loads(p.read_text(encoding="utf-8-sig"))
39
+ return d if isinstance(d, dict) else {}
40
+ except Exception:
41
+ return {}
42
+
43
+
44
+ def _dialogue_decode(blob: bytes, source: str) -> str:
45
+ """BOM → UTF-8 严格解码 → GB18030 回退;实际编码留日志,不乱码静默入库。"""
46
+ if not blob:
47
+ return ""
48
+ encoding = "utf-8"
49
+ if blob.startswith(b"\xef\xbb\xbf"):
50
+ encoding = "utf-8-sig"
51
+ elif blob.startswith((b"\xff\xfe", b"\xfe\xff")):
52
+ encoding = "utf-16"
53
+ else:
54
+ try:
55
+ return blob.decode("utf-8")
56
+ except UnicodeDecodeError:
57
+ encoding = "gb18030"
58
+ try:
59
+ text = blob.decode(encoding)
60
+ except UnicodeDecodeError:
61
+ text = blob.decode(encoding, errors="replace")
62
+ core.log_event("dialogue", f"对话摄取解码({source}):{encoding}", level="info")
63
+ return text
64
+
65
+
66
+ def _dialogue_turns_from_text(text: str, ext: str) -> list:
67
+ """把导出片段解析成 [(role, text)];role ∈ user / ai / other。"""
68
+ turns = []
69
+ for ln in text.splitlines():
70
+ s = ln.strip()
71
+ if not s:
72
+ continue
73
+ if ext == ".jsonl":
74
+ try:
75
+ d = json.loads(s)
76
+ except Exception:
77
+ continue
78
+ if isinstance(d, str):
79
+ turns.append(("other", d))
80
+ continue
81
+ if not isinstance(d, dict):
82
+ continue
83
+ txt = d.get("content") or d.get("text") or d.get("message") or ""
84
+ if isinstance(txt, list): # OpenAI 风格 content parts
85
+ txt = " ".join(str(x.get("text") if isinstance(x, dict) else x) for x in txt)
86
+ txt = str(txt).strip()
87
+ if not txt:
88
+ continue
89
+ raw_role = str(d.get("role") or d.get("sender") or d.get("from") or "").lower()
90
+ if raw_role in ("user", "human", "me", "我", "用户"):
91
+ role = "user"
92
+ elif raw_role in ("assistant", "ai", "bot", "model", "灵枢", "助手"):
93
+ role = "ai"
94
+ else:
95
+ role = "other"
96
+ turns.append((role, txt))
97
+ else:
98
+ m = re.match(r"^\s*(user|human|assistant|ai|bot|model|我|用户|助手|灵枢)\s*[::]\s*(.+)$",
99
+ s, re.I)
100
+ if m:
101
+ who = m.group(1).lower()
102
+ role = "user" if who in ("user", "human", "我", "用户") else "ai"
103
+ turns.append((role, m.group(2).strip()))
104
+ else:
105
+ turns.append(("other", s))
106
+ return turns
107
+
108
+
109
+ def _dialogue_chunks(turns: list, max_chars: int = 700) -> list:
110
+ """相邻轮次拼成块(用户/我 前缀);块满就切,一块 = 一条 episode 记忆。"""
111
+ chunks, buf, size = [], [], 0
112
+ for role, text in turns:
113
+ if len(text) < 2:
114
+ continue
115
+ prefix = "用户: " if role == "user" else ("我: " if role == "ai" else "")
116
+ piece = prefix + text
117
+ if buf and size + len(piece) > max_chars:
118
+ chunks.append("\n".join(buf))
119
+ buf, size = [], 0
120
+ buf.append(piece)
121
+ size += len(piece) + 1
122
+ if buf:
123
+ chunks.append("\n".join(buf))
124
+ return [c for c in chunks if len(c) >= 8]
125
+
126
+
127
+ def _dialogue_files(sources: list, max_files: int) -> list:
128
+ """收集候选文件(最多 max_files 个,按 mtime 新→旧)。"""
129
+ found = []
130
+ for src in sources:
131
+ root = Path(str(src)).expanduser()
132
+ if not root.is_dir():
133
+ continue
134
+ base_depth = len(root.parts)
135
+ for f in root.rglob("*"):
136
+ try:
137
+ if len(f.parts) - base_depth > _DIALOGUE_MAX_DEPTH:
138
+ continue
139
+ if f.is_file() and f.suffix.lower() in _DIALOGUE_EXTS:
140
+ found.append(f)
141
+ except OSError:
142
+ continue
143
+ found.sort(key=lambda f: -(f.stat().st_mtime if f.exists() else 0))
144
+ return found[:max_files]
145
+
146
+
147
+ def ingest_dialogues(paths=None, limit: int | None = None, dry_run: bool = False) -> dict:
148
+ """增量摄取其他会话的对话导出 → episode 记忆。
149
+
150
+ 参数:
151
+ paths 额外/替代的源目录(缺省用 config.dialogue_sources)
152
+ limit 本次最多处理多少个文件(缺省 config.dialogue_ingest_max_files)
153
+ dry_run 只统计不写库(不推进偏移、不写记忆)
154
+ 返回:{enabled, files, scanned, imported, skipped, chars, dry_run}
155
+ """
156
+ cfg = load_config()
157
+ if not cfg.get("dialogue_ingest"):
158
+ return {"ok": True, "enabled": False, "files": 0, "scanned": 0,
159
+ "imported": 0, "skipped": 0, "chars": 0, "dry_run": dry_run,
160
+ "reason": "未开启:config dialogue_ingest=false"}
161
+ sources = [str(x) for x in (paths or cfg.get("dialogue_sources") or []) if str(x).strip()]
162
+ if not sources:
163
+ return {"ok": True, "enabled": True, "files": 0, "scanned": 0,
164
+ "imported": 0, "skipped": 0, "chars": 0, "dry_run": dry_run,
165
+ "reason": "没有配置 dialogue_sources 目录"}
166
+ max_files = max(1, min(int(limit or cfg.get("dialogue_ingest_max_files") or 50), 500))
167
+ max_chars = max(200, min(int(cfg.get("dialogue_ingest_max_chars") or 700), 2000))
168
+ imported, skipped, chars, touched = 0, 0, 0, 0
169
+ # offsets 既记读取位置,也记已导入块哈希:去重不再全量扫记忆库;
170
+ # 整个读偏移→写记忆→存偏移过程持同一把锁,避免两个进程重复导入。
171
+ with core._locked(_dialogue_offsets_path()):
172
+ files = _dialogue_files(sources, max_files)
173
+ offsets = _dialogue_load_offsets()
174
+ known = {h for entry in offsets.values() if isinstance(entry, dict)
175
+ for h in (entry.get("chunk_hashes") or [])}
176
+ for f in files:
177
+ key = str(f.resolve())
178
+ try:
179
+ st = f.stat()
180
+ except OSError:
181
+ continue
182
+ entry = offsets.get(key) or {}
183
+ # 用 offset==size 判断"已读干净":尾部半行没读完时不跳过,
184
+ # 下次等它补上换行再继续(否则会永久漏掉最后一条)。
185
+ if entry.get("offset") == st.st_size and entry.get("mtime") == st.st_mtime:
186
+ continue # 没变过:完全不读
187
+ start = int(entry.get("offset") or 0)
188
+ if st.st_size < start:
189
+ start = 0 # 文件被截断/重写:从头再来(块哈希去重兜底)
190
+ remaining = max(0, st.st_size - start)
191
+ try:
192
+ with open(f, "rb") as fh:
193
+ fh.seek(start)
194
+ blob = fh.read(min(_DIALOGUE_READ_CAP, remaining))
195
+ except OSError:
196
+ continue
197
+ if remaining > _DIALOGUE_READ_CAP:
198
+ core.log_event("dialogue", f"对话摄取分段读取({f.name}):"
199
+ f"偏移 {start},本次 {len(blob)} 字节,剩余下次继续",
200
+ level="info")
201
+ # 偏移永远落在完整行边界:尾部半行(正在写/无换行结尾)留到下次,
202
+ # 否则续读时会把一条完整的新记录误当成"残片"丢掉。
203
+ if blob and not blob.endswith(b"\n"):
204
+ cut = blob.rfind(b"\n")
205
+ if cut < 0:
206
+ continue
207
+ blob = blob[:cut + 1]
208
+ text = _dialogue_decode(blob, f.name)
209
+ turns = _dialogue_turns_from_text(text, f.suffix.lower())
210
+ file_hashes = list(entry.get("chunk_hashes") or [])
211
+ for chunk in _dialogue_chunks(turns, max_chars):
212
+ digest = hashlib.sha256(chunk.strip().encode("utf-8")).hexdigest()
213
+ if digest in known:
214
+ skipped += 1
215
+ continue
216
+ if not dry_run:
217
+ try:
218
+ _mem().remember(chunk, kind="episode", importance=0.45,
219
+ tags=["对话摄取", f.stem], source="dialogue",
220
+ channel=f"dialogue:{f.stem}")
221
+ except Exception as exc:
222
+ core.log_event("dialogue", f"对话摄取写入失败({f.name}):{exc}", level="warn")
223
+ continue
224
+ known.add(digest)
225
+ file_hashes.append(digest)
226
+ imported += 1
227
+ chars += len(chunk)
228
+ if not dry_run:
229
+ # offset 只推进到最后一个完整行末尾;尾部半行等下次补全
230
+ offsets[key] = {"offset": start + len(blob), "size": st.st_size,
231
+ "mtime": st.st_mtime, "ts": now_ts(),
232
+ "chunk_hashes": file_hashes}
233
+ touched += 1
234
+ if not dry_run and touched:
235
+ try:
236
+ core.atomic_json(_dialogue_offsets_path(), offsets)
237
+ except Exception as exc:
238
+ core.log_event("dialogue", f"对话摄取偏移保存失败:{exc}", level="warn")
239
+ return {"ok": True, "enabled": True, "files": len(files), "scanned": len(files),
240
+ "imported": imported, "skipped": skipped, "chars": chars,
241
+ "dry_run": dry_run, "sources": sources}
242
+
@@ -0,0 +1,159 @@
1
+ # -*- coding: utf-8 -*-
2
+ """可选 embedding / 降级向量(v3.39 从 core.py 拆出)。
3
+
4
+ 零依赖铁律:配了 embed.url(或环境变量 LINGSHU_EMBED_URL)才启用真嵌入;
5
+ 未配置/不可达时自动退回 fallback_embed.py 的纯 stdlib hash 向量;兜底也关掉
6
+ 才返回 None,调用方按"无 Dense 能力"降级。网络调用全走标准库 urllib,
7
+ 任何超时/异常一律静默返回 None,绝不阻断主链路。
8
+
9
+ 依赖约定(与 mem_dialogue.py 一致):
10
+ - 可变全局(HOME / config / 日志 / 熔断状态)一律走 `core.*` 模块属性,
11
+ 不 `from core import xxx` 复制值——core 会 rebind HOME,复制出来的是快照;
12
+ - 熔断状态 _EMBED_DOWN_UNTIL 留在 core:insights 面板与测试都按
13
+ core._EMBED_DOWN_UNTIL 直接读写,必须共享同一份进程内状态;
14
+ - `import core` 延迟到函数调用时(`_core()`),因为 core.py 末尾会
15
+ `from mem_embed import *`——导入期不触碰 core,杜绝循环导入。
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import time
22
+
23
+ # star-import 导出面:core.py 末尾 `from mem_embed import *` 依赖它。
24
+ # 下划线开头的 _embed_cfg 必须显式列出,否则 star-import 不会带过去
25
+ # (memory.py / cli.py 等模块 `from core import *` 后要直接调 _embed_cfg())。
26
+ __all__ = ["_embed_cfg", "fallback_encode_cached", "embed_texts"]
27
+
28
+ _core_mod = None
29
+
30
+
31
+ def _core():
32
+ """延迟拿 core 模块(首次调用后缓存):避免导入期循环,同时始终读活值。"""
33
+ global _core_mod
34
+ m = _core_mod
35
+ if m is None:
36
+ import core
37
+ m = _core_mod = core
38
+ return m
39
+
40
+
41
+ def _embed_cfg() -> dict | None:
42
+ """读 embed 配置;url 空白(未配置)返回 None。"""
43
+ url = os.environ.get("LINGSHU_EMBED_URL", "").strip()
44
+ try:
45
+ cfg = _core().load_config().get("embed") or {}
46
+ except Exception:
47
+ cfg = {}
48
+ if not url:
49
+ url = str(cfg.get("url") or "").strip()
50
+ if not url:
51
+ return None
52
+ return {
53
+ "url": url,
54
+ "model": str(cfg.get("model") or "nomic-embed-text"),
55
+ "timeout_sec": float(cfg.get("timeout_sec") or 8),
56
+ "max_chars": int(cfg.get("max_chars") or 3000),
57
+ "batch_size": int(cfg.get("batch_size") or 8),
58
+ }
59
+
60
+
61
+ # fallback_embed.encode 的进程内 LRU 缓存(查询/旧记忆在线编码时避免重复 hash)
62
+ _FB_EMBED_CACHE: dict = {}
63
+ _FB_EMBED_CACHE_MAX = 2000
64
+
65
+
66
+ def fallback_encode_cached(text: str, dims: int) -> list | None:
67
+ """fallback_embed.encode 的进程内 LRU 缓存(查询/旧记忆在线编码时避免重复 hash)。
68
+ 任何异常返回 None,不炸。"""
69
+ global _FB_EMBED_CACHE
70
+ try:
71
+ key = (dims, str(text or ""))
72
+ hit = _FB_EMBED_CACHE.get(key)
73
+ if hit is not None:
74
+ return hit
75
+ import fallback_embed
76
+ v = fallback_embed.encode(text, dims)
77
+ if v is not None:
78
+ if len(_FB_EMBED_CACHE) >= _FB_EMBED_CACHE_MAX:
79
+ _FB_EMBED_CACHE.clear() # 简单粗暴防膨胀;缓存命中是纯优化,丢了不伤正确性
80
+ _FB_EMBED_CACHE[key] = v
81
+ return v
82
+ except Exception:
83
+ return None
84
+
85
+
86
+ def embed_texts(texts: list) -> list | None:
87
+ """批量生成 embedding(Ollama /api/embeddings)。
88
+
89
+ 返回与 texts 等长的 list[list[float]];未配置/超时/异常/返回结构不符
90
+ 一律静默返回 None——调用方按"无 Dense 能力"降级,不做半吊子混合。
91
+ """
92
+ core = _core()
93
+ cfg = _embed_cfg()
94
+ if not texts:
95
+ return None
96
+ # 冷却期:上次连不上远端,这次直接走兜底,不再等满 timeout 也不重复告警
97
+ if cfg and time.time() < core._EMBED_DOWN_UNTIL:
98
+ cfg = None
99
+ # 未配置真嵌入服务时,先看降级向量兜底能不能接管(embed.fallback 默认开);
100
+ # 兜底也关了才真正返回 None(调用方按"无 Dense 能力"降级)。
101
+ if not cfg:
102
+ try:
103
+ import fallback_embed
104
+ fb = fallback_embed.cfg()
105
+ except Exception:
106
+ fb = None
107
+ if not fb:
108
+ return None
109
+ out = []
110
+ for t in texts:
111
+ v = fallback_encode_cached(str(t or "")[:3000], fb["dims"])
112
+ if v is None:
113
+ return None # 批量里有空文本等坏输入:整体按"无向量"处理
114
+ out.append(v)
115
+ return out
116
+ import urllib.request # 标准库,延迟 import:不用 Dense 时不付加载成本
117
+ out = []
118
+ try:
119
+ for t in texts:
120
+ body = json.dumps({
121
+ "model": cfg["model"],
122
+ "prompt": str(t or "")[: cfg["max_chars"]],
123
+ }).encode("utf-8")
124
+ req = urllib.request.Request(
125
+ cfg["url"], data=body,
126
+ headers={"Content-Type": "application/json"}, method="POST")
127
+ with urllib.request.urlopen(req, timeout=cfg["timeout_sec"]) as resp:
128
+ data = json.loads(resp.read().decode("utf-8"))
129
+ vec = data.get("embedding")
130
+ if not isinstance(vec, list) or not vec:
131
+ return None
132
+ out.append([float(x) for x in vec])
133
+ core._EMBED_DOWN_UNTIL = 0.0
134
+ return out
135
+ except Exception as exc:
136
+ _cd = 300.0
137
+ try:
138
+ _cd = max(30.0, float((cfg or {}).get("fail_cooldown_sec") or 300))
139
+ except Exception:
140
+ pass
141
+ core._EMBED_DOWN_UNTIL = time.time() + _cd
142
+ core.log_event("embed", f"embedding 调用失败,{int(_cd)} 秒内不再重试,先走降级向量:{exc}",
143
+ level="warn")
144
+ # 降级兜底:真嵌入不可用(未配置/不可达)时用纯 stdlib hash 嵌入接管
145
+ # (config embed.fallback.enabled 默认开)。批量语义:返回等长列表。
146
+ try:
147
+ import fallback_embed # 同目录模块,零依赖
148
+ fb = fallback_embed.cfg()
149
+ if fb:
150
+ out = []
151
+ for t in texts:
152
+ v = fallback_encode_cached(str(t or "")[:3000], fb["dims"])
153
+ if v is None:
154
+ return None # 批量里有空文本等坏输入:整体按"无向量"处理
155
+ out.append(v)
156
+ return out
157
+ except Exception:
158
+ pass
159
+ return None
@@ -0,0 +1,160 @@
1
+ # -*- coding: utf-8 -*-
2
+ """教训库(v3.70 从 memory.py 拆出)。
3
+
4
+ 依赖约定(与 mem_topic.py 同一套,务必遵守,否则循环导入):
5
+ - 只依赖 core 的名字(HOME / READONLY / read_jsonl / write_jsonl / _locked /
6
+ now_ts / _num / audit_log / log_event / ensure_home 等,core 已 star-import)
7
+ 与标准库(hashlib / os / Path);**绝不 import memory**;
8
+ - memory.py 末尾 `from mem_lesson import *` 保留 memory.{lessons_file,
9
+ load_lessons, add_lesson, ...} 调用面。
10
+
11
+ 拆出理由:教训库是一组自洽的 read-modify-write 操作(读库/校验/退役/审核),
12
+ 与记忆主链路无耦合。边界经依赖分析确认:L2830-2955 内 9 个函数依赖块外
13
+ memory 函数为空,只依赖 core + 标准库。injectable_lessons 依赖 _assoc_file
14
+ (关联图),留在 memory.py,不随块搬。
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import os
20
+
21
+ import core # noqa: F401 教训库要动态取 core.HOME(--home/--init 切换后指向新目录)
22
+ from core import * # noqa: F401,F403
23
+ # _num 是下划线开头,from core import * 不会带进来;memory.py 原本靠
24
+ # mem_score 的 star-import 提供它,新模块要显式取,否则 add_lesson 必崩。
25
+ from mem_score import _num # noqa: F401
26
+ from core import _locked # noqa: F401 下划线名字 star-import 不带,需显式取
27
+
28
+ __all__ = [
29
+ "LESSONS_FILE_NAME", "lessons_file", "_lesson_id",
30
+ "load_lessons", "save_lessons", "list_lessons", "add_lesson",
31
+ "validate_lesson", "set_lesson_status", "lessons_for_review",
32
+ ]
33
+
34
+
35
+ # 教训库:用对了 times_validated+1、confidence 上调;用错了降权;confidence <0.2 标记
36
+ # retired 退出注入——错的教训比没有教训更危险。
37
+ LESSONS_FILE_NAME = "lessons.jsonl"
38
+
39
+
40
+ def lessons_file() -> Path:
41
+ """教训库文件路径。动态取 core.HOME:--home/--init 切换后指向新目录。"""
42
+ return core.HOME / LESSONS_FILE_NAME
43
+
44
+
45
+ def _lesson_id(ts: int) -> str:
46
+ h = hashlib.sha1(f"lesson{ts}{os.urandom(4).hex()}".encode("utf-8")).hexdigest()[:8]
47
+ return f"les_{ts}_{h}"
48
+
49
+
50
+ def load_lessons() -> list:
51
+ """读教训库。坏行跳过 + warn 日志(与 read_jsonl 同风格),畸形条目过滤。"""
52
+ raw = read_jsonl(lessons_file())
53
+ good, bad = [], 0
54
+ for r in raw:
55
+ if isinstance(r, dict) and r.get("id") and r.get("text"):
56
+ good.append(r)
57
+ else:
58
+ bad += 1
59
+ if bad:
60
+ log_event("lessons", f"教训库跳过 {bad} 条畸形记录(缺 id/text 或类型错)", level="warning")
61
+ return good
62
+
63
+
64
+ def save_lessons(rows: list) -> None:
65
+ write_jsonl(lessons_file(), rows)
66
+
67
+
68
+ def list_lessons(include_retired: bool = False) -> list:
69
+ ls = load_lessons()
70
+ if not include_retired:
71
+ ls = [l for l in ls if not l.get("retired")]
72
+ # 按 confidence 从高到低,同分新的在前
73
+ return sorted(ls, key=lambda l: (-_num(l.get("confidence"), 0.5), -_num(l.get("created"), 0)))
74
+
75
+
76
+ def add_lesson(text: str, evidence=None, confidence: float = 0.5,
77
+ status: str = "active") -> dict:
78
+ """新增一条教训。做梦提炼的默认 status="pending"(待审核闸),人工 add 的直接 active。"""
79
+ ensure_home()
80
+ text = (text or "").strip()
81
+ if not text:
82
+ raise ValueError("教训内容为空")
83
+ if READONLY:
84
+ raise PermissionError("记忆库当前只读,无法写教训。用 --home 指向可写目录。")
85
+ conf = _num(confidence, 0.5)
86
+ conf = max(0.0, min(1.0, conf))
87
+ ts = now_ts()
88
+ lesson = {
89
+ "id": _lesson_id(ts),
90
+ "text": text,
91
+ "kind": "lesson",
92
+ "status": status if status in ("pending", "active") else "pending",
93
+ "confidence": round(conf, 3),
94
+ "times_validated": 0,
95
+ "evidence": [str(e) for e in (evidence or []) if e],
96
+ "created": ts,
97
+ "updated": ts,
98
+ }
99
+ # 写入加锁:教训库与记忆库一样是 read-modify-write,不加锁并发写会互相覆盖
100
+ with _locked(lessons_file()):
101
+ save_lessons(load_lessons() + [lesson])
102
+ audit_log("system" if status == "pending" else "user", "lesson_add", lesson["id"],
103
+ f"confidence={lesson['confidence']}, status={lesson['status']}")
104
+ log_event("lessons", f"新增教训 {lesson['id']}({lesson['status']})")
105
+ return lesson
106
+
107
+
108
+ def validate_lesson(lesson_id: str, ok: bool) -> dict:
109
+ """校验教训:ok=True 认为有用(times_validated+1、confidence 上调);
110
+ ok=False 踩了坑(降权);confidence <0.2 标记 retired,不再注入。"""
111
+ if READONLY:
112
+ raise PermissionError("记忆库当前只读,无法校验教训。用 --home 指向可写目录。")
113
+ lesson_id = str(lesson_id or "").strip()
114
+ with _locked(lessons_file()):
115
+ rows = load_lessons()
116
+ target = next((l for l in rows if l.get("id") == lesson_id), None)
117
+ if not target:
118
+ raise ValueError(f"没有这条教训:{lesson_id}")
119
+ conf = _num(target.get("confidence"), 0.5)
120
+ if ok:
121
+ target["times_validated"] = int(_num(target.get("times_validated"), 0)) + 1
122
+ # 上调有上限(0.95):再对也不能当铁律,教训永远依赖语境
123
+ conf = min(0.95, conf + 0.10)
124
+ else:
125
+ conf = conf - 0.15
126
+ target["confidence"] = round(max(0.0, conf), 3)
127
+ target["updated"] = now_ts()
128
+ # 低于 0.2 退役:留着仅作档案,注入与校验提示都不再带它
129
+ if target["confidence"] < 0.2 and not target.get("retired"):
130
+ target["retired"] = True
131
+ target["retired_at"] = now_ts()
132
+ audit_log("system", "lesson_retire", lesson_id,
133
+ f"confidence={target['confidence']} < 0.2,自动退役")
134
+ save_lessons(rows)
135
+ audit_log("user", "lesson_validate", lesson_id,
136
+ f"ok={ok}, confidence={target['confidence']}, "
137
+ f"times_validated={target['times_validated']}")
138
+ return dict(target)
139
+
140
+
141
+ def set_lesson_status(lesson_id: str, status: str) -> dict:
142
+ """审核闸:pending → active(review confirm 用)/ active → discarded(review discard 用)。"""
143
+ if status not in ("pending", "active", "discarded"):
144
+ raise ValueError(f"非法状态:{status}")
145
+ if READONLY:
146
+ raise PermissionError("记忆库当前只读,无法改教训状态。用 --home 指向可写目录。")
147
+ with _locked(lessons_file()):
148
+ rows = load_lessons()
149
+ target = next((l for l in rows if l.get("id") == lesson_id), None)
150
+ if not target:
151
+ raise ValueError(f"没有这条教训:{lesson_id}")
152
+ target["status"] = status
153
+ target["updated"] = now_ts()
154
+ save_lessons(rows)
155
+ audit_log("user", "lesson_review", lesson_id, f"status → {status}")
156
+ return dict(target)
157
+
158
+
159
+ def lessons_for_review() -> list:
160
+ return [l for l in load_lessons() if l.get("status") == "pending"]