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.
Files changed (61) hide show
  1. package/CHANGELOG.md +181 -0
  2. package/README.md +1577 -1577
  3. package/SKILL-lite.md +59 -59
  4. package/SKILL-tiny.md +38 -38
  5. package/SKILL.md +405 -404
  6. package/cordis-plugin/lingshu-cron/plugin.js +15 -5
  7. package/package.json +52 -52
  8. package/scripts/_ci_env_probe.py +81 -0
  9. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +23 -22
  10. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +181 -0
  11. package/scripts/astrbot_plugin_lingshu/engine/README.md +1577 -1577
  12. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +59 -59
  13. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +38 -38
  14. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +405 -404
  15. package/scripts/astrbot_plugin_lingshu/engine/scripts/_ci_env_probe.py +81 -0
  16. package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +28 -0
  17. package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +218 -190
  18. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +31 -0
  19. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +28 -0
  20. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +43 -0
  21. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +74 -0
  22. package/scripts/astrbot_plugin_lingshu/engine/scripts/coverage_report.py +195 -0
  23. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +28 -0
  24. package/scripts/astrbot_plugin_lingshu/engine/scripts/make_icon.py +24 -0
  25. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +221 -219
  26. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +10 -3
  27. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +31 -0
  28. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +28 -0
  29. package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +470 -460
  30. package/scripts/astrbot_plugin_lingshu/engine/scripts/release.py +42 -0
  31. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +29 -1
  32. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety_net.py +12 -0
  33. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +28 -0
  34. package/scripts/astrbot_plugin_lingshu/make_checksums.py +28 -0
  35. package/scripts/behavior_baseline.py +28 -0
  36. package/scripts/bench.py +218 -190
  37. package/scripts/check_pressure_sync.py +31 -0
  38. package/scripts/check_tag.py +28 -0
  39. package/scripts/check_version.py +47 -0
  40. package/scripts/cli.py +43 -0
  41. package/scripts/core.py +74 -0
  42. package/scripts/coverage_report.py +195 -0
  43. package/scripts/growth.py +28 -0
  44. package/scripts/make_icon.py +24 -0
  45. package/scripts/make_manifest.py +285 -254
  46. package/scripts/make_plugin_zip.py +28 -0
  47. package/scripts/mem_dialogue.py +221 -219
  48. package/scripts/memory.py +10 -3
  49. package/scripts/panel_build.py +31 -0
  50. package/scripts/panel_server.py +28 -0
  51. package/scripts/panels.py +470 -460
  52. package/scripts/release.py +42 -0
  53. package/scripts/run_tests.py +31 -0
  54. package/scripts/safety.py +29 -1
  55. package/scripts/safety_net.py +12 -0
  56. package/scripts/session_import.py +28 -0
  57. package/scripts/sync_engine.py +170 -139
  58. package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +0 -49
  59. package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +0 -53
  60. package/docs//345/217/221/345/270/203/350/207/252/345/212/250/345/214/226.md +0 -54
  61. package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +0 -189
