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,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)
@@ -0,0 +1,177 @@
1
+ # -*- coding: utf-8 -*-
2
+ """话题栈(v3.69 从 memory.py 拆出)。
3
+
4
+ 依赖约定(与 mem_score.py 同一套,务必遵守,否则循环导入):
5
+ - 只依赖 core 的名字(TOPIC_* 常量 / _locked / now_ts / read_jsonl /
6
+ write_jsonl / log_event / ensure_home / HOUR / READONLY 等,core 已
7
+ star-import)与标准库;**绝不 import memory**;
8
+ - memory.py 末尾 `from mem_topic import *` 保留 memory.topic_xxx 调用面。
9
+
10
+ 拆出理由:这一段是"快聊死的话题别再硬塞"的自洽逻辑(衰减、TTL、权重、
11
+ 反馈),与记忆读写主链路无耦合。边界经依赖分析确认:块内自定义名字只有
12
+ 本块的 6 个 topic_* 函数与 1 个 helper(_topic_check_writable),TOPIC_*
13
+ 常量全在 core.py,全部随 `from core import *` 可见。
14
+
15
+ # v3.69 待合并:本文件写入后,从 memory.py 删除对应块(L2718-2866)并在
16
+ # 末尾加 star-import;用 behavior_baseline check 逐字验证行为不变。
17
+ """
18
+ from __future__ import annotations
19
+
20
+ from core import * # noqa: F401,F403
21
+
22
+ __all__ = [
23
+ "load_topics", "topic_status", "topic_touch",
24
+ "topic_feedback", "topic_drop", "topic_can_spawn",
25
+ "_topic_check_writable",
26
+ ]
27
+
28
+
29
+ # 会话话题栈:AI 聊天时按「跟随当前 > 唤起历史 > 自发新话题」决策,
30
+ # 栈里的权重决定一个旧话题还值不值得再提、以及是否到了该主动开新话题的时候。
31
+
32
+ def load_topics(now: float = None, scope: str | None = None) -> list:
33
+ """读话题栈:指数衰减未重提话题、丢弃 TTL 过期项,按权重降序返回。
34
+
35
+ scope=None 返回全部 scope 的记录;scope="" 只看默认(本机)栈,
36
+ scope="channel@group:..." 只看对应通道的栈(B-08/C-03 通道隔离)。
37
+ """
38
+ now = now if now is not None else now_ts()
39
+ if not TOPIC_FILE.exists():
40
+ return []
41
+ out = []
42
+ for r in read_jsonl(TOPIC_FILE):
43
+ try:
44
+ ts = float(r.get("ts") or 0)
45
+ w = float(r.get("weight", 0))
46
+ except (TypeError, ValueError):
47
+ continue
48
+ if now - ts >= TOPIC_TTL:
49
+ continue # 7 天没重提,彻底退栈
50
+ if scope is not None and str(r.get("scope", "")) != scope:
51
+ continue
52
+ # 自上次活跃以来每过一个衰减周期(12h)权重 ×TOPIC_DECAY
53
+ periods = int((now - ts) / (12 * HOUR))
54
+ w *= (TOPIC_DECAY ** periods)
55
+ r = dict(r)
56
+ r["weight"] = round(min(max(w, 0.0), 1.0), 3)
57
+ out.append(r)
58
+ out.sort(key=lambda x: -x["weight"])
59
+ return out
60
+
61
+
62
+ def topic_status(scope: str = "") -> dict:
63
+ rows = load_topics(scope=scope)
64
+ return {
65
+ "count": len(rows),
66
+ "capacity": TOPIC_CAPACITY,
67
+ "spawn_threshold": TOPIC_SPAWN_THRESHOLD,
68
+ "scope": scope,
69
+ "top": rows[0]["name"] if rows else None,
70
+ "weak": [r["name"] for r in rows if r["weight"] < TOPIC_SPAWN_THRESHOLD],
71
+ "items": rows,
72
+ }
73
+
74
+
75
+ def _topic_check_writable() -> None:
76
+ """B-09:写路径统一入口检查——只读模式下优雅报错,避免 _locked 在不存在的
77
+ 目录里创建锁文件失败报出含糊的 OSError。"""
78
+ if READONLY:
79
+ raise RuntimeError("只读模式(--ro):话题栈不可修改")
80
+ ensure_home()
81
+
82
+
83
+ def topic_touch(name: str, type_: str = "", weight: float = 0.8,
84
+ why: str = "", delta: float = None, scope: str = "") -> list:
85
+ """用户重提或 AI 接住某话题:拉高权重(默认 0.8,或按 delta 增量)。
86
+
87
+ 用户主动抛出新话题是正向信号,直接置高;AI 引出的自发话题
88
+ 初始权重偏低(weight=0.4),避免抢占用户的主线。
89
+ scope:话题栈作用域(空串=本机默认栈;通道场景传 channel/group/user 组合串)。
90
+ """
91
+ name = (name or "").strip()
92
+ if not name:
93
+ raise ValueError("话题名为空")
94
+ # B-18:weight 与 delta 语义互斥(delta=增量、weight=直接置高),同传会失真
95
+ if delta is not None and weight != 0.8:
96
+ raise ValueError("weight 与 delta 互斥:请只传其一")
97
+ _topic_check_writable()
98
+ with _locked(TOPIC_FILE):
99
+ # 读全量(含各 scope)再按 scope 过滤操作,写回时合并,互不挤占
100
+ rows = load_topics() # 已剔除 TTL 过期项(I-10 物理清理)
101
+ sub = [r for r in rows if str(r.get("scope", "")) == scope]
102
+ rows = [r for r in rows if str(r.get("scope", "")) != scope]
103
+ for r in sub:
104
+ if r["name"] == name:
105
+ base = r["weight"]
106
+ new = base + delta if delta is not None else weight
107
+ r["weight"] = round(min(max(new, 0.0), 1.0), 3)
108
+ r["ts"] = now_ts()
109
+ r["turns"] = int(r.get("turns", 0)) + 1
110
+ if scope:
111
+ r["scope"] = scope
112
+ if type_:
113
+ r["type"] = type_
114
+ if why:
115
+ r.setdefault("whys", []).append(why)
116
+ break
117
+ else:
118
+ sub.insert(0, {"name": name, "weight": round(min(max(
119
+ (0.4 if delta is not None else weight), 0.0), 1.0), 3),
120
+ "ts": now_ts(), "turns": 1, "type": (type_ or "chat"),
121
+ "scope": scope,
122
+ "spawned_by_ai": delta is not None and weight is None,
123
+ "whys": [why] if why else []})
124
+ if len(sub) > TOPIC_CAPACITY:
125
+ # E-04:被挤出栈尾的话题留痕,别无声消失
126
+ evicted = [r["name"] for r in sub[TOPIC_CAPACITY:]]
127
+ log_event("topic", f"话题被挤出栈(scope={scope or '默认'}):{'、'.join(evicted)}",
128
+ evicted="; ".join(evicted))
129
+ sub = sub[:TOPIC_CAPACITY]
130
+ write_jsonl(TOPIC_FILE, rows + sub)
131
+ return sub
132
+
133
+
134
+ def topic_feedback(name: str, positive: bool, why: str = "", scope: str = "") -> list:
135
+ """兴趣反馈闭环:用户敷衍/转移话题 = 负反馈(权重 ×0.6);
136
+ 用户展开多说 = 正反馈(权重 +0.15)。写回话题栈,后续减少用户不感兴趣的自发话题。"""
137
+ _topic_check_writable() # B-09:与 topic_touch 一致的只读/目录检查
138
+ with _locked(TOPIC_FILE):
139
+ rows = load_topics()
140
+ sub = [r for r in rows if str(r.get("scope", "")) == scope]
141
+ rows = [r for r in rows if str(r.get("scope", "")) != scope]
142
+ for r in sub:
143
+ if r["name"] == name:
144
+ base = r["weight"]
145
+ r["weight"] = round(min(max(base * 0.6 if not positive else base + 0.15, 0.0), 1.0), 3)
146
+ r["ts"] = now_ts()
147
+ if why:
148
+ r.setdefault("whys", []).append(("+" if positive else "-") + why)
149
+ break
150
+ write_jsonl(TOPIC_FILE, rows + sub)
151
+ return sub
152
+
153
+
154
+ def topic_drop(name: str, scope: str = "") -> list:
155
+ """把话题彻底移出栈(用户明确说不想聊了)。"""
156
+ _topic_check_writable() # B-09
157
+ with _locked(TOPIC_FILE):
158
+ rows = load_topics()
159
+ sub = [r for r in rows if str(r.get("scope", "")) == scope and r["name"] != name]
160
+ rows = [r for r in rows if not (str(r.get("scope", "")) == scope and r["name"] == name)]
161
+ write_jsonl(TOPIC_FILE, rows + sub)
162
+ return sub
163
+
164
+
165
+ def topic_can_spawn(emotion_blocked: bool = False, scope: str = "") -> dict:
166
+ """自发话题准入判定(供注入包与 AI 参考,最终决定权在 AI 自己)。
167
+
168
+ 满足:存在权重低于阈值的话题(当前话题快聊死了)且情绪不拦。
169
+ 不满足的场景(倾诉/吐槽/认真提问/刚抛新话题/想结束)由 AI 按纪律自行判断。
170
+ """
171
+ st = topic_status(scope=scope)
172
+ weak = st["weak"]
173
+ return {
174
+ "can_spawn": bool(weak) and not emotion_blocked,
175
+ "weak_topics": weak,
176
+ "emotion_blocked": emotion_blocked,
177
+ }