lingshu-skill 5.14.0 → 5.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/scripts/memory.py CHANGED
@@ -1364,6 +1364,13 @@ def remember(text: str, kind: str = "fact", importance: float | None = None,
1364
1364
  # 第四轮#3:合并路径补项目标记——旧条目还挂着 "default" 时趁机挂上真实项目
1365
1365
  if project and str(project).strip() and str(m.get("project") or "default") == "default":
1366
1366
  m["project"] = str(project).strip()[:64]
1367
+ # P1-4:合并时若分支变了,说明这条已是**跨分支知识** → 清掉 branch,
1368
+ # 否则它在另一个分支上会被平白降权 50%(误伤)。
1369
+ if _branch_memory_on():
1370
+ _cur_br = _git_branch()
1371
+ _old_br = str(m.get("branch") or "")
1372
+ if _cur_br and _old_br and _cur_br != _old_br:
1373
+ m.pop("branch", None)
1367
1374
  save_all(records)
1368
1375
  # P1:异步补/更新 embedding(文本变了或还没有向量才调度;
1369
1376
  # 未配置 embed 服务时 _embed_wanted 直接 False,零开销跳过)
@@ -170,7 +170,14 @@ def overview() -> dict:
170
170
  except (OSError, ValueError):
171
171
  continue
172
172
  st = _safe("stats", brain.stats, {}) or {}
173
+ # P2-4 成长阶段:面板概览一行"灵枢健康度:少年(doctor 32 次 / failures 7 条)"
174
+ try:
175
+ _stage = growth.stage_state()
176
+ except Exception: # noqa: BLE001
177
+ _stage = None
178
+
173
179
  return {
180
+ "stage": _stage,
174
181
  "stats": st,
175
182
  # 层分布统计条用:各层记忆数(含归档),纯计数不做降级分支
176
183
  "layer_counts": {"hippo": st.get("hippo", 0), "cortex": st.get("cortex", 0),
@@ -1480,6 +1487,11 @@ def _api_daily(self, path, data):
1480
1487
 
1481
1488
 
1482
1489
  def _api_skill_self_review(self, path, data):
1490
+ # P2-4:自审也记一笔(成长阶段要用"self-review 次数")
1491
+ try:
1492
+ growth.record_doctor_run(0, 0, 0, kind="self-review")
1493
+ except Exception: # noqa: BLE001
1494
+ pass
1483
1495
  r = growth.self_review(force=bool(data.get("force")),
1484
1496
  days=_to_int(data.get("days", 3) or 3, 3) or 3)
1485
1497
  self._json({"ok": True, "result": r})
@@ -76,6 +76,12 @@ CONFIG_SCHEMA: list[dict[str, Any]] = [
76
76
  "hint": "送进 rerank 的候选条数,越大越准也越慢"},
77
77
 
78
78
  # —— 面板与宿主 ——
79
+ {"key": "speak_up_prob", "group": "水位与节奏", "label": "主动搭话概率",
80
+ "kind": "float", "min": 0, "max": 1, "step": 0.05,
81
+ "hint": "每轮结束按此概率让灵枢自己说一句(纯模板、不进模型);0=关闭"},
82
+ {"key": "speak_up_cooldown_min", "group": "水位与节奏", "label": "主动搭话冷却(分钟)",
83
+ "kind": "int", "min": 0, "max": 1440, "step": 5,
84
+ "hint": "两次主动搭话之间至少间隔多久,防刷屏"},
79
85
  {"key": "use_index_memory", "group": "注入与预算", "label": "索引法记忆",
80
86
  "kind": "enum", "options": ["auto", "always", "off"],
81
87
  "hint": "注入只送一句索引+id,正文用 recall 取;auto=水位≥60% 才切(省 40%+ 注入量)"},
@@ -0,0 +1,186 @@
1
+ # -*- coding: utf-8 -*-
2
+ """灵枢主动搭话(P1-3):会话之间按概率自己说一句。
3
+
4
+ 借鉴 dsh-speak-up 的"本地掷骰子"——**不进模型、不花 token**,纯模板 + 词表。
5
+
6
+ 四条闸门,缺一不可(任何一条不满足就安静,绝不刷屏):
7
+ ① `speak_up_prob` > 0(默认 0.10;设 0 永不出声)
8
+ ② 用户这一轮**只是陈述**(没在问问题)
9
+ ③ 灵枢此刻情绪不激动(`rationality.effective > 30`)
10
+ ④ 距上次主动搭话 ≥ `speak_up_cooldown_min`(默认 15 分钟)
11
+
12
+ 模板库取值:从最近记忆里挑一个关键词/主题,塞进句子里——避免"干巴巴的固定话术"。
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import random
18
+ import re
19
+ import time
20
+
21
+ import brain
22
+ import core
23
+
24
+ STATE_FILE = "speak-up.json"
25
+ DEFAULT_PROB = 0.10
26
+ DEFAULT_COOLDOWN_MIN = 15
27
+
28
+ # 模板库:{关键词} 会被替换成最近记忆里的一个主题词。刻意写得短、不油腻。
29
+ TEMPLATES = (
30
+ "你好像在忙{kw},要不要说说?",
31
+ "刚才提到{kw},我有点感兴趣。",
32
+ "关于{kw},要我帮你翻翻以前的记录吗?",
33
+ "{kw}那件事,你后来怎么定的?",
34
+ "我留意到{kw},需要我记一笔吗?",
35
+ "说到{kw}——我之前是不是也碰过?",
36
+ )
37
+
38
+ # 判定"在提问"的标志:有问号、或出现这些请求词
39
+ _QUESTION_RE = re.compile(r"[??]|(吗|呢|怎么|如何|为什么|为何|是否|能不能|可不可以|要不要|帮我|请问)")
40
+ # 主题词排除:整词黑名单 + 子串黑名单(含这些基本不是"话题词")
41
+ _STOP = {"这个", "那个", "什么", "现在", "就是", "然后", "可以", "需要", "一下",
42
+ "我们", "你们", "他们", "自己", "时候", "问题", "东西", "事情", "系统",
43
+ "内容", "部分", "方式", "情况", "方法", "功能", "代码"}
44
+ _STOP_SUB = ("你", "我", "他", "她", "它", "咱", "您", "的", "了", "着", "吗",
45
+ "呢", "吧", "啊", "哦", "嗯", "是", "在", "有", "和", "与", "或",
46
+ "把", "被", "对", "从", "到", "会", "能", "要", "就", "也", "都",
47
+ "很", "太", "更", "最", "但", "而", "如", "若", "因", "所", "这",
48
+ "那", "哪", "什", "么", "怎", "为", "用", "做", "说", "看", "想")
49
+
50
+
51
+ def _state_path():
52
+ return core.HOME / STATE_FILE
53
+
54
+
55
+ def _load_state() -> dict:
56
+ try:
57
+ d = json.loads(_state_path().read_text(encoding="utf-8"))
58
+ return d if isinstance(d, dict) else {}
59
+ except (OSError, ValueError):
60
+ return {}
61
+
62
+
63
+ def _save_state(st: dict) -> None:
64
+ try:
65
+ core.atomic_json(_state_path(), st)
66
+ except (OSError, ValueError):
67
+ pass
68
+
69
+
70
+ def _cfg() -> dict:
71
+ try:
72
+ return core.load_config()
73
+ except Exception: # noqa: BLE001
74
+ return {}
75
+
76
+
77
+ def prob() -> float:
78
+ """触发概率(0~1)。坏配置回落默认值。"""
79
+ try:
80
+ v = float(_cfg().get("speak_up_prob", DEFAULT_PROB))
81
+ except (TypeError, ValueError):
82
+ return DEFAULT_PROB
83
+ return max(0.0, min(1.0, v))
84
+
85
+
86
+ def cooldown_sec() -> float:
87
+ try:
88
+ v = float(_cfg().get("speak_up_cooldown_min", DEFAULT_COOLDOWN_MIN))
89
+ except (TypeError, ValueError):
90
+ v = DEFAULT_COOLDOWN_MIN
91
+ return max(0.0, v) * 60.0
92
+
93
+
94
+ def is_question(text: str) -> bool:
95
+ """这一轮用户是不是在提问/请求(那就别主动搭话,先回答)。"""
96
+ return bool(_QUESTION_RE.search(str(text or "")))
97
+
98
+
99
+ def _good_topic(w: str) -> bool:
100
+ """一个候选是否适合当话题词(人/物/概念,而不是代词+动词碎片)。"""
101
+ w = str(w or "").strip().lstrip("#")
102
+ if not (2 <= len(w) <= 12):
103
+ return False
104
+ if w in _STOP:
105
+ return False
106
+ # 含任何虚词/代词字符就不是话题词("你可以用" 这类就是被这条挡掉的)
107
+ if any(ch in w for ch in _STOP_SUB):
108
+ return False
109
+ # 至少一半得是汉字/字母/数字,排除纯符号
110
+ core_chars = [c for c in w if c.isalnum()]
111
+ if len(core_chars) < 2 or len(core_chars) < len(w) / 2:
112
+ return False
113
+ return True
114
+
115
+
116
+ def _topic_from_recent() -> str:
117
+ """从最近记忆的**实体/标签**里抽一个话题词;抽不到返回 ""(宁可不说)。"""
118
+ try:
119
+ rows = brain.recent(12) or []
120
+ except Exception: # noqa: BLE001
121
+ return ""
122
+ cands = []
123
+ for m in rows:
124
+ for w in (m.get("entities") or []):
125
+ if _good_topic(w):
126
+ cands.append(str(w).strip().lstrip("#"))
127
+ for w in (m.get("tags") or []):
128
+ if _good_topic(w):
129
+ cands.append(str(w).strip().lstrip("#"))
130
+ if not cands:
131
+ return ""
132
+ # 去重后从"较新"的候选里挑,避免老话题反复出现
133
+ uniq = list(dict.fromkeys(cands))
134
+ return uniq[-1] if len(uniq) == 1 else random.choice(uniq[-6:])
135
+
136
+
137
+ def maybe(last_user_text: str = "", force: bool = False,
138
+ rng: random.Random | None = None, now: float | None = None) -> dict:
139
+ """决定是否主动搭话。返回 {triggered, text, reason}。
140
+
141
+ `force=True` 跳过概率与冷却(调试/验收用),但仍守"不是提问"这条。
142
+ """
143
+ now = time.time() if now is None else now
144
+ rng = rng or random
145
+
146
+ p = prob()
147
+ if p <= 0 and not force:
148
+ return {"triggered": False, "reason": "speak_up_prob=0(已关闭)"}
149
+ if last_user_text and is_question(last_user_text):
150
+ return {"triggered": False, "reason": "这一轮是提问,先回答"}
151
+ try:
152
+ import emotion
153
+ eff = float((emotion.rationality() or {}).get("effective") or 0)
154
+ except Exception: # noqa: BLE001
155
+ eff = 100.0
156
+ if not force and eff <= 30:
157
+ return {"triggered": False, "reason": f"情绪太激动(理智 {eff:.0f} ≤ 30)"}
158
+ st = _load_state()
159
+ last = float(st.get("last_at") or 0)
160
+ cd = cooldown_sec()
161
+ if not force and now - last < cd:
162
+ left = int((cd - (now - last)) / 60) + 1
163
+ return {"triggered": False, "reason": f"冷却中(还需 {left} 分钟)"}
164
+ if not force and rng.random() >= p:
165
+ return {"triggered": False, "reason": f"掷骰子未中(p={p:.2f})"}
166
+
167
+ kw = _topic_from_recent()
168
+ if not kw:
169
+ return {"triggered": False, "reason": "没有可用的主题词(库太新/太干净)"}
170
+ text = rng.choice(TEMPLATES).format(kw=kw)
171
+ st["last_at"] = now
172
+ st["last_text"] = text
173
+ st["count"] = int(st.get("count") or 0) + 1
174
+ _save_state(st)
175
+ # 留痕:doctor / 面板日志能看到"它什么时候自己开过口"
176
+ try:
177
+ import failures
178
+ failures.record("speak_up.triggered", text[:120], level="info")
179
+ except Exception: # noqa: BLE001
180
+ pass
181
+ try:
182
+ brain.log_event("speak_up", f"主动搭话:{text[:80]}")
183
+ except Exception: # noqa: BLE001
184
+ pass
185
+ return {"triggered": True, "text": text, "topic": kw,
186
+ "count": st["count"], "prob": p}