lingshu-skill 5.70.0 → 5.71.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 (38) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/SKILL-lite.md +1 -1
  3. package/SKILL-tiny.md +1 -1
  4. package/SKILL.md +1 -1
  5. package/cordis-plugin/lingshu-cron/plugin.js +36 -14
  6. package/cordis-plugin/lingshu-im/plugin.js +67 -15
  7. package/manifest.json +35 -35
  8. package/package.json +1 -1
  9. package/scripts/assembler.py +8 -2
  10. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +88 -16
  11. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +45 -0
  12. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +1 -1
  13. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +1 -1
  14. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +1 -1
  15. package/scripts/astrbot_plugin_lingshu/engine/scripts/assembler.py +8 -2
  16. package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +13 -2
  17. package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +45 -0
  18. package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +13 -2
  19. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth_parts.py +5 -1
  20. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +62 -6
  21. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +47 -1
  22. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +12 -2
  23. package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +10 -4
  24. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +6 -1
  25. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +6 -2
  26. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +68 -21
  27. package/scripts/astrbot_plugin_lingshu/make_checksums.py +8 -4
  28. package/scripts/checkpoint.py +13 -2
  29. package/scripts/dream.py +45 -0
  30. package/scripts/emotion.py +13 -2
  31. package/scripts/growth_parts.py +5 -1
  32. package/scripts/memory.py +62 -6
  33. package/scripts/panel_cloud.py +47 -1
  34. package/scripts/panel_server.py +12 -2
  35. package/scripts/persona.py +10 -4
  36. package/scripts/safety.py +6 -1
  37. package/scripts/session_import.py +6 -2
  38. package/scripts/session_rag.py +68 -21
@@ -350,10 +350,12 @@ def load_persona() -> dict:
350
350
  log_event("persona", "检测到人格空态,已自动从 persona.lastgood.json 回滚", level="warn")
351
351
  # AUTOHEAL-COMMIT(v5.56):立即写回盘,否则下次 load 又读到空态 →
352
352
  # 反复回滚 + 反复告警(实测 5 分钟刷 78 条 warn)。写回失败不影响返回值。
353
- try:
354
- atomic_json(HOME / "persona.json", _good)
355
- except Exception:
356
- pass
353
+ # LS-026(v5.71):人格自愈绝不能在只读模式写盘!
354
+ if not READONLY:
355
+ try:
356
+ atomic_json(HOME / "persona.json", _good)
357
+ except Exception:
358
+ pass
357
359
  except Exception:
358
360
  pass
359
361
 
@@ -426,8 +428,12 @@ def save_persona(p: dict) -> None:
426
428
  atomic_json(HOME / "persona.json", p)
427
429
  # PERSONA-AUTOHEAL(v5.54):每次成功保存"有名字"的人格,同步留一份 lastgood。
428
430
  # 这样无论哪条路径把人格写空,load_persona 都能自动回滚——不再依赖人工恢复。
431
+ # LS-027(v5.71):写回 lastgood 前执行完整结构校验!
432
+ # lastgood 是人格的最后一道网——若把带坏字段的人格快照进去,
433
+ # 空态回滚时会原样恢复坏数据。校验失败绝不留底(宁缺勿错)。
429
434
  try:
430
435
  if str(((p.get("identity") or {}).get("名字") or "")).strip():
436
+ _validate_persona_struct(p, "persona.lastgood.json")
431
437
  atomic_json(HOME / "persona.lastgood.json", p)
432
438
  except Exception:
433
439
  pass
package/scripts/safety.py CHANGED
@@ -126,8 +126,13 @@ def dangerous_reason(home: Path | str) -> str | None:
126
126
  if _is_home_dir(r):
127
127
  return "用户主目录本体不能当记忆库(restore --exact 会清空整个用户目录)"
128
128
  low = str(r).lower().replace("/", "\\") if sys.platform == "win32" else str(r).lower()
129
+ # LS-001(v5.71):修复 POSIX 危险路径子目录绕过!
130
+ # 旧写法在所有平台都追加 "\\" 做前缀分隔——POSIX 路径分隔符是 "/",
131
+ # `/etc/passwd`、`/usr/share/x` 等子目录永远匹配不上前缀,整个系统目录树
132
+ # 在 Linux/macOS 上漏判。分隔符必须跟随平台。
133
+ _sep = "\\" if sys.platform == "win32" else "/"
129
134
  for pref in _SYSTEM_PREFIXES:
