lingshu-skill 5.68.0 → 5.70.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 (31) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +1 -1
  3. package/SKILL-lite.md +1 -1
  4. package/SKILL-tiny.md +1 -1
  5. package/SKILL.md +1 -1
  6. package/assets/panel.html +11 -3
  7. package/cordis-plugin/lingshu-cron/plugin.js +32 -6
  8. package/cordis-plugin/lingshu-guard/plugin.js +34 -10
  9. package/cordis-plugin/lingshu-im/plugin.js +19 -2
  10. package/cordis-plugin/lingshu-startup/context-fold.js +5 -1
  11. package/cordis-plugin/lingshu-startup/plugin.js +9 -1
  12. package/index.js +26 -21
  13. package/manifest.json +35 -35
  14. package/package.json +1 -1
  15. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +10 -10
  16. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +43 -0
  17. package/scripts/astrbot_plugin_lingshu/engine/README.md +1 -1
  18. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +1 -1
  19. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +1 -1
  20. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +1 -1
  21. package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +11 -3
  22. package/scripts/astrbot_plugin_lingshu/engine/scripts/desktop_shortcut.py +10 -1
  23. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +5629 -5575
  24. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_data.py +17 -3
  25. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_settings.py +24 -1
  26. package/scripts/desktop_shortcut.py +10 -1
  27. package/scripts/growth.py +5629 -5575
  28. package/scripts/panel_data.py +17 -3
  29. package/scripts/panel_settings.py +24 -1
  30. package/scripts/run_tests.py +240 -171
  31. package/scripts/update_dsh_copy.ps1 +42 -6
@@ -98,10 +98,22 @@ def list_backups(limit: int = 30) -> dict:
98
98
  except OSError:
99
99
  continue
100
100
  sha_file = p.with_name(p.name + ".sha256")
101
- man = _manifest_of(p)
101
+ # LS-074(v5.69):隔离损坏备份 manifest 的字段错误!
102
+ # 单条记录的 manifest 读失败 / 字段类型错不再让它 abort 整个列表——
103
+ # 按字段级容错,正常备份照常展示。
104
+ man = None
105
+ man_err = ""
106
+ try:
107
+ man = _manifest_of(p)
108
+ except Exception as _me: # noqa: BLE001
109
+ man_err = str(_me)[:80]
102
110
  records = None
103
- if man:
104
- records = int(man.get("total_records") or 0)
111
+ if isinstance(man, dict):
112
+ try:
113
+ records = int(man.get("total_records") or 0)
114
+ except (TypeError, ValueError):
115
+ records = None
116
+ man_err = "total_records 字段类型异常"
105
117
  if records is None:
106
118
  records = _count_in_zip(p) # 老备份没清单:解包数一遍
107
119
  age_h = max(0.0, (time.time() - st.st_mtime) / 3600.0)
@@ -120,6 +132,8 @@ def list_backups(limit: int = 30) -> dict:
120
132
  "suspicious_why": ("包体过小" if bad_size
121
133
  else (f"记录数 {records} < 阈值 {threshold}" if bad_records else "")),
122
134
  "has_sha": sha_file.is_file(),
135
+ "manifest_ok": bool(isinstance(man, dict) and not man_err),
136
+ "manifest_error": man_err,
123
137
  })
124
138
  return {"dir": str(d), "dir_exists": d.is_dir(), "items": items,
125
139
  "count": len(items), "current_records": cur,
@@ -167,7 +167,13 @@ def all_items() -> list[dict]:
167
167
 
168
168
 
169
169
  def coerce(spec: dict, raw) -> Any:
170
- """按 schema 校验并转换一个值;不合法抛 ValueError(消息可直接给用户看)。"""
170
+ """按 schema 校验并转换一个值;不合法抛 ValueError(消息可直接给用户看)。
171
+
172
+ LS-075(v5.69):实现 enum 设置的后端转换——kind=enum 按 options 校验并返回字符串。
173
+ LS-077(v5.69):拒绝 float 配置中的非有限数——NaN/Infinity 落盘后
174
+ 标准 JSON 输出会变 `NaN` 字面量,前端 JSON.parse 直接失败("已写入但前端解析失败")。
175
+ """
176
+ import math as _math
171
177
  kind = spec["kind"]
172
178
  if kind == "bool":
173
179
  if isinstance(raw, bool):
@@ -178,11 +184,28 @@ def coerce(spec: dict, raw) -> Any:
178
184
  if s in ("false", "0", "no", "off"):
179
185
  return False
180
186
  raise ValueError(f"{spec['label']} 是开关,只接受 true/false")
187
+ if kind == "enum":
188
+ # LS-075: enum 类型——按 options 白名单校验,返回字符串
189
+ opts = spec.get("options") or []
190
+ s = str(raw).strip()
191
+ # enum 的 options 可能是 ["a","b"] 或 [{"value":"a","label":"A"},...]
192
+ vals = []
193
+ for o in opts:
194
+ if isinstance(o, dict):
195
+ vals.append(str(o.get("value", "")))
196
+ else:
197
+ vals.append(str(o))
198
+ if s not in vals:
199
+ raise ValueError(f"{spec['label']} 只能是 {'/'.join(vals) if vals else '(无可选值)'}")
200
+ return s
181
201
  if kind in ("int", "float"):
182
202
  try:
183
203
  num = float(raw)
184
204
  except (TypeError, ValueError):
185
205
  raise ValueError(f"{spec['label']} 需要是数字")
206
+ # LS-077: 拒绝非有限数
207
+ if not _math.isfinite(num):
208
+ raise ValueError(f"{spec['label']} 不能是 NaN 或 Infinity")
186
209
  if kind == "int":
187
210
  if num != int(num):
188
211
  raise ValueError(f"{spec['label']} 需要是整数")
@@ -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:]))
@@ -26,11 +26,19 @@ $src = Split-Path -Parent $PSScriptRoot # 仓库根目录(本脚本
26
26
  $profilesRoot = Join-Path $env:USERPROFILE ".dsh\profiles"
