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,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"]
@@ -0,0 +1,210 @@
1
+ # -*- coding: utf-8 -*-
2
+ """评分与保留度纯函数(v3.40 从 memory.py 拆出)。
3
+
4
+ 依赖约定:
5
+ - 只做纯计算:入参是文本/数字/记忆 dict,不读盘、不写盘、不依赖 HOME;
6
+ - 时间与常量走 core(now_ts/HOUR/DAY/DEFAULT_STABILITY),不复制可变全局;
7
+ - memory.py 末尾 `from mem_score import *` 保留 memory.xxx 调用面。
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ import re
13
+
14
+ from core import * # noqa: F401,F403 (now_ts/HOUR/DAY/DEFAULT_STABILITY 等纯函数/常量)
15
+
16
+ __all__ = [
17
+ "terms", "jaccard", "build_idf", "relevance",
18
+ "_num", "heuristic_importance", "_imp_key_safe",
19
+ "retention", "activation", "ACTIVATION_FORGET_THRESHOLD", "activation_forget",
20
+ "_KIND_STABILITY_FACTOR", "_cosine_sim",
21
+ ]
22
+
23
+
24
+ # ---------------------------------------------------------------- 文本与相似度
25
+
26
+ _CJK = re.compile(r"[\u4e00-\u9fff]+")
27
+ # 数字/编号(如 "版本0" vs "版本1")必须保留为独立 term,否则不同数字的记忆会被误判为重复而合并覆盖
28
+ _WORD = re.compile(r"[a-z0-9]+")
29
+ _PUNCT = re.compile(r"[^\w\u4e00-\u9fff]+")
30
+
31
+
32
+ def terms(text: str) -> set:
33
+ """中文用字符二元组,英文/数字用词。构成模糊匹配的最小单元。"""
34
+ t = (text or "").lower()
35
+ out = set()
36
+ for seg in _CJK.findall(t):
37
+ if len(seg) == 1:
38
+ out.add(seg)
39
+ for i in range(len(seg) - 1):
40
+ out.add(seg[i:i + 2])
41
+ out.update(_WORD.findall(t))
42
+ return out
43
+
44
+
45
+ def jaccard(a: set, b: set) -> float:
46
+ if not a or not b:
47
+ return 0.0
48
+ return len(a & b) / len(a | b)
49
+
50
+
51
+ def build_idf(docs: list) -> dict:
52
+ df = {}
53
+ for d in docs:
54
+ for t in d:
55
+ df[t] = df.get(t, 0) + 1
56
+ n = max(1, len(docs))
57
+ return {t: math.log((n + 1) / (c + 0.5)) + 0.5 for t, c in df.items()}
58
+
59
+
60
+ def relevance(q_terms: set, d_terms: set, idf: dict) -> float:
61
+ shared = q_terms & d_terms
62
+ if not shared:
63
+ return 0.0
64
+ num = sum(idf.get(t, 0.5) for t in shared)
65
+ den = math.sqrt(sum(idf.get(t, 0.5) for t in q_terms) * sum(idf.get(t, 0.5) for t in d_terms))
66
+ return min(1.0, num / den) if den else 0.0
67
+
68
+
69
+ # ---------------------------------------------------------------- 数值与重要性打分
70
+
71
+ def _num(v, default: float = 0.0) -> float:
72
+ """把可能是 None / 字符串 / 数字 / bool / NaN 的值安全转成 float;转不了用默认值。
73
+ 记忆库里手改、旧版本、坏字段都可能让数值变成 null 或字符串,硬 float() 会整条崩。"""
74
+ if v is None or isinstance(v, bool): # bool 是 int 子类,True 会变 1.0,按坏值回退
75
+ return float(default)
76
+ try:
77
+ f = float(v)
78
+ except (TypeError, ValueError):
79
+ return float(default)
80
+ # 模型可能产出 NaN/Infinity(JSON 里非法但 Python json 会放行),比较/运算会一路污染
81
+ if math.isnan(f) or math.isinf(f):
82
+ return float(default)
83
+ return f
84
+
85
+
86
+ def heuristic_importance(text: str, kind: str, entities=None,
87
+ correction: bool = False, emotional: float = 0.0) -> float:
88
+ """#42 多维重要性打分:写入时就回答"这条记忆有多重要"。
89
+
90
+ 维度(SCM multi-dimensional importance / Memory Bear activation 的轻量版):
91
+ kind 基线 → 命中关键词 → 文本长度 → 实体数量 → 情绪强度 → 是否 correction。
92
+ 打分只影响起步权重,后续回忆次数/做梦巩固仍会拉开差距。
93
+ """
94
+ base = {
95
+ "identity": 0.95, "insight": 0.75, "preference": 0.70,
96
+ "habit": 0.65, "emotion": 0.60, "fact": 0.58, "episode": 0.40,
97
+ "mistake": 0.70, "relationship": 0.70,
98
+ }.get(kind, 0.5)
99
+ hot = ("记住", "重要", "永远", "一定", "绝不", "喜欢", "讨厌", "生日",
100
+ "名字", "答应", "承诺", "第一次", "决定")
101
+ if any(w in text for w in hot):
102
+ base += 0.15
103
+ if len(text) >= 60:
104
+ base += 0.05
105
+ # 实体维度:涉及的人/物越多,关系网络价值越高(上限 +0.10)
106
+ n_ent = len(entities or [])
107
+ if n_ent:
108
+ base += min(0.10, 0.04 * n_ent)
109
+ # 情绪维度:写入时情绪越激动记得越牢(调用方已算好的 arousal,0~1)
110
+ if emotional > 0:
111
+ base += min(0.12, 0.12 * _num(emotional, 0.0))
112
+ # correction 维度:被纠正过的说法是失败闭环第一手证据,起步就该高
113
+ if correction:
114
+ base = max(base, 0.75)
115
+ return max(0.05, min(1.0, round(base, 2)))
116
+
117
+
118
+ def _imp_key_safe(m: dict) -> float:
119
+ """importance 安全取值:坏类型(None/list 等)沉底为 0,不让一条坏记忆炸掉画像。"""
120
+ return _num(m.get("importance"), 0.0)
121
+
122
+
123
+ # ---------------------------------------------------------------- 保留度 / 唤醒值
124
+
125
+ def retention(m: dict, now: int | None = None) -> float:
126
+ """艾宾浩斯遗忘曲线:R = exp(-Δt / S)"""
127
+ now = now or now_ts()
128
+ last = m.get("last_access")
129
+ if last is None:
130
+ last = m.get("created", now)
131
+ dt = max(0.0, now - _num(last, now))
132
+ stability = max(HOUR, _num(m.get("stability"), DEFAULT_STABILITY))
133
+ # v3.01 遗忘可纠正(借鉴 fish-soul 艾宾浩斯):mistake/relationship 这类
134
+ # 成长型记忆默认更抗遗忘——稳定度乘一个大于 1 的系数(等效半衰期更长)。
135
+ kind = str(m.get("kind") or "")
136
+ stability *= _KIND_STABILITY_FACTOR.get(kind, 1.0)
137
+ return math.exp(-dt / stability)
138
+
139
+
140
+ # 类别稳定度系数:>1 更抗遗忘(半衰期更长),mistake/relationship 是成长地基
141
+ _KIND_STABILITY_FACTOR = {"mistake": 1.5, "relationship": 1.5, "identity": 2.0, "preference": 1.2}
142
+
143
+
144
+ def activation(m: dict, now: int | None = None) -> float:
145
+ """#43 唤醒值(ACT-R activation + Memory Bear 遗忘引擎):一条记忆"此刻有多容易被想起"。
146
+
147
+ activation = importance × R(艾宾浩斯保留度) × recency_bonus
148
+ - importance:写入时打分的多维重要性(#42)
149
+ - R:retention() 的指数衰减(stability 越大衰减越慢)
150
+ - recency_bonus:最近 3 天内被召回过给小额加成(用进废退)
151
+ 取值 0~1,做梦/归档按它排序决定"谁先被压缩淡忘",recall 命中则自然回升
152
+ (last_access 更新 → R 回升)。纯计算不改库,只读调用零风险。
153
+ """
154
+ now = now or now_ts()
155
+ imp = max(0.0, min(1.0, _num(m.get("importance"), 0.5)))
156
+ R = retention(m, now)
157
+ # 用进废退:3 天内想起过一次给 +0.08,封顶一次(连续想起靠 R 本身维持)
158
+ idle = now - _num(m.get("last_access"), _num(m.get("created"), now))
159
+ recency = 0.08 if idle <= 3 * DAY else 0.0
160
+ return round(max(0.0, min(1.0, imp * R + recency)), 4)
161
+
162
+
163
+ # 唤醒值软处理阈值:做梦时 activation 低于此值的记忆降层/切断关联。
164
+ # 不是删除——dust 层可 revive 复活,被意外召回(recall 触碰)后 R 回升即自然"复活"。
165
+ ACTIVATION_FORGET_THRESHOLD = 0.06
166
+
167
+
168
+ def activation_forget(records: list, now: int | None = None,
169
+ threshold: float = ACTIVATION_FORGET_THRESHOLD) -> list:
170
+ """#43 唤醒值遗忘引擎(软处理):对 activation < 阈值的活跃层记忆做三步弱化——
171
+ 1) 降层到 dust;2) 切断 outgoing 关联边(别的记忆指向它的边不动,留复活线索);
172
+ 3) 清 embedding(向量召回不再命中,等 revive 后重新生成)。
173
+ 不碰:pinned / correction / identity / 待审核 / 已经在 dust 的。
174
+ 返回被处理的记录列表(调用方决定是否落盘)。"""
175
+ now = now or now_ts()
176
+ hit = []
177
+ by_id = {m.get("id"): m for m in records if m.get("id")}
178
+ for m in records:
179
+ if m.get("layer") not in ("hippo", "cortex") or m.get("pinned"):
180
+ continue
181
+ if m.get("correction") or m.get("kind") == "identity" or m.get("review") == "pending":
182
+ continue
183
+ if activation(m, now) < threshold:
184
+ m["layer"] = "dust"
185
+ m["forgotten_at"] = now
186
+ m["detail"] = round(max(0.12, _num(m.get("detail"), 1) * 0.4), 2)
187
+ m.pop("embedding", None) # 向量降级:复活后 _embed_wanted 会重新调度
188
+ for sid in (m.get("links") or []):
189
+ src = by_id.get(sid)
190
+ if src and src.get("links"):
191
+ src["links"] = [x for x in src["links"] if x != m["id"]]
192
+ m["links"] = []
193
+ hit.append(m)
194
+ return hit
195
+
196
+
197
+ # ---------------------------------------------------------------- 向量相似度(纯标准库)
198
+
199
+ def _cosine_sim(a: list, b: list) -> float:
200
+ """纯标准库余弦相似度:零向量/空向量/维度不一致都返回 0.0,不抛异常。
201
+
202
+ 从 memory._dense_recall 的内联算式抽出:对非零且同维的向量,结果与旧实现完全一致;
203
+ 零向量在旧实现里靠 `or 1.0` 兜底成 0.0,这里显式判断,便于单测覆盖边界。
204
+ """
205
+ n = len(a)
206
+ if not n or n != len(b):
207
+ return 0.0
208
+ an = math.sqrt(sum(x * x for x in a)) or 1.0
209
+ bn = math.sqrt(sum(x * x for x in b)) or 1.0
210
+ return sum(x * y for x, y in zip(a, b)) / (an * bn)