130
- if low == pref or low.startswith(pref.rstrip("\\") + "\\"):
135
+ if low == pref or low.startswith(pref.rstrip("\\/") + _sep):
131
136
  return f"系统目录不能当记忆库:{raw}"
132
137
  # 所有用户的父目录(C:\Users 本身)
133
138
  try:
@@ -34,8 +34,6 @@ from __future__ import annotations
34
34
 
35
35
  import argparse
36
36
  import hashlib
37
- import brain
38
- import core
39
37
  import json
40
38
  import os
41
39
  import re
@@ -47,10 +45,16 @@ import time
47
45
  from dataclasses import dataclass
48
46
  from pathlib import Path
49
47
 
48
+ # LS-057(v5.71):修正导入顺序——先设置模块目录再 import brain!
49
+ # 旧写法在 sys.path 注入前就 import brain/core,通过 spec_from_file_location
50
+ # 独立加载(测试沙箱/外部宿主)时本目录不在 sys.path,直接 ModuleNotFoundError。
50
51
  HERE = Path(__file__).resolve().parent
51
52
  if str(HERE) not in sys.path: # 允许 `python scripts/session_import.py` 与 tests 直接 import
52
53
  sys.path.insert(0, str(HERE))
53
54
 
55
+ import brain # noqa: E402
56
+ import core # noqa: E402
57
+
54
58
  import session_rag # noqa: E402
55
59
 
56
60
  PLATFORM = "dsh"
