lingshu-skill 5.25.0 → 5.29.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 (51) hide show
  1. package/CHANGELOG.md +189 -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 -405
  6. package/cordis-plugin/lingshu-cron/plugin.js +15 -5
  7. package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +228 -150
  8. package/package.json +52 -52
  9. package/scripts/_ci_env_probe.py +81 -0
  10. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +18 -18
  11. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +189 -0
  12. package/scripts/astrbot_plugin_lingshu/engine/README.md +1577 -1577
  13. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +59 -59
  14. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +38 -38
  15. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +405 -405
  16. package/scripts/astrbot_plugin_lingshu/engine/scripts/_ci_env_probe.py +81 -0
  17. package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +28 -0
  18. package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +218 -190
  19. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +31 -0
  20. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +28 -0
  21. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +11 -2
  22. package/scripts/astrbot_plugin_lingshu/engine/scripts/coverage_report.py +28 -0
  23. package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +14 -1
  24. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +28 -0
  25. package/scripts/astrbot_plugin_lingshu/engine/scripts/make_icon.py +24 -0
  26. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +31 -0
  27. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +28 -0
  28. package/scripts/astrbot_plugin_lingshu/engine/scripts/release.py +28 -0
  29. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +28 -0
  30. package/scripts/astrbot_plugin_lingshu/make_checksums.py +28 -0
  31. package/scripts/behavior_baseline.py +28 -0
  32. package/scripts/bench.py +218 -190
  33. package/scripts/check_pressure_sync.py +31 -0
  34. package/scripts/check_tag.py +28 -0
  35. package/scripts/check_version.py +31 -0
  36. package/scripts/cli.py +11 -2
  37. package/scripts/coverage_report.py +28 -0
  38. package/scripts/dream.py +14 -1
  39. package/scripts/growth.py +28 -0
  40. package/scripts/make_icon.py +24 -0
  41. package/scripts/make_manifest.py +285 -254
  42. package/scripts/make_plugin_zip.py +28 -0
  43. package/scripts/panel_build.py +31 -0
  44. package/scripts/panel_server.py +28 -0
  45. package/scripts/release.py +28 -0
  46. package/scripts/run_tests.py +31 -0
  47. package/scripts/session_import.py +28 -0
  48. package/scripts/sync_engine.py +170 -139
  49. package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +0 -49
  50. package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +0 -53
  51. package/docs//345/217/221/345/270/203/350/207/252/345/212/250/345/214/226.md +0 -54
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
- 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())
@@ -277,5 +277,36 @@ def main(argv: list[str] | None = None) -> int:
277
277
  return check(args.staged)
278
278
 
279
279
 
280
+ def _ensure_utf8_stdout() -> None:
281
+ """把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
282
+
283
+ 为什么必须有:CI 的 windows-latest stdout 是 cp1252,脚本一 print 中文就
284
+ UnicodeEncodeError 直接退出(实测 sync_engine.py 因此挂掉,Ubuntu 同期正常)。
285
+ 这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
286
+
287
+ reconfigure 不可用(3.6 及更早 / 被替换过的流)时静默跳过,绝不因此再崩。
288
+ """
289
+ for name in ("stdout", "stderr"):
290
+ stream = getattr(sys, name, None)
291
+ fn = getattr(stream, "reconfigure", None)
292
+ if callable(fn):
293
+ try:
294
+ fn(encoding="utf-8", errors="replace")
295
+ continue
296
+ except (OSError, ValueError, AttributeError):
297
+ pass
298
+ # 退路:包一层 UTF-8 writer(errors=replace,坏字符变 ?,不打断程序)
299
+ try:
300
+ import io
301
+ buf = getattr(stream, "buffer", None)
302
+ if buf is not None:
303
+ setattr(sys, name,
304
+ io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
305
+ line_buffering=True))
306
+ except Exception: # noqa: BLE001
307
+ pass
308
+
309
+
280
310
  if __name__ == "__main__":
311
+ _ensure_utf8_stdout()
281
312
  sys.exit(main())
package/scripts/cli.py CHANGED
@@ -697,14 +697,23 @@ def cmd_relink(limit: int = 0, min_score: float = 1.0, max_links: int = 5) -> in
697
697
  """全库联想建链:给历史记忆按词面相似度补挂 links(双向)。
698
698
 
699
699
  与 cold/archive 分层无关——建链是给"还在热查询集里的记忆"补关联网。
700
- 整体一把写锁、一次快照内完成(全库也只是一次 load + 一次 save,
701
- 与 dream 的整库遍历同量级,分批反而要反复读盘)。
700
+
701
+ **必须持写锁**:load_all → 改 links → save_all 是整库快照回写,锁外做会被
702
+ remember / dream / 面板的并发写整片覆盖。本函数早期版本漏了锁,docstring 却
703
+ 写着"整体一把写锁"——注释骗过了历次审计(实测 61 行里 0 处 `_locked`)。
702
704
  """
703
705
  import memory as _mem
704
706
  if READONLY:
705
707
  print("[只读] 记忆库当前不可写,relink 需要写盘。", file=sys.stderr)
706
708
  return 1
707
709
  ensure_home()
710
+ with _locked(HOME / "hippocampus.jsonl"):
711
+ return _relink_locked(limit, min_score, max_links)
712
+
713
+
714
+ def _relink_locked(limit: int, min_score: float, max_links: int) -> int:
715
+ """真正的遍历。**调用方必须已持有 hippocampus 写锁。**"""
716
+ import memory as _mem
708
717
  # 记忆上万后全库 jaccard 两两比对是 O(n²),但与 recall/dream 现有全量扫描
