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
@@ -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())
@@ -136,6 +136,22 @@ def check(staged: bool = False, base: str = "HEAD") -> int:
136
136
  f"({m_first.strip()}),与 SKILL.md version({new_ver})不一致。"
137
137
  f"先在 CHANGELOG 顶部补 v{new_ver} 小节。", file=sys.stderr)
138
138
  return 1
139
+ # SKILL-lite / SKILL-tiny 的 version 是"文档对得上哪个引擎"的标记。
140
+ # 它们**不**触发"改了就必须升版",但一旦写了 version 就必须与 SKILL.md 一致,
141
+ # 否则读者会拿一份标着 5.4 的裁剪文档去操作 5.24 的引擎(实测漂了 20 个小版本)。
142
+ for _rel in ("SKILL-lite.md", "SKILL-tiny.md"):
143
+ _p = ROOT / _rel
144
+ if not _p.is_file():
145
+ continue
146
+ _m = re.search(r"^version:\s*([\d.]+)", _p.read_text(encoding="utf-8-sig"), re.M)
147
+ if not _m:
148
+ continue
149
+ if _m.group(1) != new_ver:
150
+ print(f"[version] 拒绝:{_rel} version({_m.group(1)})与 SKILL.md "
151
+ f"version({new_ver})不一致。跑 release.py bump 会自动同步,"
152
+ f"或手动改成 {new_ver}。", file=sys.stderr)
153
+ return 1
154
+
139
155
  # manifest.json 存在时:其 version 必须与 SKILL.md 完全一致
140
156
  mf_path = ROOT / "manifest.json"
141
157
  if mf_path.exists():
@@ -261,5 +277,36 @@ def main(argv: list[str] | None = None) -> int:
261
277
  return check(args.staged)
262
278
 
263
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
+
264
310
  if __name__ == "__main__":
311
+ _ensure_utf8_stdout()
265
312
  sys.exit(main())
package/scripts/cli.py CHANGED
@@ -75,6 +75,10 @@ def _sanitize_config_json(data: bytes) -> bytes:
75
75
  if isinstance(cloud, dict):
76
76
  cloud.pop("gitee_token", None)
77
77
  cloud.pop("github_token", None)
78
+ # 顶层 token 也要清:growth._remote_token 读的是 config.json **顶层**的
79
+ # gitee_token / github_token,不清会把"能推/能删仓库"的凭据明文带进备份 zip
80
+ for k in ("gitee_token", "github_token", "token", "api_key"):
81
+ cfg.pop(k, None)
78
82
  return json.dumps(cfg, ensure_ascii=False, indent=2).encode("utf-8")
79
83
  except Exception:
80
84
  return b"" # 解析失败宁可跳过也不把可能含密的原文写进备份
@@ -4159,6 +4163,21 @@ def _main(argv=None) -> int:
4159
4163
 
4160
4164
  pinned = bool(_re.search(r"^github:.*#[0-9a-f]{7,}", spec))
4161
4165
  behind = bool(installed and src and installed != src)
4166
+ # 声明里的 X.Y(`^5.18` / `^5.18.0` / `~5.18` / `5.18.x` 都认)。
4167
+ # semver 范围在语义上"兼容"新版,但**商店/依赖视图读的是这个字符串**,
4168
+ # 声明停在 5.18 就一直显示 5.18.0(实测漂了 6 个版本没人发现)。
4169
+ m_decl = _re.search(r"(\d+)\.(\d+)", spec or "")
4170
+ decl_xy = f"{m_decl.group(1)}.{m_decl.group(2)}" if m_decl else ""
4171
+ src_xy = ""
4172
+ m_src = _re.match(r"(\d+)\.(\d+)", src or "")
4173
+ if m_src:
4174
+ src_xy = f"{m_src.group(1)}.{m_src.group(2)}"
4175
+ if decl_xy and src_xy and decl_xy != src_xy:
4176
+ return ("app-pin", "WARN",
4177
+ f"APP 依赖声明是 \"{spec}\"(显示 v{decl_xy}),源码已 v{src_xy}——"
4178
+ f"商店/依赖视图会一直显示旧版本。"
4179
+ f"修:把 profile 的 package.json 改成 \"^{src}.0\","
4180
+ f"再在该目录跑 pnpm install --no-frozen-lockfile")
4162
4181
  if pinned and behind:
4163
4182
  sha = spec.rsplit("#", 1)[-1][:8]
4164
4183
  return ("app-pin", "WARN",
@@ -4255,6 +4274,24 @@ def _main(argv=None) -> int:
4255
4274
  return ("runtime-liveness", "WARN", ";".join(parts))
4256
4275
  return ("runtime-liveness", "PASS", ";".join(parts))
4257
4276
 
4277
+ def _doctor_swallowed() -> tuple:
4278
+ """近 7 天被吞掉的异常(写盘/摄取/回滚等关键路径)。"""
4279
+ try:
4280
+ import core as _c
4281
+ r = _c.swallow_report(7)
4282
+ except Exception as exc: # noqa: BLE001
4283
+ return ("swallowed", "PASS", f"计数器不可用(跳过):{exc}")
4284
+ total = int(r.get("total") or 0)
4285
+ by = r.get("by_kind") or {}
4286
+ if not total:
4287
+ return ("swallowed", "PASS", "近 7 天没有关键路径吞异常")
4288
+ top = "、".join(f"{k}×{v}" for k, v in
4289
+ sorted(by.items(), key=lambda kv: -kv[1])[:3])
4290
+ # 阈值:单类 >10 或总量 >30 才算"有东西长期在静默失败"
4291
+ worst = max(by.values()) if by else 0
4292
+ level = "WARN" if (worst > 10 or total > 30) else "PASS"
4293
+ return ("swallowed", level, f"近 7 天吞了 {total} 次({top})")
4294
+
4258
4295
  def _doctor_skill_evolve() -> tuple:
4259
4296
  """P2-2:技能贴士文件是否存在(有经验被回灌过)。只读,无贴士不算错误。"""
4260
4297
  try:
@@ -4534,6 +4571,12 @@ def _main(argv=None) -> int:
4534
4571
  except Exception as e:
4535
4572
  checks.append(("runtime-liveness", "WARN", f"自检失败:{e}"))
4536
4573
 
4574
+ # 13c. 关键路径被吞异常计数(让"最近七天吞了多少次"可见)
4575
+ try:
4576
+ checks.append(_doctor_swallowed())
4577
+ except Exception as e:
4578
+ checks.append(("swallowed", "WARN", f"自检失败:{e}"))
4579
+
4537
4580
  # 13b. P2-2:技能贴士(自我进化的落点)
4538
4581
  try:
4539
4582
  checks.append(_doctor_skill_evolve())
package/scripts/core.py CHANGED
@@ -571,6 +571,80 @@ def redact(text: str) -> str:
571
571
  return text
572
572
 
573
573
 
574
+ # ---------------------------------------------------------------- 被吞异常计数
575
+ # 为什么需要它:代码里有大量 `except ...: pass`(审计数出 188 处,多为
576
+ # `except OSError: pass` 的可选操作,属正常取舍)。问题是"取舍"和"真出故障"
577
+ # 长得一模一样,所以故障可以被静默吞掉很久没人知道。
578
+ # 日志靠不住(1MB 轮转 + 最旧文件丢弃,实测只剩 26 条),所以单独计数。
579
+ SWALLOW_FILE = HOME / "swallowed.json"
580
+ SWALLOW_KEEP_DAYS = 30
581
+
582
+
583
+ def swallow(kind: str, exc: BaseException | None = None, *, where: str = "") -> None:
584
+ """记一次"被吞掉的异常"。绝不抛、不阻塞、不做重活。
585
+
586
+ 只在**关键路径**上调用(写盘/迁移/恢复/召回降级),不要给每个
587
+ `except OSError: pass` 都加——那样计数器本身就成了噪音。
588
+ """
589
+ if READONLY:
590
+ return
591
+ try:
592
+ day = time.strftime("%Y-%m-%d", time.localtime())
593
+ key = f"{day}|{kind}"
594
+ data = {}
595
+ try:
596
+ if SWALLOW_FILE.is_file():
597
+ data = json.loads(SWALLOW_FILE.read_text(encoding="utf-8-sig"))
598
+ if not isinstance(data, dict):
599
+ data = {}
600
+ except Exception: # noqa: BLE001
601
+ data = {}
602
+ rec = data.get(key)
603
+ if not isinstance(rec, dict):
604
+ rec = {"n": 0, "last": "", "where": ""}
605
+ rec["n"] = int(rec.get("n") or 0) + 1
606
+ rec["last"] = str(exc)[:160] if exc else ""
607
+ if where:
608
+ rec["where"] = where[:80]
609
+ data[key] = rec
610
+ # 只留最近 SWALLOW_KEEP_DAYS 天
611
+ cutoff = time.strftime("%Y-%m-%d",
612
+ time.localtime(time.time() - SWALLOW_KEEP_DAYS * DAY))
613
+ data = {k: v for k, v in data.items() if k.split("|")[0] >= cutoff}
614
+ atomic_json(SWALLOW_FILE, data)
615
+ except Exception: # noqa: BLE001
616
+ pass # 计数器自己绝不能再抛
617
+
618
+
619
+ def swallow_report(days: int = 7) -> dict:
620
+ """近 N 天被吞异常的汇总:{total, by_kind: {kind: n}, days}。"""
621
+ out = {"total": 0, "by_kind": {}, "days": days}
622
+ try:
623
+ if not SWALLOW_FILE.is_file():
624
+ return out
625
+ data = json.loads(SWALLOW_FILE.read_text(encoding="utf-8-sig"))
626
+ if not isinstance(data, dict):
627
+ return out
628
+ cutoff = time.strftime("%Y-%m-%d",
629
+ time.localtime(time.time() - max(1, days) * DAY))
630
+ by = {}
631
+ for key, rec in data.items():
632
+ try:
633
+ day, kind = str(key).split("|", 1)
634
+ except ValueError:
635
+ continue
636
+ if day < cutoff:
637
+ continue
638
+ n = int((rec or {}).get("n") or 0)
639
+ if n > 0:
640
+ by[kind] = by.get(kind, 0) + n
641
+ out["by_kind"] = by
642
+ out["total"] = sum(by.values())
643
+ except Exception: # noqa: BLE001
644
+ pass
645
+ return out
646
+
647
+
574
648
  def log_event(kind: str, message: str, level: str = "info", **extra) -> None:
575
649
  """轻量运行日志(lingshu.log):锁冲突、内部异常、解析报错等留痕,面板「日志」页可看。
576
650
 
@@ -0,0 +1,195 @@
1
+ # -*- coding: utf-8 -*-
2
+ """零依赖行覆盖率报告:在**同一个进程**里打一遍主 API,用标准库 trace 统计。
3
+
4
+ 为什么不用 `python -m trace` 跑整个测试集:
5
+ 测试全是 `subprocess.run([python, ...])` 起的子进程,父进程的 trace 抓不到子进程,
6
+ 报出来的覆盖率会低得毫无意义(还容易误判成"代码没被测到")。
7
+
8
+ 所以这里换个口径:**在单进程内真实调用主链路**(记/回忆/注入/做梦/体检/情绪/成长…),
9
+ 统计 `scripts/*.py` 里有哪些行被走到。它不是"测试覆盖率",而是
10
+ **"主 API 冒烟覆盖率"**——用来发现"某个模块整体没被任何入口碰过"这类问题。
11
+
12
+ 用法:
13
+ python scripts/coverage_report.py # 报告 + 最低覆盖模块 Top10
14
+ python scripts/coverage_report.py --min 60 # 低于 60% 的模块视为可疑,退出码 1
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import pathlib
20
+ import sys
21
+ import tempfile
22
+ import trace
23
+ import os
24
+
25
+ ROOT = pathlib.Path(__file__).resolve().parent.parent
26
+ SCRIPTS = ROOT / "scripts"
27
+
28
+
29
+ def _exercise() -> list:
30
+ """在临时 HOME 里真实调用主链路。返回 [(说明, 是否成功)]。"""
31
+ home = tempfile.mkdtemp(prefix="ls-cov-")
32
+ os.environ["BRAIN_MEMORY_HOME"] = home
33
+ os.environ["PYTHONIOENCODING"] = "utf-8"
34
+ sys.path.insert(0, str(SCRIPTS))
35
+
36
+ import brain # noqa: F401 合并命名空间
37
+ import core
38
+ import memory as mem
39
+ import emotion as em
40
+ import persona as pe
41
+ import dream
42
+ import growth
43
+ import safety_net
44
+ import shape_audit
45
+
46
+ core.ensure_home()
47
+ done = []
48
+
49
+ def step(name, fn):
50
+ try:
51
+ fn()
52
+ done.append((name, True))
53
+ except Exception as exc: # noqa: BLE001
54
+ done.append((f"{name}({type(exc).__name__}: {str(exc)[:60]})", False))
55
+
56
+ ids = {}
57
+
58
+ def _remember():
59
+ rec, _ = mem.remember("覆盖率冒烟:用户偏好把话说清楚,讨厌猜测",
60
+ kind="fact", importance=0.7, tags=["冒烟"])
61
+ ids["a"] = rec["id"]
62
+ mem.remember("覆盖率冒烟:备份要先留底再动手", kind="mistake", importance=0.8)
63
+
64
+ step("remember", _remember)
65
+ step("recall", lambda: mem.recall("备份 留底", k=5, mode="fast", strengthen=False))
66
+ step("stats", mem.stats)
67
+ step("inject", lambda: mem.build_injection("接着做覆盖率"))
68
+ step("capture", lambda: mem.capture("user: 覆盖率冒烟对话\nassistant: 收到",
69
+ tag="即记", kind="episode"))
70
+ step("injectable_lessons", lambda: mem.injectable_lessons("覆盖率"))
71
+ step("detect_conflicts", lambda: mem.detect_conflicts(limit=10))
72
+ step("set_frozen", lambda: ids.get("a") and mem.set_frozen(ids["a"], True))
73
+ step("touch_by_emotion", lambda: ids.get("a") and mem.touch_by_emotion(ids["a"], -0.7, 0.8))
74
+ step("fetch", lambda: ids.get("a") and mem.fetch(ids["a"]))
75
+ step("emotion now", em.mood_now)
76
+ step("emotion feel", lambda: em.feel("满足", intensity=0.5, why="冒烟"))
77
+ step("emotion auto", lambda: em.auto_appraise("这次真的很难过很委屈,气死了,"
78
+ "希望以后别再这样,我真的会很失望,也很难受"))
79
+ step("persona load", pe.load_persona)
80
+ step("persona snapshot", lambda: pe.persona_snapshot("覆盖率冒烟"))
81
+ step("dream report", lambda: dream.dream_report() if hasattr(dream, "dream_report") else None)
82
+ step("dream verify", lambda: dream.dream_verify() if hasattr(dream, "dream_verify") else None)
83
+ step("growth digest", lambda: growth.digest(3))
84
+ step("growth stage", growth.stage_state)
85
+ step("growth health", growth.health_score)
86
+ step("growth skill_evolve", lambda: growth.skill_evolve(days=7, dry_run=True))
87
+ step("safety snapshot", lambda: safety_net.snapshot("覆盖率冒烟"))
88
+ step("safety list", safety_net.list_snapshots)
89
+ step("shape audit", lambda: shape_audit.audit())
90
+ step("core doctor-ish", lambda: core.load_config())
91
+ return done
92
+
93
+
94
+ def _count_coverage(tracer: trace.Trace) -> dict:
95
+ """从 trace 结果算每个文件的 (hit_lines, total_lines)。"""
96
+ counts = tracer.results().counts # {(filename, lineno): count}
97
+ hit = {}
98
+ for (fname, lineno), cnt in counts.items():
99
+ try:
100
+ p = pathlib.Path(fname).resolve()
101
+ except OSError:
102
+ continue
103
+ if p.parent != SCRIPTS.resolve() or p.suffix != ".py":
104
+ continue
105
+ if cnt > 0:
106
+ hit.setdefault(p.name, set()).add(lineno)
107
+
108
+ # 每个文件的可执行行数:用 ast 之外最省事的办法——非空、非纯注释行
109
+ out = {}
110
+ for py in sorted(SCRIPTS.glob("*.py")):
111
+ try:
112
+ lines = py.read_text(encoding="utf-8", errors="replace").splitlines()
113
+ except OSError:
114
+ continue
115
+ total = 0
116
+ for raw in lines:
117
+ s = raw.strip()
118
+ if not s or s.startswith("#"):
119
+ continue
120
+ total += 1
121
+ n_hit = len(hit.get(py.name, ()))
122
+ if total:
123
+ out[py.name] = (n_hit, total)
124
+ return out
125
+
126
+
127
+ def main(argv=None) -> int:
128
+ ap = argparse.ArgumentParser(description="零依赖主 API 冒烟覆盖率")
129
+ ap.add_argument("--min", type=int, default=0,
130
+ help="低于该百分比的模块视为可疑,退出码 1(默认 0 = 只报告)")
131
+ ap.add_argument("--top", type=int, default=10, help="列出覆盖率最低的 N 个模块")
132
+ args = ap.parse_args(argv)
133
+
134
+ tracer = trace.Trace(count=1, trace=0, ignoredirs=[sys.prefix, sys.exec_prefix])
135
+ done = tracer.runfunc(_exercise)
136
+ cov = _count_coverage(tracer)
137
+
138
+ ok = [n for n, good in done if good]
139
+ bad = [n for n, good in done if not good]
140
+ print(f"主链路冒烟:{len(ok)} 步成功 / {len(bad)} 步失败")
141
+ for name in bad:
142
+ print(f" ⚠ 失败:{name}")
143
+
144
+ rows = [(name, h, t, (h / t * 100 if t else 0.0)) for name, (h, t) in cov.items()]
145
+ rows.sort(key=lambda r: r[3])
146
+ tot_h = sum(r[1] for r in rows)
147
+ tot_t = sum(r[2] for r in rows)
148
+ print(f"\n脚本行覆盖(主 API 冒烟口径):{tot_h}/{tot_t} = "
149
+ f"{tot_h / tot_t * 100:.1f}%" if tot_t else "无数据")
150
+
151
+ print(f"\n覆盖率最低的 {args.top} 个模块:")
152
+ for name, h, t, pct in rows[:args.top]:
153
+ print(f" {pct:>5.1f}% {h:>4}/{t:<5} {name}")
154
+
155
+ suspects = [r for r in rows if r[3] < args.min and r[2] >= 20]
156
+ if args.min and suspects:
157
+ print(f"\n[失败] {len(suspects)} 个模块覆盖率低于 {args.min}%:")
158
+ for name, h, t, pct in suspects[:12]:
159
+ print(f" {pct:.1f}% {name}")
160
+ return 1
161
+ if bad:
162
+ return 2
163
+ return 0
164
+
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
+
193
+ if __name__ == "__main__":
194
+ _ensure_utf8_stdout()
195
+ sys.exit(main())
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
 
@@ -10,6 +10,7 @@
10
10
  用法:python scripts/make_icon.py [--out 路径.ico]
11
11
  """
12
12
  from __future__ import annotations
13
+ import sys
13
14
 
14
15
  import argparse
15
16
  import math
@@ -142,5 +143,28 @@ def main() -> int:
142
143
  return 0
143
144
 
144
145
 
146
+ def _ensure_utf8_stdout() -> None:
147
+ """stdout/stderr 切 UTF-8——Windows CI 是 cp1252,print 中文会直接崩。"""
148
+ for _name in ("stdout", "stderr"):
149
+ _s = getattr(sys, _name, None)
150
+ _fn = getattr(_s, "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
+ try:
158
+ import io
159
+ _buf = getattr(_s, "buffer", None)
160
+ if _buf is not None:
161
+ setattr(sys, _name,
162
+ io.TextIOWrapper(_buf, encoding="utf-8", errors="replace",
163
+ line_buffering=True))
164
+ except Exception:
165
+ pass
166
+
167
+
145
168
  if __name__ == "__main__":
169
+ _ensure_utf8_stdout()
146
170
  raise SystemExit(main())