@@ -95,7 +95,14 @@ def ingest_messages(rows, *, session: str = "default", platform: str = "",
95
95
  skipped += 1
96
96
  continue
97
97
  role = str(r.get("role") or "other").lower()
98
- ts = float(r.get("ts") or r.get("created") or 0)
98
+ # LS-046(v5.71):隔离会话批次中的脏时间戳!
99
+ # 旧实现 float("bad") 直接抛 ValueError——一条脏 ts 让**整批**合法
100
+ # 消息全部回滚。现在单条 try/except:脏时间戳记 skipped 并继续。
101
+ try:
102
+ ts = float(r.get("ts") or r.get("created") or 0)
103
+ except (TypeError, ValueError):
104
+ skipped += 1
105
+ continue
99
106
  # LS-034(v5.65):主键纳入 platform 和 workspace 作用域
100
107
  mid = _msg_id(session, role, ts, text, platform=platform, workspace=workspace)
101
108
  try:
@@ -145,24 +152,39 @@ def _scope_clauses(*, workspace=None, platform=None,
145
152
 
146
153
  def search(query: str, k: int = 10, *, path=None, workspace=None,
147
154
  platform=None) -> list[dict]:
148
- """FTS/LIKE 检索;workspace/platform 为可选精确过滤,缺省不过滤(保持旧行为)。"""
155
+ """FTS/LIKE 检索;workspace/platform 为可选精确过滤,缺省不过滤(保持旧行为)。
156
+
157
+ LS-047(v5.71):检索是只读操作——库不存在时返回空结果,绝不自动建库建表。
158
+ """
149
159
  q = str(query or "").strip()
150
160
  if not q:
151
161
  return []
152
162
  limit = max(1, int(k))
153
- with connect(path) as conn:
154
- conn.executescript(SCHEMA)
163
+ # 库不存在:只读语义,返回空而不创建
164
+ _p = Path(path) if path else db_path()
165
+ if not _p.is_file():
166
+ return []
167
+ try:
168
+ conn = _connect_readonly(path)
169
+ except FileNotFoundError:
170
+ return []
171
+ with conn:
155
172
  # FTS5 trigram 只对 ≥3 字符的词元建索引:中文两字词("云南")MATCH 不到,
156
173
  # 短查询走 LIKE 兜底(200k 条内可接受;更长的词仍走 FTS 排序)。
157
174
  if len(q) < 3:
158
- scope, scope_params = _scope_clauses(workspace=workspace, platform=platform)
159
- rows = conn.execute(
160
- "SELECT id, session, platform, workspace, role, ts, text, 0.0 AS score"
161
- f" FROM messages WHERE text LIKE ?{scope} ORDER BY ts DESC LIMIT ?",
162
- [f"%{q}%", *scope_params, limit]).fetchall()
163
- return [{"id": r["id"], "session": r["session"], "platform": r["platform"],
164
- "workspace": r["workspace"], "role": r["role"], "ts": r["ts"],
165
- "text": r["text"], "score": float(r["score"] or 0.0)} for r in rows]
175
+ try:
176
+ scope, scope_params = _scope_clauses(workspace=workspace, platform=platform)
177
+ rows = conn.execute(
178
+ "SELECT id, session, platform, workspace, role, ts, text, 0.0 AS score"
179
+ f" FROM messages WHERE text LIKE ?{scope} ORDER BY ts DESC LIMIT ?",
180
+ [f"%{q}%", *scope_params, limit]).fetchall()
181
+ return [{"id": r["id"], "session": r["session"], "platform": r["platform"],
182
+ "workspace": r["workspace"], "role": r["role"], "ts": r["ts"],
183
+ "text": r["text"], "score": 0.0} for r in rows]
184
+ except sqlite3.OperationalError:
185
+ # 表未建(空库文件):如实返回空
186
+ return []
187
+ # 长查询:FTS5 bm25 相关性排序(mode=ro 连接下 FTS 虚表只读可用)
166
188
  try:
167
189
  scope, scope_params = _scope_clauses(workspace=workspace, platform=platform,
168
190
  prefix="m.")
@@ -185,16 +207,41 @@ def search(query: str, k: int = 10, *, path=None, workspace=None,
185
207
  "text": r["text"], "score": float(r["score"] or 0.0)} for r in rows]
186
208
 
187
209
 
210
+ def _connect_readonly(path=None):
211
+ """LS-047(v5.71):只读连接——文件不存在或只读时绝不自动建库建表。"""
212
+ p = Path(path) if path else db_path()
213
+ if not p.is_file():
214
+ raise FileNotFoundError(f"会话库不存在:{p}")
215
+ conn = sqlite3.connect(f"file:{p}?mode=ro", uri=True)
216
+ conn.row_factory = sqlite3.Row
217
+ return conn
218
+
219
+
188
220
  def stats(path=None) -> dict:
189
- """库概览:总数 + 按 platform/workspace 分组计数(P1 多平台/多工作区可见性)。"""
190
- with connect(path) as conn:
191
- conn.executescript(SCHEMA)
192
- n = conn.execute("SELECT count(*) AS n FROM messages").fetchone()["n"]
193
- sess = conn.execute("SELECT count(DISTINCT session) AS n FROM messages").fetchone()["n"]
194
- by_platform = {str(r["platform"] or ""): r["n"] for r in conn.execute(
195
- "SELECT platform, count(*) AS n FROM messages GROUP BY platform ORDER BY n DESC")}
196
- by_workspace = {str(r["workspace"] or ""): r["n"] for r in conn.execute(
197
- "SELECT workspace, count(*) AS n FROM messages GROUP BY workspace ORDER BY n DESC")}
221
+ """库概览:总数 + 按 platform/workspace 分组计数(P1 多平台/多工作区可见性)。
222
+
223
+ LS-047(v5.71):只读查询用 mode=ro 连接且不自动建库建表——
224
+ 查询一个不存在的库应报"不存在"而不是凭空创建一个空库。
225
+ """
226
+ try:
227
+ conn = _connect_readonly(path)
228
+ except FileNotFoundError as exc:
229
+ return {"messages": 0, "sessions": 0, "path": str(path or db_path()),
230
+ "by_platform": {}, "by_workspace": {}, "error": str(exc)}
231
+ try:
232
+ with conn:
233
+ n = conn.execute("SELECT count(*) AS n FROM messages").fetchone()["n"]
234
+ sess = conn.execute("SELECT count(DISTINCT session) AS n FROM messages").fetchone()["n"]
235
+ by_platform = {str(r["platform"] or ""): r["n"] for r in conn.execute(
236
+ "SELECT platform, count(*) AS n FROM messages GROUP BY platform ORDER BY n DESC")}
237
+ by_workspace = {str(r["workspace"] or ""): r["n"] for r in conn.execute(
238
+ "SELECT workspace, count(*) AS n FROM messages GROUP BY workspace ORDER BY n DESC")}
239
+ except sqlite3.OperationalError as exc:
240
+ # 表还没建(空库文件):如实报告空态,不替用户建表
241
+ return {"messages": 0, "sessions": 0, "path": str(path or db_path()),
242
+ "by_platform": {}, "by_workspace": {}, "error": str(exc)}
243
+ finally:
244
+ conn.close()
198
245
  return {"messages": n, "sessions": sess, "path": str(path or db_path()),
199
246
  "by_platform": by_platform, "by_workspace": by_workspace}
200
247