@@ -0,0 +1,81 @@
1
+ # -*- coding: utf-8 -*-
2
+ """CI 诊断探针:只在 sync_engine 失败时被调用,把环境事实打出来。
3
+
4
+ 为什么单独成文件:内联在 workflow 的 heredoc 会破坏 YAML 缩进(实测解析失败),
5
+ 而这一段逻辑值得留档——它回答的是"为什么在 Windows runner 上失败、Linux 上不".
6
+ """
7
+ import locale
8
+ import pathlib
9
+ import sys
10
+
11
+
12
+ def main() -> int:
13
+ root = pathlib.Path(".").resolve()
14
+ print(f" cwd={root}")
15
+ print(f" python={sys.version.split()[0]}")
16
+ print(f" fsencoding={sys.getfilesystemencoding()}")
17
+ print(f" preferred={locale.getpreferredencoding(False)}")
18
+
19
+ print(" --- 关键路径 ---")
20
+ for rel in ("scripts",
21
+ "scripts/astrbot_plugin_lingshu",
22
+ "scripts/astrbot_plugin_lingshu/engine",
23
+ "docs/panel-api.md", "docs/commands.md",
24
+ "docs/mechanics.md", "docs/models.md", "docs/recovery.md",
25
+ "assets/panel.html"):
26
+ p = root / rel
27
+ kind = "-" if not p.exists() else ("dir" if p.is_dir() else f"{p.stat().st_size}B")
28
+ print(f" {rel}: {kind}")
29
+
30
+ # 换行抽样:CI 若在 Windows 上 checkout 成 CRLF,这里能直接看出来
31
+ print(" --- 换行抽样(前 5 个 .md/.py)---")
32
+ shown = 0
33
+ for p in sorted(root.rglob("*")):
34
+ if shown >= 5:
35
+ break
36
+ if p.is_file() and p.suffix.lower() in (".md", ".py") and "node_modules" not in str(p):
37
+ b = p.read_bytes()[:400]
38
+ crlf = b.count(b"\r\n")
39
+ lf = b.count(b"\n") - crlf
40
+ print(f" {p.relative_to(root)}: CRLF={crlf} LF={lf}")
41
+ shown += 1
42
+
43
+ # engine 里是否残留已从根目录删掉的文档
44
+ eng = root / "scripts" / "astrbot_plugin_lingshu" / "engine"
45
+ if eng.is_dir():
46
+ stale = [p.name for p in eng.rglob("*.md")
47
+ if not (root / p.relative_to(eng)).exists()]
48
+ print(f" --- engine 里根目录已无对应项的 .md: {stale[:8] or '无'}")
49
+ return 0
50
+
51
+
52
+ def _ensure_utf8_stdout() -> None:
53
+ """把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
54
+
55
+ CI 的 windows-latest stdout 是 cp1252:脚本一 print 中文就 UnicodeEncodeError
56
+ 直接退出(实测 sync_engine.py / make_checksums.py 都因此挂过,Ubuntu 同期正常)。
57
+ 这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
58
+ """
59
+ for name in ("stdout", "stderr"):
60
+ stream = getattr(sys, name, None)
61
+ fn = getattr(stream, "reconfigure", None)
62
+ if callable(fn):
63
+ try:
64
+ fn(encoding="utf-8", errors="replace")
65
+ continue
66
+ except (OSError, ValueError, AttributeError):
67
+ pass
68
+ try:
69
+ import io
70
+ buf = getattr(stream, "buffer", None)
71
+ if buf is not None:
72
+ setattr(sys, name,
73
+ io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
74
+ line_buffering=True))
75
+ except Exception: # noqa: BLE001
76
+ pass
77
+
78
+
79
+ if __name__ == "__main__":
80
+ _ensure_utf8_stdout()
81
+ 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:]))
@@ -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
- if __name__ == "__main__":
192
- sys.exit(main())
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())
@@ -51,5 +51,36 @@ def main() -> int:
51
51
  return 0
52
52
 
53
53
 
54
+ def _ensure_utf8_stdout() -> None:
55
+ """把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
56
+
57
+ 为什么必须有:CI 的 windows-latest stdout 是 cp1252,脚本一 print 中文就
58
+ UnicodeEncodeError 直接退出(实测 sync_engine.py 因此挂掉,Ubuntu 同期正常)。
59
+ 这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
60
+
61
+ reconfigure 不可用(3.6 及更早 / 被替换过的流)时静默跳过,绝不因此再崩。
62
+ """
63
+ for name in ("stdout", "stderr"):
64
+ stream = getattr(sys, name, None)
65
+ fn = getattr(stream, "reconfigure", None)
66
+ if callable(fn):
67
+ try:
68
+ fn(encoding="utf-8", errors="replace")
69
+ continue
70
+ except (OSError, ValueError, AttributeError):
71
+ pass
72
+ # 退路:包一层 UTF-8 writer(errors=replace,坏字符变 ?,不打断程序)
73
+ try:
74
+ import io
75
+ buf = getattr(stream, "buffer", None)
76
+ if buf is not None:
77
+ setattr(sys, name,
78
+ io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
79
+ line_buffering=True))
80
+ except Exception: # noqa: BLE001
81
+ pass
82
+
83
+
54
84
  if __name__ == "__main__":
85
+ _ensure_utf8_stdout()
55
86
  sys.exit(main())
@@ -211,5 +211,33 @@ def main(argv: list[str] | None = None) -> int:
211
211
  return check(create_if_missing=True)
212
212
 
213
213
 
214
+ def _ensure_utf8_stdout() -> None:
215
+ """把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
216
+
217
+ CI 的 windows-latest stdout 是 cp1252:脚本一 print 中文就 UnicodeEncodeError
218
+ 直接退出(实测 sync_engine.py / make_checksums.py 都因此挂过,Ubuntu 同期正常)。
219
+ 这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
220
+ """
221
+ for name in ("stdout", "stderr"):
222
+ stream = getattr(sys, name, None)
223
+ fn = getattr(stream, "reconfigure", None)
224
+ if callable(fn):
225
+ try:
226
+ fn(encoding="utf-8", errors="replace")
227
+ continue
228
+ except (OSError, ValueError, AttributeError):
229
+ pass
230
+ try:
231
+ import io
232
+ buf = getattr(stream, "buffer", None)
233
+ if buf is not None:
234
+ setattr(sys, name,
235
+ io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
236
+ line_buffering=True))
237
+ except Exception: # noqa: BLE001
238
+ pass
239
+
240
+
214
241
  if __name__ == "__main__":
242
+ _ensure_utf8_stdout()
215
243
  sys.exit(main())