27
27
 
28
28
  function Get-CopyVersion($dir) {
29
+ # LS-139(v5.70):坏 package.json 必须失败而非返回 "?"!
30
+ # 旧实现 catch 一切返回 "?"——解析错误被当成"没版本",脚本继续跑、最终报成功,
31
+ # 但副本里的 package.json 已经损坏,DSH 加载必崩。
29
32
  try {
30
33
  $pkg = Get-Content -LiteralPath (Join-Path $dir "package.json") -Raw -Encoding UTF8 | ConvertFrom-Json
31
- return [string]$pkg.version
34
+ $v = [string]$pkg.version
35
+ if (-not $v) { throw "package.json 无 version 字段" }
36
+ return $v
32
37
  } catch {
33
- return "?"
38
+ if (-not (Test-Path -LiteralPath (Join-Path $dir "package.json"))) {
39
+ return ""
40
+ }
41
+ throw "目标副本 package.json 解析失败(副本已损坏,拒绝在其上继续操作):$($_.Exception.Message)"
34
42
  }
35
43
  }
36
44
 
@@ -70,11 +78,27 @@ if ($files.Count -eq 0) {
70
78
  }
71
79
 
72
80
  # 3) 逐文件复制(不删除目标里多出来的旧文件,避免误删用户自装的东西)
81
+ # LS-140(v5.70):PowerShell 热同步具备事务与回滚!
82
+ # 旧实现直接 Copy-Item 覆盖——中途失败留下"一半新一半旧"的混合副本。
83
+ # 现在:先整目录备份,失败时整体回滚,绝不留混合树。
73
84
  $hadFailure = $false
74
85
  foreach ($dst in $targets) {
75
86
  $before = Get-CopyVersion $dst
87
+ if (-not $before) {
88
+ Write-Host ("[跳过] {0}:副本尚未安装(package.json 不存在)" -f $dst) -ForegroundColor Yellow
89
+ continue
90
+ }
76
91
  $copied = 0
77
92
  $failed = @()
93
+ # —— 备份目标(事务回滚的退路)——
94
+ $backup = "$dst.bak-$(Get-Date -Format yyyyMMddHHmmss)"
95
+ try {
96
+ Copy-Item -LiteralPath $dst -Destination $backup -Recurse -Force
97
+ } catch {
98
+ Write-Host ("[错误] 无法备份目标副本 {0},拒绝在其上继续复制:{1}" -f $dst, $_.Exception.Message) -ForegroundColor Red
99
+ exit 1
100
+ }
101
+ $allOk = $true
78
102
  foreach ($rel in $files) {
79
103
  $relWin = $rel -replace '/', '\'
80
104
  $s = Join-Path $src $relWin
@@ -89,16 +113,28 @@ foreach ($dst in $targets) {
89
113
  $copied++
90
114
  } catch {
91
115
  $failed += ("{0} —— {1}" -f $rel, $_.Exception.Message)
116
+ $allOk = $false
92
117
  }
93
118
  }
94
- $after = Get-CopyVersion $dst
95
- Write-Host ("[同步] {0}" -f $dst)
96
- Write-Host (" 版本 {0} -> {1},复制 {2}/{3} 个文件" -f $before, $after, $copied, $files.Count) -ForegroundColor Green
97
- if ($failed.Count -gt 0) {
119
+ if (-not $allOk) {
120
+ # LS-140:回滚——删除部分更新的副本,从备份恢复原状
121
+ Write-Host ("[回滚] {0}:复制失败,恢复备份状态" -f $dst) -ForegroundColor Yellow
122
+ try {
123
+ Remove-Item -LiteralPath $dst -Recurse -Force
124
+ Rename-Item -LiteralPath $backup -NewName (Split-Path -Leaf $dst)
125
+ } catch {
126
+ Write-Host ("[严重] 回滚失败!副本 {0} 处于混合状态,请手动从备份 {1} 恢复" -f $dst, $backup) -ForegroundColor Red
127
+ }
98
128
  $hadFailure = $true
99
129
  Write-Host (" 失败 {0} 个(多半是 DSH 正在占用文件,完全退出 DSH 后重跑):" -f $failed.Count) -ForegroundColor Yellow
100
130
  $failed | Select-Object -First 5 | ForEach-Object { Write-Host (" - {0}" -f $_) -ForegroundColor Yellow }
131
+ continue
101
132
  }
133
+ # 成功:清理备份
134
+ try { Remove-Item -LiteralPath $backup -Recurse -Force } catch {}
135
+ $after = Get-CopyVersion $dst
136
+ Write-Host ("[同步] {0}" -f $dst)
137
+ Write-Host (" 版本 {0} -> {1},复制 {2}/{3} 个文件" -f $before, $after, $copied, $files.Count) -ForegroundColor Green
102
138
  }
103
139
 
104
140
  if ($hadFailure) { exit 1 }