709
718
  # 同量级;先按创建时间倒序截 limit,保证"最近的最先补到"。
710
719
  rows = _mem.load_all()
@@ -163,5 +163,33 @@ def main(argv=None) -> int:
163
163
  return 0
164
164
 
165
165
 
166
+ def _ensure_utf8_stdout() -> None:
167
+ """把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
168
+
169
+ CI 的 windows-latest stdout 是 cp1252:脚本一 print 中文就 UnicodeEncodeError
170
+ 直接退出(实测 sync_engine.py / make_checksums.py 都因此挂过,Ubuntu 同期正常)。
171
+ 这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
172
+ """
173
+ for name in ("stdout", "stderr"):
174
+ stream = getattr(sys, name, None)
175
+ fn = getattr(stream, "reconfigure", None)
176
+ if callable(fn):
177
+ try:
178
+ fn(encoding="utf-8", errors="replace")
179
+ continue
180
+ except (OSError, ValueError, AttributeError):
181
+ pass
182
+ try:
183
+ import io
184
+ buf = getattr(stream, "buffer", None)
185
+ if buf is not None:
186
+ setattr(sys, name,
187
+ io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
188
+ line_buffering=True))
189
+ except Exception: # noqa: BLE001
190
+ pass
191
+
192
+
166
193
  if __name__ == "__main__":
194
+ _ensure_utf8_stdout()
167
195
  sys.exit(main())
package/scripts/dream.py CHANGED
@@ -732,6 +732,7 @@ def dream(trigger: str = "manual", dry_run: bool = False) -> dict:
732
732
  # 新任务也可能被晾着(借鉴 Mnemosyne 幂等键防重复情节、租约验证)。
733
733
  # 未超时 → 沿用旧任务;超时太久(孤儿)→ 归档后接新任务。
734
734
  old = load_dream_pending()
735
+ keep_old = False
735
736
  if old and old.get("task_id"):
736
737
  age = now - _num(old.get("created"), now)
737
738
  if age < _DREAM_ORPHAN_TTL:
@@ -739,6 +740,7 @@ def dream(trigger: str = "manual", dry_run: bool = False) -> dict:
739
740
  task_id = old["task_id"]
740
741
  report["task_id"] = task_id
741
742
  report["pending_kept"] = True
743
+ keep_old = True
742
744
  log_event("dream", f"已有未整理的梦(task_id={old['task_id']},"
743
745
  f"{age / 3600:.1f}h 前触发),本次不重复生成新任务", level="warn")
744
746
  else:
@@ -751,7 +753,18 @@ def dream(trigger: str = "manual", dry_run: bool = False) -> dict:
751
753
  f"悬置 {age / 3600:.1f}h > {_DREAM_ORPHAN_TTL / 3600:.0f}h),"
752
754
  "生成新任务", level="warn")
753
755
  report["orphaned_task_id"] = old["task_id"]
754
- atomic_json(HOME / "dreams" / "pending.json", new_pending)
756
+ # ⚠ 两处必须一起改(原先只改了一半,实测导致自动做梦必然失败):
757
+ # ① 沿用旧任务时**绝不能写盘**——new_pending 装的是本次的新簇,
758
+ # 写下去等于用新簇顶掉旧 task_id 的任务,旧簇静默丢失;
759
+ # ② 真写盘时,pending 里的 task_id 必须是**最终** task_id。
760
+ # new_pending 在 L709 用新 id 构造,若期间 task_id 被改写(孤儿归档
761
+ # 分支不会改,但任何未来的改写都会),两者就会错位——
762
+ # 而 `dream --auto` 拿 report["task_id"] 去 apply,盘上却是另一个 id
763
+ # → 稳定报"任务对不上"。这里显式同步,不依赖构造顺序。
764
+ if not keep_old:
765
+ new_pending["task_id"] = task_id
766
+ new_pending["apply_schema"]["task_id"] = task_id
767
+ atomic_json(HOME / "dreams" / "pending.json", new_pending)
755
768
  # 没有可整理的碎片就不写 pending.json,免得让 AI 对着一份空任务空转
756
769
  write_dream_report(report)
757
770
  st = load_dream_state()
package/scripts/growth.py CHANGED
@@ -5379,6 +5379,34 @@ def _run(argv=None) -> int:
5379
5379
  from growth_parts import * # noqa: E402,F401,F403
5380
5380
 
5381
5381
 
5382
+ def _ensure_utf8_stdout() -> None:
5383
+ """把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
5384
+
5385
+ CI 的 windows-latest stdout 是 cp1252:脚本一 print 中文就 UnicodeEncodeError
5386
+ 直接退出(实测 sync_engine.py / make_checksums.py 都因此挂过,Ubuntu 同期正常)。
5387
+ 这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
5388
+ """
5389
+ for name in ("stdout", "stderr"):
5390
+ stream = getattr(sys, name, None)
5391
+ fn = getattr(stream, "reconfigure", None)
5392
+ if callable(fn):
5393
+ try:
5394
+ fn(encoding="utf-8", errors="replace")
5395
+ continue
5396
+ except (OSError, ValueError, AttributeError):
5397
+ pass
5398
+ try:
5399
+ import io
5400
+ buf = getattr(stream, "buffer", None)
5401
+ if buf is not None:
5402
+ setattr(sys, name,
5403
+ io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
5404
+ line_buffering=True))
5405
+ except Exception: # noqa: BLE001
5406
+ pass
5407
+
5408
+
5382
5409
  if __name__ == "__main__":
5410
+ _ensure_utf8_stdout()
5383
5411
  sys.exit(run())
5384
5412