lingshu-skill 5.69.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 (44) hide show
  1. package/CHANGELOG.md +66 -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 +43 -43
  8. package/package.json +1 -1
  9. package/scripts/assembler.py +8 -2
  10. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +90 -18
  11. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +66 -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/desktop_shortcut.py +10 -1
  18. package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +45 -0
  19. package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +13 -2
  20. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +5629 -5575
  21. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth_parts.py +5 -1
  22. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +62 -6
  23. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +47 -1
  24. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +12 -2
  25. package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +10 -4
  26. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +6 -1
  27. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +6 -2
  28. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +68 -21
  29. package/scripts/astrbot_plugin_lingshu/make_checksums.py +8 -4
  30. package/scripts/checkpoint.py +13 -2
  31. package/scripts/desktop_shortcut.py +10 -1
  32. package/scripts/dream.py +45 -0
  33. package/scripts/emotion.py +13 -2
  34. package/scripts/growth.py +5629 -5575
  35. package/scripts/growth_parts.py +5 -1
  36. package/scripts/memory.py +62 -6
  37. package/scripts/panel_cloud.py +47 -1
  38. package/scripts/panel_server.py +12 -2
  39. package/scripts/persona.py +10 -4
  40. package/scripts/run_tests.py +240 -171
  41. package/scripts/safety.py +6 -1
  42. package/scripts/session_import.py +6 -2
  43. package/scripts/session_rag.py +68 -21
  44. package/scripts/update_dsh_copy.ps1 +42 -6
