lingshu-skill 5.24.0 → 5.28.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/CHANGELOG.md +181 -0
- package/README.md +1577 -1577
- package/SKILL-lite.md +59 -59
- package/SKILL-tiny.md +38 -38
- package/SKILL.md +405 -404
- package/cordis-plugin/lingshu-cron/plugin.js +15 -5
- package/package.json +52 -52
- package/scripts/_ci_env_probe.py +81 -0
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +23 -22
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +181 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +1577 -1577
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +59 -59
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +38 -38
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +405 -404
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_ci_env_probe.py +81 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +28 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +218 -190
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +28 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +43 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +74 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/coverage_report.py +195 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +28 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/make_icon.py +24 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +221 -219
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +10 -3
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +28 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +470 -460
- package/scripts/astrbot_plugin_lingshu/engine/scripts/release.py +42 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +29 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety_net.py +12 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +28 -0
- package/scripts/astrbot_plugin_lingshu/make_checksums.py +28 -0
- package/scripts/behavior_baseline.py +28 -0
- package/scripts/bench.py +218 -190
- package/scripts/check_pressure_sync.py +31 -0
- package/scripts/check_tag.py +28 -0
- package/scripts/check_version.py +47 -0
- package/scripts/cli.py +43 -0
- package/scripts/core.py +74 -0
- package/scripts/coverage_report.py +195 -0
- package/scripts/growth.py +28 -0
- package/scripts/make_icon.py +24 -0
- package/scripts/make_manifest.py +285 -254
- package/scripts/make_plugin_zip.py +28 -0
- package/scripts/mem_dialogue.py +221 -219
- package/scripts/memory.py +10 -3
- package/scripts/panel_build.py +31 -0
- package/scripts/panel_server.py +28 -0
- package/scripts/panels.py +470 -460
- package/scripts/release.py +42 -0
- package/scripts/run_tests.py +31 -0
- package/scripts/safety.py +29 -1
- package/scripts/safety_net.py +12 -0
- package/scripts/session_import.py +28 -0
- package/scripts/sync_engine.py +170 -139
- package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +0 -49
- package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +0 -53
- package/docs//345/217/221/345/270/203/350/207/252/345/212/250/345/214/226.md +0 -54
- package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +0 -189
|
@@ -121,6 +121,20 @@ def do_bump(new_ver: str, title: str) -> int:
|
|
|
121
121
|
print(f"[release] {rel} 没找到版本标记 {o!r},拒绝继续", file=sys.stderr)
|
|
122
122
|
return 1
|
|
123
123
|
p.write_bytes(b.replace(o, n, 1))
|
|
124
|
+
# 1b) SKILL-lite / SKILL-tiny 的 version 跟着走。
|
|
125
|
+
# 它们不触发"必须升版"(裁剪文档,正文可能长期不动),但头部的 version 若十年不动,
|
|
126
|
+
# 会让人误判"这份文档对得上引擎"。用字节级正则改,保 BOM 与原换行。
|
|
127
|
+
for rel in ("SKILL-lite.md", "SKILL-tiny.md"):
|
|
128
|
+
lp = ROOT / rel
|
|
129
|
+
if not lp.is_file():
|
|
130
|
+
continue
|
|
131
|
+
b = lp.read_bytes()
|
|
132
|
+
nb, cnt = re.subn(rb"^version:\s*[\d.]+",
|
|
133
|
+
f"version: {new_ver}".encode(), b, count=1, flags=re.M)
|
|
134
|
+
if cnt:
|
|
135
|
+
lp.write_bytes(nb)
|
|
136
|
+
print(f"[release] {rel} version → {new_ver}")
|
|
137
|
+
|
|
124
138
|
# CHANGELOG 首节改写为新版本(占位,正文留空由维护者补)
|
|
125
139
|
cl = ROOT / "CHANGELOG.md"
|
|
126
140
|
t = cl.read_text(encoding="utf-8")
|
|
@@ -241,5 +255,33 @@ def main() -> int:
|
|
|
241
255
|
return do_status()
|
|
242
256
|
|
|
243
257
|
|
|
258
|
+
def _ensure_utf8_stdout() -> None:
|
|
259
|
+
"""把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
|
|
260
|
+
|
|
261
|
+
CI 的 windows-latest stdout 是 cp1252:脚本一 print 中文就 UnicodeEncodeError
|
|
262
|
+
直接退出(实测 sync_engine.py / make_checksums.py 都因此挂过,Ubuntu 同期正常)。
|
|
263
|
+
这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
|
|
264
|
+
"""
|
|
265
|
+
for name in ("stdout", "stderr"):
|
|
266
|
+
stream = getattr(sys, name, None)
|
|
267
|
+
fn = getattr(stream, "reconfigure", None)
|
|
268
|
+
if callable(fn):
|
|
269
|
+
try:
|
|
270
|
+
fn(encoding="utf-8", errors="replace")
|
|
271
|
+
continue
|
|
272
|
+
except (OSError, ValueError, AttributeError):
|
|
273
|
+
pass
|
|
274
|
+
try:
|
|
275
|
+
import io
|
|
276
|
+
buf = getattr(stream, "buffer", None)
|
|
277
|
+
if buf is not None:
|
|
278
|
+
setattr(sys, name,
|
|
279
|
+
io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
|
|
280
|
+
line_buffering=True))
|
|
281
|
+
except Exception: # noqa: BLE001
|
|
282
|
+
pass
|
|
283
|
+
|
|
284
|
+
|
|
244
285
|
if __name__ == "__main__":
|
|
286
|
+
_ensure_utf8_stdout()
|
|
245
287
|
sys.exit(main())
|
|
@@ -324,10 +324,33 @@ def is_interactive() -> bool:
|
|
|
324
324
|
return False
|
|
325
325
|
|
|
326
326
|
|
|
327
|
+
def require_token(action: str, given: str, expected: str, *, hint: str = "") -> None:
|
|
328
|
+
"""破坏性操作的一次性确认码校验(与 confirm_destructive 同属 safety 的一套原语)。
|
|
329
|
+
|
|
330
|
+
为什么不并进 y/N:这类操作要能被**程序 / AI 调用时强制显式写下指纹**,
|
|
331
|
+
而那种场合 stdin 不是终端,交互提示根本不会出现。
|
|
332
|
+
这样说清分工,比"两套逻辑各写各的"更难出错:
|
|
333
|
+
· confirm_destructive —— 有终端时的人机确认(--yes 或 y)
|
|
334
|
+
· require_token —— 任何场合都必须匹配的指纹
|
|
335
|
+
|
|
336
|
+
不匹配抛 ValueError(调用方负责转成退出码)。
|
|
337
|
+
"""
|
|
338
|
+
if not expected:
|
|
339
|
+
raise ValueError(f"[{action}] 缺少确认码基准(内部错误)")
|
|
340
|
+
if not given or str(given) != str(expected):
|
|
341
|
+
msg = (f"[{action}] 需显式确认:确认码不匹配"
|
|
342
|
+
f"(应为目标 id 的前 {len(str(expected))} 位)")
|
|
343
|
+
if hint:
|
|
344
|
+
msg += f"。{hint}"
|
|
345
|
+
raise ValueError(msg)
|
|
346
|
+
|
|
347
|
+
|
|
327
348
|
def confirm_destructive(action: str, impact: str | list[str], *,
|
|
328
349
|
assume_yes: bool = False,
|
|
329
350
|
hint: str = "",
|
|
330
|
-
stream=None
|
|
351
|
+
stream=None,
|
|
352
|
+
token: str = "",
|
|
353
|
+
expect_token: str = "") -> bool:
|
|
331
354
|
"""破坏性操作的统一确认。返回 True=可以继续,False=调用方应中止(或被取消)。
|
|
332
355
|
|
|
333
356
|
参数:
|
|
@@ -343,6 +366,11 @@ def confirm_destructive(action: str, impact: str | list[str], *,
|
|
|
343
366
|
for line in lines:
|
|
344
367
|
print(f" - {line}", file=out)
|
|
345
368
|
|
|
369
|
+
# 指纹校验放在最前:设了 expect_token 就必须匹配,--yes 也绕不过。
|
|
370
|
+
# 这样"确认码"与"影响面提示"是同一处代码,不会出现某个入口忘了校验。
|
|
371
|
+
if expect_token:
|
|
372
|
+
require_token(action, token, expect_token, hint=hint)
|
|
373
|
+
|
|
346
374
|
if assume_yes:
|
|
347
375
|
print(f"[{action}] 已通过 --yes 确认。", file=out)
|
|
348
376
|
if hint:
|
|
@@ -339,6 +339,13 @@ def guarded_write(reason: str, writer, names=None, allow_shrink=()) -> dict:
|
|
|
339
339
|
report["error"] = f"写入异常已回滚:{err}"
|
|
340
340
|
except Exception as rexc: # noqa: BLE001
|
|
341
341
|
report["error"] = f"写入异常且回滚失败:{err} / {rexc}"
|
|
342
|
+
# 最危险的一档:写入出了问题、回滚也没成功 ⇒ 数据处于脏状态,
|
|
343
|
+
# 却只体现在返回值里。计一次数,让 doctor 的 swallowed 项能看见。
|
|
344
|
+
try:
|
|
345
|
+
import core as _c
|
|
346
|
+
_c.swallow("safety.rollback", rexc, where="safety_net.guarded_write")
|
|
347
|
+
except Exception: # noqa: BLE001
|
|
348
|
+
pass
|
|
342
349
|
return report
|
|
343
350
|
if _verify_enabled():
|
|
344
351
|
v = verify(names, allow_shrink=allow_shrink)
|
|
@@ -352,4 +359,9 @@ def guarded_write(reason: str, writer, names=None, allow_shrink=()) -> dict:
|
|
|
352
359
|
report["ok"] = True # 已回滚,数据一致
|
|
353
360
|
except Exception as rexc: # noqa: BLE001
|
|
354
361
|
report["issues"].append(f"回滚失败:{rexc}")
|
|
362
|
+
try:
|
|
363
|
+
import core as _c
|
|
364
|
+
_c.swallow("safety.rollback", rexc, where="safety_net.guarded_write")
|
|
365
|
+
except Exception: # noqa: BLE001
|
|
366
|
+
pass
|
|
355
367
|
return report
|
|
@@ -732,5 +732,33 @@ def main(argv=None) -> int:
|
|
|
732
732
|
return 0 if report.get("ok") else 1
|
|
733
733
|
|
|
734
734
|
|
|
735
|
+
def _ensure_utf8_stdout() -> None:
|
|
736
|
+
"""把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
|
|
737
|
+
|
|
738
|
+
CI 的 windows-latest stdout 是 cp1252:脚本一 print 中文就 UnicodeEncodeError
|
|
739
|
+
直接退出(实测 sync_engine.py / make_checksums.py 都因此挂过,Ubuntu 同期正常)。
|
|
740
|
+
这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
|
|
741
|
+
"""
|
|
742
|
+
for name in ("stdout", "stderr"):
|
|
743
|
+
stream = getattr(sys, name, None)
|
|
744
|
+
fn = getattr(stream, "reconfigure", None)
|
|
745
|
+
if callable(fn):
|
|
746
|
+
try:
|
|
747
|
+
fn(encoding="utf-8", errors="replace")
|
|
748
|
+
continue
|
|
749
|
+
except (OSError, ValueError, AttributeError):
|
|
750
|
+
pass
|
|
751
|
+
try:
|
|
752
|
+
import io
|
|
753
|
+
buf = getattr(stream, "buffer", None)
|
|
754
|
+
if buf is not None:
|
|
755
|
+
setattr(sys, name,
|
|
756
|
+
io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
|
|
757
|
+
line_buffering=True))
|
|
758
|
+
except Exception: # noqa: BLE001
|
|
759
|
+
pass
|
|
760
|
+
|
|
761
|
+
|
|
735
762
|
if __name__ == "__main__":
|
|
763
|
+
_ensure_utf8_stdout()
|
|
736
764
|
sys.exit(main())
|
|
@@ -83,5 +83,33 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
83
83
|
return 0
|
|
84
84
|
|
|
85
85
|
|
|
86
|
+
def _ensure_utf8_stdout() -> None:
|
|
87
|
+
"""把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
|
|
88
|
+
|
|
89
|
+
CI 的 windows-latest stdout 是 cp1252:脚本一 print 中文就 UnicodeEncodeError
|
|
90
|
+
直接退出(实测 sync_engine.py / make_checksums.py 都因此挂过,Ubuntu 同期正常)。
|
|
91
|
+
这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
|
|
92
|
+
"""
|
|
93
|
+
for name in ("stdout", "stderr"):
|
|
94
|
+
stream = getattr(sys, name, None)
|
|
95
|
+
fn = getattr(stream, "reconfigure", None)
|
|
96
|
+
if callable(fn):
|
|
97
|
+
try:
|
|
98
|
+
fn(encoding="utf-8", errors="replace")
|
|
99
|
+
continue
|
|
100
|
+
except (OSError, ValueError, AttributeError):
|
|
101
|
+
pass
|
|
102
|
+
try:
|
|
103
|
+
import io
|
|
104
|
+
buf = getattr(stream, "buffer", None)
|
|
105
|
+
if buf is not None:
|
|
106
|
+
setattr(sys, name,
|
|
107
|
+
io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
|
|
108
|
+
line_buffering=True))
|
|
109
|
+
except Exception: # noqa: BLE001
|
|
110
|
+
pass
|
|
111
|
+
|
|
112
|
+
|
|
86
113
|
if __name__ == "__main__":
|
|
114
|
+
_ensure_utf8_stdout()
|
|
87
115
|
sys.exit(main())
|
|
@@ -278,5 +278,33 @@ def main(argv: list[str]) -> int:
|
|
|
278
278
|
return check(a.quiet)
|
|
279
279
|
|
|
280
280
|
|
|
281
|
+
def _ensure_utf8_stdout() -> None:
|
|
282
|
+
"""把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
|
|
283
|
+
|
|
284
|
+
CI 的 windows-latest stdout 是 cp1252:脚本一 print 中文就 UnicodeEncodeError
|
|
285
|
+
直接退出(实测 sync_engine.py / make_checksums.py 都因此挂过,Ubuntu 同期正常)。
|
|
286
|
+
这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
|
|
287
|
+
"""
|
|
288
|
+
for name in ("stdout", "stderr"):
|
|
289
|
+
stream = getattr(sys, name, None)
|
|
290
|
+
fn = getattr(stream, "reconfigure", None)
|
|
291
|
+
if callable(fn):
|
|
292
|
+
try:
|
|
293
|
+
fn(encoding="utf-8", errors="replace")
|
|
294
|
+
continue
|
|
295
|
+
except (OSError, ValueError, AttributeError):
|
|
296
|
+
pass
|
|
297
|
+
try:
|
|
298
|
+
import io
|
|
299
|
+
buf = getattr(stream, "buffer", None)
|
|
300
|
+
if buf is not None:
|
|
301
|
+
setattr(sys, name,
|
|
302
|
+
io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
|
|
303
|
+
line_buffering=True))
|
|
304
|
+
except Exception: # noqa: BLE001
|
|
305
|
+
pass
|
|
306
|
+
|
|
307
|
+
|
|
281
308
|
if __name__ == "__main__":
|
|
309
|
+
_ensure_utf8_stdout()
|
|
282
310
|
sys.exit(main(sys.argv[1:]))
|
package/scripts/bench.py
CHANGED
|
@@ -1,192 +1,220 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
# -*- coding: utf-8 -*-
|
|
3
|
-
"""灵枢 —— 性能基准(第四轮提案 #5)。
|
|
4
|
-
|
|
5
|
-
生成 N 条合成记忆到**临时隔离 HOME**(绝不碰真实记忆库),量四条主路径的
|
|
6
|
-
p50/p95 耗时,回答"5000 条时还快不快"这类问题——改召回阈值/换 embed 兜底
|
|
7
|
-
前后各跑一次,用数字代替手感。
|
|
8
|
-
|
|
9
|
-
用法:
|
|
10
|
-
python scripts/bench.py # 默认 1000 条,常规套件
|
|
11
|
-
python scripts/bench.py --n 5000 # 大库压力
|
|
12
|
-
python scripts/bench.py --quick # 300 条,1 分钟内出结果
|
|
13
|
-
python scripts/bench.py --quick --save # 把本次 p50/p95 存成基线
|
|
14
|
-
python scripts/bench.py --quick --check # 与基线比对,超 1.5 倍即失败
|
|
15
|
-
|
|
16
|
-
零依赖,纯标准库。退出码 0=全部完成;--check 超阈值退出 1。
|
|
17
|
-
基线文件放 tests/bench-baseline.json(tests 不进发布 manifest,随仓库走)。
|
|
18
|
-
"""
|
|
19
|
-
|
|
20
|
-
from __future__ import annotations
|
|
21
|
-
|
|
22
|
-
import argparse
|
|
23
|
-
import json
|
|
24
|
-
import random
|
|
25
|
-
import shutil
|
|
26
|
-
import statistics
|
|
27
|
-
import subprocess
|
|
28
|
-
import sys
|
|
29
|
-
import tempfile
|
|
30
|
-
import time
|
|
31
|
-
from pathlib import Path
|
|
32
|
-
|
|
33
|
-
ROOT = Path(__file__).resolve().parent
|
|
34
|
-
BRAIN = ROOT / "brain.py"
|
|
35
|
-
BASELINE = ROOT.parent / "tests" / "bench-baseline.json"
|
|
36
|
-
CHECK_RATIO = 1.5
|
|
37
|
-
|
|
38
|
-
TOPICS = ["部署", "数据库", "前端", "算法", "会议", "测试", "文档", "安全",
|
|
39
|
-
"缓存", "权限", "日志", "重构", "网络", "备份", "监控", "配置"]
|
|
40
|
-
USERS = ["alice", "bob", "carol"]
|
|
41
|
-
PROJECTS = ["proj-alpha", "proj-beta", "proj-gamma"]
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
def _run(args: list, home: Path, timeout: float = 120, strict: bool = True) -> tuple[float, str]:
|
|
45
|
-
"""跑一次 brain.py 子进程,返回 (耗时秒, stdout)。strict=False 时不校验退出码。"""
|
|
46
|
-
env = {**__import__("os").environ,
|
|
47
|
-
"BRAIN_MEMORY_HOME": str(home),
|
|
48
|
-
"BRAIN_MEMORY_BACKUP_DIR": str(home / "backups")}
|
|
49
|
-
t0 = time.perf_counter()
|
|
50
|
-
r = subprocess.run([sys.executable, str(BRAIN), *args],
|
|
51
|
-
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, env=env)
|
|
52
|
-
dt = time.perf_counter() - t0
|
|
53
|
-
if strict and r.returncode not in (0,):
|
|
54
|
-
raise RuntimeError(f"brain.py {' '.join(args)} 退出码 {r.returncode}: {r.stderr[-300:]}")
|
|
55
|
-
return dt, r.stdout
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
def _pctl(samples: list) -> dict:
|
|
59
|
-
"""p50 / p95(样本少时 p95 就是最大值近似)。"""
|
|
60
|
-
xs = sorted(samples)
|
|
61
|
-
n = len(xs)
|
|
62
|
-
return {"p50": statistics.median(xs),
|
|
63
|
-
"p95": xs[max(0, int(round(n * 0.95)) - 1)] if n else 0.0,
|
|
64
|
-
"n": n}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
def _save_baseline(n: int, results: dict) -> None:
|
|
68
|
-
"""把本次 p50/p95 写成基线(同机同 n 的后续 --check 用它比对)。"""
|
|
69
|
-
data = {"n": n, "generated": time.strftime("%Y-%m-%d %H:%M"),
|
|
70
|
-
"results": {k: _pctl(v) for k, v in results.items() if v}}
|
|
71
|
-
BASELINE.parent.mkdir(parents=True, exist_ok=True)
|
|
72
|
-
BASELINE.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n",
|
|
73
|
-
encoding="utf-8")
|
|
74
|
-
print(f"[bench] 基线已保存:{BASELINE}")
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
def _check_baseline(n: int, results: dict) -> int:
|
|
78
|
-
"""与基线比对 p50;超过 CHECK_RATIO 倍告警并返回 1。
|
|
79
|
-
|
|
80
|
-
不同 n / 不同机器之间绝对值不可比,所以只做"同机回归"的粗门禁;
|
|
81
|
-
没有基线文件时直接放行(首次接入不阻塞)。
|
|
82
|
-
"""
|
|
83
|
-
if not BASELINE.is_file():
|
|
84
|
-
print(f"[bench] 未找到基线 {BASELINE},跳过比对(先跑一次 --save)")
|
|
85
|
-
return 0
|
|
86
|
-
try:
|
|
87
|
-
base = json.loads(BASELINE.read_text(encoding="utf-8-sig"))
|
|
88
|
-
except (OSError, ValueError) as e:
|
|
89
|
-
print(f"[bench] 基线读取失败({e}),跳过比对")
|
|
90
|
-
return 0
|
|
91
|
-
base_res = base.get("results") or {}
|
|
92
|
-
if int(base.get("n") or 0) != n:
|
|
93
|
-
print(f"[bench] 基线 n={base.get('n')} 与本轮 n={n} 不同,仅打印不判定")
|
|
94
|
-
worst = 0
|
|
95
|
-
print("\n===== 与基线比对(阈值 ×{:.1f})=====".format(CHECK_RATIO))
|
|
96
|
-
for name, samples in results.items():
|
|
97
|
-
if not samples or name not in base_res:
|
|
98
|
-
continue
|
|
99
|
-
cur = _pctl(samples)["p50"]
|
|
100
|
-
old = float(base_res[name].get("p50") or 0)
|
|
101
|
-
if old <= 0:
|
|
102
|
-
continue
|
|
103
|
-
ratio = cur / old
|
|
104
|
-
flag = "WARN" if ratio > CHECK_RATIO else "ok"
|
|
105
|
-
print(f"{name:<10} 基线 {old*1000:7.0f} ms → 本次 {cur*1000:7.0f} ms ×{ratio:.2f} [{flag}]")
|
|
106
|
-
if ratio > CHECK_RATIO:
|
|
107
|
-
worst = 1
|
|
108
|
-
return worst
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
def main() -> int:
|
|
113
|
-
ap = argparse.ArgumentParser(description="灵枢性能基准(隔离临时库,不碰真实数据)")
|
|
114
|
-
ap.add_argument("--n", type=int, default=1000, help="合成记忆条数(默认 1000)")
|
|
115
|
-
ap.add_argument("--quick", action="store_true", help="快速模式:n=300")
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""灵枢 —— 性能基准(第四轮提案 #5)。
|
|
4
|
+
|
|
5
|
+
生成 N 条合成记忆到**临时隔离 HOME**(绝不碰真实记忆库),量四条主路径的
|
|
6
|
+
p50/p95 耗时,回答"5000 条时还快不快"这类问题——改召回阈值/换 embed 兜底
|
|
7
|
+
前后各跑一次,用数字代替手感。
|
|
8
|
+
|
|
9
|
+
用法:
|
|
10
|
+
python scripts/bench.py # 默认 1000 条,常规套件
|
|
11
|
+
python scripts/bench.py --n 5000 # 大库压力
|
|
12
|
+
python scripts/bench.py --quick # 300 条,1 分钟内出结果
|
|
13
|
+
python scripts/bench.py --quick --save # 把本次 p50/p95 存成基线
|
|
14
|
+
python scripts/bench.py --quick --check # 与基线比对,超 1.5 倍即失败
|
|
15
|
+
|
|
16
|
+
零依赖,纯标准库。退出码 0=全部完成;--check 超阈值退出 1。
|
|
17
|
+
基线文件放 tests/bench-baseline.json(tests 不进发布 manifest,随仓库走)。
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import json
|
|
24
|
+
import random
|
|
25
|
+
import shutil
|
|
26
|
+
import statistics
|
|
27
|
+
import subprocess
|
|
28
|
+
import sys
|
|
29
|
+
import tempfile
|
|
30
|
+
import time
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
ROOT = Path(__file__).resolve().parent
|
|
34
|
+
BRAIN = ROOT / "brain.py"
|
|
35
|
+
BASELINE = ROOT.parent / "tests" / "bench-baseline.json"
|
|
36
|
+
CHECK_RATIO = 1.5
|
|
37
|
+
|
|
38
|
+
TOPICS = ["部署", "数据库", "前端", "算法", "会议", "测试", "文档", "安全",
|
|
39
|
+
"缓存", "权限", "日志", "重构", "网络", "备份", "监控", "配置"]
|
|
40
|
+
USERS = ["alice", "bob", "carol"]
|
|
41
|
+
PROJECTS = ["proj-alpha", "proj-beta", "proj-gamma"]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _run(args: list, home: Path, timeout: float = 120, strict: bool = True) -> tuple[float, str]:
|
|
45
|
+
"""跑一次 brain.py 子进程,返回 (耗时秒, stdout)。strict=False 时不校验退出码。"""
|
|
46
|
+
env = {**__import__("os").environ,
|
|
47
|
+
"BRAIN_MEMORY_HOME": str(home),
|
|
48
|
+
"BRAIN_MEMORY_BACKUP_DIR": str(home / "backups")}
|
|
49
|
+
t0 = time.perf_counter()
|
|
50
|
+
r = subprocess.run([sys.executable, str(BRAIN), *args],
|
|
51
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, env=env)
|
|
52
|
+
dt = time.perf_counter() - t0
|
|
53
|
+
if strict and r.returncode not in (0,):
|
|
54
|
+
raise RuntimeError(f"brain.py {' '.join(args)} 退出码 {r.returncode}: {r.stderr[-300:]}")
|
|
55
|
+
return dt, r.stdout
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _pctl(samples: list) -> dict:
|
|
59
|
+
"""p50 / p95(样本少时 p95 就是最大值近似)。"""
|
|
60
|
+
xs = sorted(samples)
|
|
61
|
+
n = len(xs)
|
|
62
|
+
return {"p50": statistics.median(xs),
|
|
63
|
+
"p95": xs[max(0, int(round(n * 0.95)) - 1)] if n else 0.0,
|
|
64
|
+
"n": n}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _save_baseline(n: int, results: dict) -> None:
|
|
68
|
+
"""把本次 p50/p95 写成基线(同机同 n 的后续 --check 用它比对)。"""
|
|
69
|
+
data = {"n": n, "generated": time.strftime("%Y-%m-%d %H:%M"),
|
|
70
|
+
"results": {k: _pctl(v) for k, v in results.items() if v}}
|
|
71
|
+
BASELINE.parent.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
BASELINE.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n",
|
|
73
|
+
encoding="utf-8")
|
|
74
|
+
print(f"[bench] 基线已保存:{BASELINE}")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _check_baseline(n: int, results: dict) -> int:
|
|
78
|
+
"""与基线比对 p50;超过 CHECK_RATIO 倍告警并返回 1。
|
|
79
|
+
|
|
80
|
+
不同 n / 不同机器之间绝对值不可比,所以只做"同机回归"的粗门禁;
|
|
81
|
+
没有基线文件时直接放行(首次接入不阻塞)。
|
|
82
|
+
"""
|
|
83
|
+
if not BASELINE.is_file():
|
|
84
|
+
print(f"[bench] 未找到基线 {BASELINE},跳过比对(先跑一次 --save)")
|
|
85
|
+
return 0
|
|
86
|
+
try:
|
|
87
|
+
base = json.loads(BASELINE.read_text(encoding="utf-8-sig"))
|
|
88
|
+
except (OSError, ValueError) as e:
|
|
89
|
+
print(f"[bench] 基线读取失败({e}),跳过比对")
|
|
90
|
+
return 0
|
|
91
|
+
base_res = base.get("results") or {}
|
|
92
|
+
if int(base.get("n") or 0) != n:
|
|
93
|
+
print(f"[bench] 基线 n={base.get('n')} 与本轮 n={n} 不同,仅打印不判定")
|
|
94
|
+
worst = 0
|
|
95
|
+
print("\n===== 与基线比对(阈值 ×{:.1f})=====".format(CHECK_RATIO))
|
|
96
|
+
for name, samples in results.items():
|
|
97
|
+
if not samples or name not in base_res:
|
|
98
|
+
continue
|
|
99
|
+
cur = _pctl(samples)["p50"]
|
|
100
|
+
old = float(base_res[name].get("p50") or 0)
|
|
101
|
+
if old <= 0:
|
|
102
|
+
continue
|
|
103
|
+
ratio = cur / old
|
|
104
|
+
flag = "WARN" if ratio > CHECK_RATIO else "ok"
|
|
105
|
+
print(f"{name:<10} 基线 {old*1000:7.0f} ms → 本次 {cur*1000:7.0f} ms ×{ratio:.2f} [{flag}]")
|
|
106
|
+
if ratio > CHECK_RATIO:
|
|
107
|
+
worst = 1
|
|
108
|
+
return worst
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def main() -> int:
|
|
113
|
+
ap = argparse.ArgumentParser(description="灵枢性能基准(隔离临时库,不碰真实数据)")
|
|
114
|
+
ap.add_argument("--n", type=int, default=1000, help="合成记忆条数(默认 1000)")
|
|
115
|
+
ap.add_argument("--quick", action="store_true", help="快速模式:n=300")
|
|
116
116
|
ap.add_argument("--keep", action="store_true", help="保留临时库(调试用)")
|
|
117
117
|
ap.add_argument("--save", action="store_true", help="把本次结果存为基线")
|
|
118
|
-
ap.add_argument("--check", action="store_true", help="与基线比对,超 1.5 倍退出 1")
|
|
119
|
-
opts = ap.parse_args()
|
|
120
|
-
if opts.quick:
|
|
121
|
-
opts.n = min(opts.n, 300)
|
|
122
|
-
|
|
123
|
-
home = Path(tempfile.mkdtemp(prefix="lingshu-bench-"))
|
|
124
|
-
print(f"[bench] 隔离 HOME:{home}")
|
|
125
|
-
rng = random.Random(20261115)
|
|
126
|
-
|
|
127
|
-
results: dict[str, list] = {"remember": [], "recall": [], "inject": [], "doctor": []}
|
|
128
|
-
try:
|
|
129
|
-
# 0. 初始化
|
|
130
|
-
_run(["init"], home)
|
|
131
|
-
|
|
132
|
-
# 1. 写入基准:批量 remember(每条一个子进程也量得到真实端到端成本)
|
|
133
|
-
print(f"[bench] 生成 {opts.n} 条合成记忆…")
|
|
134
|
-
t0 = time.perf_counter()
|
|
135
|
-
for i in range(opts.n):
|
|
136
|
-
topic = TOPICS[i % len(TOPICS)]
|
|
137
|
-
text = (f"{topic}方案第{i}条:{rng.choice(['决定', '发现', '总结'])}"
|
|
138
|
-
f"{topic}相关做法{rng.randint(1, 999)},注意版本{rng.randint(1, 9)}")
|
|
139
|
-
_run(["remember", text, "--kind", "fact", "--importance",
|
|
140
|
-
str(rng.choice([0.4, 0.5, 0.7, 0.7, 0.8, 0.9])),
|
|
141
|
-
"--project", PROJECTS[i % len(PROJECTS)]], home, timeout=60)
|
|
142
|
-
results["remember"].append(time.perf_counter() - t0)
|
|
143
|
-
t0 = time.perf_counter()
|
|
144
|
-
# 批量写完后再补几条批量型写入:单条走 --importance 的解析已覆盖,
|
|
145
|
-
# 这里换 fast 路径量小查询延迟基线(在空查询上测意义不大,略)。
|
|
146
|
-
|
|
147
|
-
# 2. 召回基准:混合 fast/deep 模式查询
|
|
148
|
-
for i in range(20):
|
|
149
|
-
q = rng.choice(TOPICS) + rng.choice(["方案", "做法", "决定"])
|
|
150
|
-
dt, _ = _run(["recall", q, "--k", "8"], home, timeout=60)
|
|
151
|
-
results["recall"].append(dt)
|
|
152
|
-
# 同项目召回(第四轮#3 加成路径)
|
|
153
|
-
for i in range(5):
|
|
154
|
-
dt, _ = _run(["recall", "方案做法", "--k", "8",
|
|
155
|
-
"--project", rng.choice(PROJECTS)], home, timeout=60)
|
|
156
|
-
results["recall"].append(dt)
|
|
157
|
-
|
|
158
|
-
# 3. 注入基准:build_injection 主路径(空 query = 无定向注入)
|
|
159
|
-
for i in range(10):
|
|
160
|
-
dt, _ = _run(["inject", "--budget", "2000", ""], home, timeout=60)
|
|
161
|
-
results["inject"].append(dt)
|
|
162
|
-
|
|
163
|
-
# 4. 体检基准:doctor 全检查(含 engine-sync 子进程)——隔离 HOME 下
|
|
164
|
-
# engine-sync 等检查项可能报 FAIL/WARN 属预期(退出码 2),只量耗时
|
|
165
|
-
dt, _ = _run(["doctor"], home, timeout=120, strict=False)
|
|
166
|
-
results["doctor"].append(dt)
|
|
167
|
-
|
|
168
|
-
# 报告
|
|
169
|
-
print("\n===== 灵枢性能基准结果 =====")
|
|
170
|
-
print(f"库规模:{opts.n} 条合成记忆 | 隔离 HOME:{home if opts.keep else '(已清理)'}")
|
|
171
|
-
for name, samples in results.items():
|
|
172
|
-
if not samples:
|
|
173
|
-
continue
|
|
174
|
-
p = _pctl(samples)
|
|
175
|
-
print(f"{name:<10} n={p['n']:>3} p50={p['p50']*1000:8.0f} ms "
|
|
176
|
-
f"p95={p['p95']*1000:8.0f} ms")
|
|
177
|
-
print("说明:单次调用含 Python 启动 ~100ms 基线;关注相对变化而非绝对值。")
|
|
178
|
-
if opts.save:
|
|
179
|
-
_save_baseline(opts.n, results)
|
|
180
|
-
if opts.check:
|
|
181
|
-
return _check_baseline(opts.n, results)
|
|
182
|
-
return 0
|
|
183
|
-
except Exception as e:
|
|
184
|
-
print(f"[bench] 失败:{e}", file=sys.stderr)
|
|
185
|
-
return 1
|
|
186
|
-
finally:
|
|
187
|
-
if not opts.keep:
|
|
188
|
-
shutil.rmtree(home, ignore_errors=True)
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
118
|
+
ap.add_argument("--check", action="store_true", help="与基线比对,超 1.5 倍退出 1")
|
|
119
|
+
opts = ap.parse_args()
|
|
120
|
+
if opts.quick:
|
|
121
|
+
opts.n = min(opts.n, 300)
|
|
122
|
+
|
|
123
|
+
home = Path(tempfile.mkdtemp(prefix="lingshu-bench-"))
|
|
124
|
+
print(f"[bench] 隔离 HOME:{home}")
|
|
125
|
+
rng = random.Random(20261115)
|
|
126
|
+
|
|
127
|
+
results: dict[str, list] = {"remember": [], "recall": [], "inject": [], "doctor": []}
|
|
128
|
+
try:
|
|
129
|
+
# 0. 初始化
|
|
130
|
+
_run(["init"], home)
|
|
131
|
+
|
|
132
|
+
# 1. 写入基准:批量 remember(每条一个子进程也量得到真实端到端成本)
|
|
133
|
+
print(f"[bench] 生成 {opts.n} 条合成记忆…")
|
|
134
|
+
t0 = time.perf_counter()
|
|
135
|
+
for i in range(opts.n):
|
|
136
|
+
topic = TOPICS[i % len(TOPICS)]
|
|
137
|
+
text = (f"{topic}方案第{i}条:{rng.choice(['决定', '发现', '总结'])}"
|
|
138
|
+
f"{topic}相关做法{rng.randint(1, 999)},注意版本{rng.randint(1, 9)}")
|
|
139
|
+
_run(["remember", text, "--kind", "fact", "--importance",
|
|
140
|
+
str(rng.choice([0.4, 0.5, 0.7, 0.7, 0.8, 0.9])),
|
|
141
|
+
"--project", PROJECTS[i % len(PROJECTS)]], home, timeout=60)
|
|
142
|
+
results["remember"].append(time.perf_counter() - t0)
|
|
143
|
+
t0 = time.perf_counter()
|
|
144
|
+
# 批量写完后再补几条批量型写入:单条走 --importance 的解析已覆盖,
|
|
145
|
+
# 这里换 fast 路径量小查询延迟基线(在空查询上测意义不大,略)。
|
|
146
|
+
|
|
147
|
+
# 2. 召回基准:混合 fast/deep 模式查询
|
|
148
|
+
for i in range(20):
|
|
149
|
+
q = rng.choice(TOPICS) + rng.choice(["方案", "做法", "决定"])
|
|
150
|
+
dt, _ = _run(["recall", q, "--k", "8"], home, timeout=60)
|
|
151
|
+
results["recall"].append(dt)
|
|
152
|
+
# 同项目召回(第四轮#3 加成路径)
|
|
153
|
+
for i in range(5):
|
|
154
|
+
dt, _ = _run(["recall", "方案做法", "--k", "8",
|
|
155
|
+
"--project", rng.choice(PROJECTS)], home, timeout=60)
|
|
156
|
+
results["recall"].append(dt)
|
|
157
|
+
|
|
158
|
+
# 3. 注入基准:build_injection 主路径(空 query = 无定向注入)
|
|
159
|
+
for i in range(10):
|
|
160
|
+
dt, _ = _run(["inject", "--budget", "2000", ""], home, timeout=60)
|
|
161
|
+
results["inject"].append(dt)
|
|
162
|
+
|
|
163
|
+
# 4. 体检基准:doctor 全检查(含 engine-sync 子进程)——隔离 HOME 下
|
|
164
|
+
# engine-sync 等检查项可能报 FAIL/WARN 属预期(退出码 2),只量耗时
|
|
165
|
+
dt, _ = _run(["doctor"], home, timeout=120, strict=False)
|
|
166
|
+
results["doctor"].append(dt)
|
|
167
|
+
|
|
168
|
+
# 报告
|
|
169
|
+
print("\n===== 灵枢性能基准结果 =====")
|
|
170
|
+
print(f"库规模:{opts.n} 条合成记忆 | 隔离 HOME:{home if opts.keep else '(已清理)'}")
|
|
171
|
+
for name, samples in results.items():
|
|
172
|
+
if not samples:
|
|
173
|
+
continue
|
|
174
|
+
p = _pctl(samples)
|
|
175
|
+
print(f"{name:<10} n={p['n']:>3} p50={p['p50']*1000:8.0f} ms "
|
|
176
|
+
f"p95={p['p95']*1000:8.0f} ms")
|
|
177
|
+
print("说明:单次调用含 Python 启动 ~100ms 基线;关注相对变化而非绝对值。")
|
|
178
|
+
if opts.save:
|
|
179
|
+
_save_baseline(opts.n, results)
|
|
180
|
+
if opts.check:
|
|
181
|
+
return _check_baseline(opts.n, results)
|
|
182
|
+
return 0
|
|
183
|
+
except Exception as e:
|
|
184
|
+
print(f"[bench] 失败:{e}", file=sys.stderr)
|
|
185
|
+
return 1
|
|
186
|
+
finally:
|
|
187
|
+
if not opts.keep:
|
|
188
|
+
shutil.rmtree(home, ignore_errors=True)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _ensure_utf8_stdout() -> None:
|
|
192
|
+
"""把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
|
|
193
|
+
|
|
194
|
+
CI 的 windows-latest stdout 是 cp1252:脚本一 print 中文就 UnicodeEncodeError
|
|
195
|
+
直接退出(实测 sync_engine.py / make_checksums.py 都因此挂过,Ubuntu 同期正常)。
|
|
196
|
+
这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
|
|
197
|
+
"""
|
|
198
|
+
for name in ("stdout", "stderr"):
|
|
199
|
+
stream = getattr(sys, name, None)
|
|
200
|
+
fn = getattr(stream, "reconfigure", None)
|
|
201
|
+
if callable(fn):
|
|
202
|
+
try:
|
|
203
|
+
fn(encoding="utf-8", errors="replace")
|
|
204
|
+
continue
|
|
205
|
+
except (OSError, ValueError, AttributeError):
|
|
206
|
+
pass
|
|
207
|
+
try:
|
|
208
|
+
import io
|
|
209
|
+
buf = getattr(stream, "buffer", None)
|
|
210
|
+
if buf is not None:
|
|
211
|
+
setattr(sys, name,
|
|
212
|
+
io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
|
|
213
|
+
line_buffering=True))
|
|
214
|
+
except Exception: # noqa: BLE001
|
|
215
|
+
pass
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
if __name__ == "__main__":
|
|
219
|
+
_ensure_utf8_stdout()
|
|
220
|
+
sys.exit(main())
|