@@ -1,171 +1,240 @@
1
- # -*- coding: utf-8 -*-
2
- """灵枢测试统一入口:**先隔离 HOME,再逐个跑**。
3
-
4
- 为什么需要它:测试都是纯标准库脚本,直接 `python tests/test_xxx.py` 跑时,
5
- `BRAIN_MEMORY_HOME` 没设就是真实记忆库——有些用例(如 `test_release_drift` 里
6
- 模拟扫描失败的那条)会通过 `core.log_event` 往真实 `~/.brain-memory/lingshu.log`
7
- 写日志。2026-11-20 就因此在本机真库日志里留下两条假的「扫描 DSH 副本失败」,
8
- 排障时把我自己带偏过一次。
9
-
10
- 本入口做三件事:
11
- 1. 把 `BRAIN_MEMORY_HOME` / `LINGSHU_GLOBAL_SKILLS` 指到临时目录(每个测试文件
12
- 一个独立目录,互不干扰,跑完删掉);
13
- 2. 逐个运行 `tests/test_*.py`,失败时打印该文件最后 40 行输出;
14
- 3. 汇总 `N/M 通过`,有失败则退出码 1。
15
-
16
- 用法:
17
- python scripts/run_tests.py # 全量
18
- python scripts/run_tests.py restore # 只跑文件名含 restore 的
19
- python scripts/run_tests.py -v # 打印每个文件的 PASS 行
20
- """
21
- from __future__ import annotations
22
-
23
- import os
24
- import shutil
25
- import subprocess
26
- import sys
27
- import tempfile
28
- from pathlib import Path
29
-
30
- ROOT = Path(__file__).resolve().parent.parent
31
- TESTS = ROOT / "tests"
32
-
33
-
34
- def main(argv: list[str]) -> int:
35
- verbose = "-v" in argv or "--verbose" in argv
36
- keywords = [a for a in argv if not a.startswith("-")]
37
- # 跑测前先把 engine 派生产物刷一遍(幂等):否则"改了 scripts 忘了 sync"会让
38
- # engine-sync 相关的测试红灯,看起来像业务 bug,实际只是产物过期(2026-11-29 连踩 3 次)。
39
- # 失败不阻断:同步脚本自己缺失/出错时照常跑测试,只是多一条提示。
40
- _sync = ROOT / "scripts" / "sync_engine.py"
41
- if _sync.is_file():
42
- try:
43
- _r = subprocess.run([sys.executable, str(_sync)], capture_output=True,
44
- text=True, encoding="utf-8", errors="replace", timeout=120)
45
- _line = next((l for l in (_r.stdout or "").splitlines() if "[sync]" in l), "")
46
- if _line:
47
- print(_line)
48
- except Exception as _e: # noqa: BLE001
49
- print(f"[提示] engine 预同步跳过:{_e}")
50
- files = sorted(TESTS.glob("test_*.py"))
51
- if keywords:
52
- files = [f for f in files if any(k in f.name for k in keywords)]
53
- if not files:
54
- print("[错误] 没有匹配的测试文件", file=sys.stderr)
55
- return 2
56
-
57
- print(f"共 {len(files)} 个测试文件(每个独立临时 HOME)")
58
- failed: list[tuple[str, str]] = []
59
- ran = 0
60
- for f in files:
61
- ran += 1
62
- tmp = Path(tempfile.mkdtemp(prefix="ls-test-"))
63
- env = dict(os.environ)
64
- env["BRAIN_MEMORY_HOME"] = str(tmp / "home")
65
- env["LINGSHU_GLOBAL_SKILLS"] = str(tmp / "skills")
66
- env["PYTHONIOENCODING"] = "utf-8"
67
- (tmp / "home").mkdir(parents=True, exist_ok=True)
68
- (tmp / "skills").mkdir(parents=True, exist_ok=True)
69
- try:
70
- r = subprocess.run([sys.executable, str(f)], capture_output=True, text=True,
71
- encoding="utf-8", errors="replace", timeout=1800, env=env)
72
- except subprocess.TimeoutExpired:
73
- failed.append((f.name, "超时(>30 分钟)"))
74
- print(f"FAIL {f.name} 超时")
75
- shutil.rmtree(tmp, ignore_errors=True)
76
- continue
77
- out = (r.stdout or "") + (r.stderr or "")
78
- if r.returncode == 0:
79
- print(f"PASS {f.name}")
80
- if verbose:
81
- for line in out.splitlines():
82
- if line.startswith(("PASS ", "FAIL ", "ERROR ", " SKIP")):
83
- print(" " + line)
84
- else:
85
- tail = "\n".join(out.strip().splitlines()[-40:])
86
- failed.append((f.name, tail))
87
- print(f"FAIL {f.name}(exit {r.returncode})")
88
- shutil.rmtree(tmp, ignore_errors=True)
89
-
90
- # —— 失败重试一次(可见,不掩盖)——
91
- # 本机 360/索引器在 66 个测试文件连跑时会造成瞬时占用,个别测试(如
92
- # checkpoint 的 git 取证、behavior baseline 的读写)会偶发失败、单跑必过。
93
- # 这里对**失败的文件整体重跑一次**:过了就标 "PASS(重试后)",仍不过才算失败。
94
- # 不做静默重试——重试过的事实必须打出来,否则等于用重试掩盖真回归。
95
- if failed:
96
- print()
97
- print("[重试] 对 %d 个失败文件各重跑一次..." % len(failed))
98
- still = []
99
- for name, detail in failed:
100
- f = next((x for x in files if x.name == name), None)
101
- if f is None:
102
- still.append((name, detail))
103
- continue
104
- tmp2 = Path(tempfile.mkdtemp(prefix="ls-retry-"))
105
- env2 = dict(os.environ)
106
- env2["BRAIN_MEMORY_HOME"] = str(tmp2 / "home")
107
- env2["LINGSHU_GLOBAL_SKILLS"] = str(tmp2 / "skills")
108
- env2["PYTHONIOENCODING"] = "utf-8"
109
- (tmp2 / "home").mkdir(parents=True, exist_ok=True)
110
- (tmp2 / "skills").mkdir(parents=True, exist_ok=True)
111
- try:
112
- r2 = subprocess.run([sys.executable, str(f)], capture_output=True, text=True,
113
- encoding="utf-8", errors="replace", timeout=1800, env=env2)
114
- except subprocess.TimeoutExpired:
115
- still.append((name, detail))
116
- shutil.rmtree(tmp2, ignore_errors=True)
117
- continue
118
- shutil.rmtree(tmp2, ignore_errors=True)
119
- if r2.returncode == 0:
120
- print(f" PASS(重试后) {name}")
121
- else:
122
- out2 = (r2.stdout or "") + (r2.stderr or "")
123
- still.append((name, "\n".join(out2.strip().splitlines()[-40:])))
124
- failed = still
125
-
126
- print()
127
- if failed:
128
- for name, detail in failed:
129
- print("=" * 70)
130
- print(f"失败:{name}")
131
- print(detail)
132
- print()
133
- print(f"{ran - len(failed)}/{ran} 通过,{len(failed)} 个失败")
134
- return 1
135
- print(f"{ran}/{ran} 通过")
136
- return 0
137
-
138
-
139
- def _ensure_utf8_stdout() -> None:
140
- """把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
141
-
142
- 为什么必须有:CI 的 windows-latest stdout 是 cp1252,脚本一 print 中文就
143
- UnicodeEncodeError 直接退出(实测 sync_engine.py 因此挂掉,Ubuntu 同期正常)。
144
- 这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
145
-
146
- reconfigure 不可用(3.6 及更早 / 被替换过的流)时静默跳过,绝不因此再崩。
147
- """
148
- for name in ("stdout", "stderr"):
149
- stream = getattr(sys, name, None)
150
- fn = getattr(stream, "reconfigure", None)
151
- if callable(fn):
152
- try:
153
- fn(encoding="utf-8", errors="replace")
154
- continue
155
- except (OSError, ValueError, AttributeError):
156
- pass
157
- # 退路:包一层 UTF-8 writer(errors=replace,坏字符变 ?,不打断程序)
158
- try:
159
- import io
160
- buf = getattr(stream, "buffer", None)
161
- if buf is not None:
162
- setattr(sys, name,
163
- io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
164
- line_buffering=True))
165
- except Exception: # noqa: BLE001
166
- pass
167
-
168
-
169
- if __name__ == "__main__":
170
- _ensure_utf8_stdout()
171
- sys.exit(main(sys.argv[1:]))
1
+ # -*- coding: utf-8 -*-
2
+ """灵枢测试统一入口:**先隔离 HOME,再逐个跑**。
3
+
4
+ 为什么需要它:测试都是纯标准库脚本,直接 `python tests/test_xxx.py` 跑时,
5
+ `BRAIN_MEMORY_HOME` 没设就是真实记忆库——有些用例(如 `test_release_drift` 里
6
+ 模拟扫描失败的那条)会通过 `core.log_event` 往真实 `~/.brain-memory/lingshu.log`
7
+ 写日志。2026-11-20 就因此在本机真库日志里留下两条假的「扫描 DSH 副本失败」,
8
+ 排障时把我自己带偏过一次。
9
+
10
+ 本入口做三件事:
11
+ 1. 把 `BRAIN_MEMORY_HOME` / `LINGSHU_GLOBAL_SKILLS` 指到临时目录(每个测试文件
12
+ 一个独立目录,互不干扰,跑完删掉);
13
+ 2. 逐个运行 `tests/test_*.py`,失败时打印该文件最后 40 行输出;
14
+ 3. 汇总 `N/M 通过`,有失败则退出码 1。
15
+
16
+ 用法:
17
+ python scripts/run_tests.py # 全量
18
+ python scripts/run_tests.py restore # 只跑文件名含 restore 的
19
+ python scripts/run_tests.py -v # 打印每个文件的 PASS 行
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import os
24
+ import shutil
25
+ import subprocess
26
+ import sys
27
+ import tempfile
28
+ from pathlib import Path
29
+
30
+ ROOT = Path(__file__).resolve().parent.parent
31
+ TESTS = ROOT / "tests"
32
+
33
+
34
+ def main(argv: list[str]) -> int:
35
+ verbose = "-v" in argv or "--verbose" in argv
36
+ keywords = [a for a in argv if not a.startswith("-")]
37
+ # 跑测前先把 engine 派生产物刷一遍(幂等):否则"改了 scripts 忘了 sync"会让
38
+ # engine-sync 相关的测试红灯,看起来像业务 bug,实际只是产物过期(2026-11-29 连踩 3 次)。
39
+ # 失败不阻断:同步脚本自己缺失/出错时照常跑测试,只是多一条提示。
40
+ _sync = ROOT / "scripts" / "sync_engine.py"
41
+ if _sync.is_file():
42
+ # LS-141(v5.70):run_tests 必须检查 engine 预同步退出码!
43
+ # 旧实现同步失败只打提示继续跑——engine-sync 相关测试会因产物过期红灯,
44
+ # 或更糟:过期的 engine 副本让某些测试**假通过**。同步非零退出必须整体失败。
45
+ try:
46
+ _r = subprocess.run([sys.executable, str(_sync)], capture_output=True,
47
+ text=True, encoding="utf-8", errors="replace", timeout=120)
48
+ _line = next((l for l in (_r.stdout or "").splitlines() if "[sync]" in l), "")
49
+ if _line:
50
+ print(_line)
51
+ if _r.returncode != 0:
52
+ _err = (_r.stderr or _r.stdout or "").strip()[-500:]
53
+ print(f"[错误] engine 预同步失败(exit {_r.returncode}),中止测试:{_err}",
54
+ file=sys.stderr)
55
+ return 2
56
+ except Exception as _e: # noqa: BLE001
57
+ print(f"[错误] engine 预同步异常,中止测试:{_e}", file=sys.stderr)
58
+ return 2
59
+ files = sorted(TESTS.glob("test_*.py"))
60
+ if keywords:
61
+ files = [f for f in files if any(k in f.name for k in keywords)]
62
+ if not files:
63
+ print("[错误] 没有匹配的测试文件", file=sys.stderr)
64
+ return 2
65
+
66
+ print(f"共 {len(files)} 个测试文件(每个独立临时 HOME)")
67
+ failed: list[tuple[str, str]] = []
68
+ ran = 0
69
+ for f in files:
70
+ ran += 1
71
+ tmp = Path(tempfile.mkdtemp(prefix="ls-test-"))
72
+ env = dict(os.environ)
73
+ env["BRAIN_MEMORY_HOME"] = str(tmp / "home")
74
+ env["LINGSHU_GLOBAL_SKILLS"] = str(tmp / "skills")
75
+ # LS-145(v5.70):隔离测试中的桌面快捷方式路径——重定向到临时目录,
76
+ # 验证真实用户桌面不出现测试 .lnk。
77
+ env["LINGSHU_TEST_DESKTOP_DIR"] = str(tmp / "desktop")
78
+ env["PYTHONIOENCODING"] = "utf-8"
79
+ (tmp / "home").mkdir(parents=True, exist_ok=True)
80
+ (tmp / "skills").mkdir(parents=True, exist_ok=True)
81
+ (tmp / "desktop").mkdir(parents=True, exist_ok=True)
82
+ try:
83
+ # LS-142(v5.70):测试超时终止整个子进程树!
84
+ # Windows 上用 CREATE_NEW_PROCESS_GROUP + taskkill /T;POSIX 用进程组 kill。
85
+ # 超时的测试可能拉起面板/服务等后代进程——只杀直接子进程会留下孤儿占用端口,
86
+ # 干扰后续重试。
87
+ import subprocess as _sp
88
+ _creation = _sp.CREATE_NEW_PROCESS_GROUP if os.name == "nt" else 0
89
+ r = subprocess.run([sys.executable, str(f)], capture_output=True, text=True,
90
+ encoding="utf-8", errors="replace", timeout=1800, env=env,
91
+ creationflags=_creation if os.name == "nt" else 0,
92
+ start_new_session=(os.name != "nt"))
93
+ except subprocess.TimeoutExpired as _te:
94
+ # 超时后杀整棵进程树
95
+ try:
96
+ if os.name == "nt":
97
+ subprocess.run(["taskkill", "/F", "/T", "/PID", str(_te.pid or 0)],
98
+ capture_output=True, timeout=10)
99
+ else:
100
+ import signal
101
+ os.killpg(os.getpgid(_te.pid), signal.SIGKILL)
102
+ except Exception:
103
+ pass
104
+ failed.append((f.name, "超时(>30 分钟)"))
105
+ print(f"FAIL {f.name} 超时")
106
+ shutil.rmtree(tmp, ignore_errors=True)
107
+ continue
108
+ out = (r.stdout or "") + (r.stderr or "")
109
+ if r.returncode == 0:
110
+ print(f"PASS {f.name}")
111
+ if verbose:
112
+ for line in out.splitlines():
113
+ if line.startswith(("PASS ", "FAIL ", "ERROR ", " SKIP")):
114
+ print(" " + line)
115
+ else:
116
+ tail = "\n".join(out.strip().splitlines()[-40:])
117
+ failed.append((f.name, tail))
118
+ print(f"FAIL {f.name}(exit {r.returncode})")
119
+ shutil.rmtree(tmp, ignore_errors=True)
120
+
121
+ # —— 失败重试一次(可见,不掩盖)——
122
+ # 本机 360/索引器在 66 个测试文件连跑时会造成瞬时占用,个别测试(如
123
+ # checkpoint 的 git 取证、behavior baseline 的读写)会偶发失败、单跑必过。
124
+ # 这里对**失败的文件整体重跑一次**:过了就标 "PASS(重试后)",仍不过才算失败。
125
+ # 不做静默重试——重试过的事实必须打出来,否则等于用重试掩盖真回归。
126
+ if failed:
127
+ print()
128
+ print("[重试] 对 %d 个失败文件各重跑一次..." % len(failed))
129
+ still = []
130
+ for name, detail in failed:
131
+ f = next((x for x in files if x.name == name), None)
132
+ if f is None:
133
+ still.append((name, detail))
134
+ continue
135
+ tmp2 = Path(tempfile.mkdtemp(prefix="ls-retry-"))
136
+ env2 = dict(os.environ)
137
+ env2["BRAIN_MEMORY_HOME"] = str(tmp2 / "home")
138
+ env2["LINGSHU_GLOBAL_SKILLS"] = str(tmp2 / "skills")
139
+ env2["LINGSHU_TEST_DESKTOP_DIR"] = str(tmp2 / "desktop")
140
+ env2["PYTHONIOENCODING"] = "utf-8"
141
+ (tmp2 / "home").mkdir(parents=True, exist_ok=True)
142
+ (tmp2 / "skills").mkdir(parents=True, exist_ok=True)
143
+ (tmp2 / "desktop").mkdir(parents=True, exist_ok=True)
144
+ try:
145
+ r2 = subprocess.run([sys.executable, str(f)], capture_output=True, text=True,
146
+ encoding="utf-8", errors="replace", timeout=1800, env=env2)
147
+ except subprocess.TimeoutExpired:
148
+ still.append((name, detail))
149
+ shutil.rmtree(tmp2, ignore_errors=True)
150
+ continue
151
+ shutil.rmtree(tmp2, ignore_errors=True)
152
+ if r2.returncode == 0:
153
+ print(f" PASS(重试后) {name}")
154
+ else:
155
+ out2 = (r2.stdout or "") + (r2.stderr or "")
156
+ still.append((name, "\n".join(out2.strip().splitlines()[-40:])))
157
+ failed = still
158
+
159
+ # LS-143(v5.70):将 .mjs 测试纳入统一测试与 CI!
160
+ # 旧实现只跑 test_*.py——test_resilience.mjs / test_timectx_fold.mjs /
161
+ # test_ls091_guard_lru.mjs 从未被统一门禁执行,回归发现不了。
162
+ node_files = sorted(TESTS.glob("test_*.mjs"))
163
+ node_ok = 0
164
+ if node_files:
165
+ _node = shutil.which("node")
166
+ if _node is None:
167
+ # LS-144(v5.70):缺少 Node 时明确 SKIP/FAIL 而非静默 PASS!
168
+ print("[SKIP] 未找到 node 可执行文件,跳过 %d 个 .mjs 测试"
169
+ "(JS 门禁未检查,发布前请安装 Node)" % len(node_files))
170
+ failed.append((".mjs 测试(全部)", "缺少 node:JS 测试未执行(SKIP 不算通过)"))
171
+ else:
172
+ for mf in node_files:
173
+ ran += 1
174
+ try:
175
+ _env = dict(os.environ)
176
+ _env["BRAIN_MEMORY_HOME"] = str(tempfile.mkdtemp(prefix="ls-mjs-") + "/home")
177
+ rm = subprocess.run([_node, "--test", str(mf)], capture_output=True,
178
+ text=True, encoding="utf-8", errors="replace",
179
+ timeout=300, env=_env)
180
+ out_m = (rm.stdout or "") + (rm.stderr or "")
181
+ if rm.returncode == 0:
182
+ node_ok += 1
183
+ print(f"PASS {mf.name}")
184
+ else:
185
+ tail_m = "\n".join(out_m.strip().splitlines()[-30:])
186
+ failed.append((mf.name, tail_m))
187
+ print(f"FAIL {mf.name}(exit {rm.returncode})")
188
+ except subprocess.TimeoutExpired:
189
+ failed.append((mf.name, "超时(>5 分钟)"))
190
+ print(f"FAIL {mf.name} 超时")
191
+ except Exception as _ne: # noqa: BLE001
192
+ failed.append((mf.name, str(_ne)))
193
+ print(f"FAIL {mf.name}:{_ne}")
194
+
195
+ print()
196
+ if failed:
197
+ for name, detail in failed:
198
+ print("=" * 70)
199
+ print(f"失败:{name}")
200
+ print(detail)
201
+ print()
202
+ print(f"{ran - len(failed)}/{ran} 通过,{len(failed)} 个失败")
203
+ return 1
204
+ print(f"{ran}/{ran} 通过")
205
+ return 0
206
+
207
+
208
+ def _ensure_utf8_stdout() -> None:
209
+ """把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
210
+
211
+ 为什么必须有:CI 的 windows-latest stdout 是 cp1252,脚本一 print 中文就
212
+ UnicodeEncodeError 直接退出(实测 sync_engine.py 因此挂掉,Ubuntu 同期正常)。
213
+ 这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
214
+
215
+ reconfigure 不可用(3.6 及更早 / 被替换过的流)时静默跳过,绝不因此再崩。
216
+ """
217
+ for name in ("stdout", "stderr"):
218
+ stream = getattr(sys, name, None)
219
+ fn = getattr(stream, "reconfigure", None)
220
+ if callable(fn):
221
+ try:
222
+ fn(encoding="utf-8", errors="replace")
223
+ continue
224
+ except (OSError, ValueError, AttributeError):
225
+ pass
226
+ # 退路:包一层 UTF-8 writer(errors=replace,坏字符变 ?,不打断程序)
227
+ try:
228
+ import io
229
+ buf = getattr(stream, "buffer", None)
230
+ if buf is not None:
231
+ setattr(sys, name,
232
+ io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
233
+ line_buffering=True))
234
+ except Exception: # noqa: BLE001
235
+ pass
236
+
237
+
238
+ if __name__ == "__main__":
239
+ _ensure_utf8_stdout()
240
+ sys.exit(main(sys.argv[1:]))
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