lingshu-skill 5.23.0 → 5.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +88 -0
- package/README.md +1 -1
- package/SKILL-lite.md +1 -1
- package/SKILL-tiny.md +1 -1
- package/SKILL.md +2 -1
- package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +13 -1
- package/package.json +1 -1
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +14 -13
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +88 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +2 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +43 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +90 -2
- package/scripts/astrbot_plugin_lingshu/engine/scripts/coverage_report.py +167 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +221 -219
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +23 -3
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +470 -460
- package/scripts/astrbot_plugin_lingshu/engine/scripts/release.py +14 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +29 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety_net.py +12 -0
- package/scripts/check_version.py +16 -0
- package/scripts/cli.py +43 -0
- package/scripts/core.py +90 -2
- package/scripts/coverage_report.py +167 -0
- package/scripts/mem_dialogue.py +221 -219
- package/scripts/memory.py +23 -3
- package/scripts/panels.py +470 -460
- package/scripts/release.py +14 -0
- package/scripts/safety.py +29 -1
- package/scripts/safety_net.py +12 -0
|
@@ -121,6 +121,20 @@ def do_bump(new_ver: str, title: str) -> int:
|
|
|
121
121
|
print(f"[release] {rel} 没找到版本标记 {o!r},拒绝继续", file=sys.stderr)
|
|
122
122
|
return 1
|
|
123
123
|
p.write_bytes(b.replace(o, n, 1))
|
|
124
|
+
# 1b) SKILL-lite / SKILL-tiny 的 version 跟着走。
|
|
125
|
+
# 它们不触发"必须升版"(裁剪文档,正文可能长期不动),但头部的 version 若十年不动,
|
|
126
|
+
# 会让人误判"这份文档对得上引擎"。用字节级正则改,保 BOM 与原换行。
|
|
127
|
+
for rel in ("SKILL-lite.md", "SKILL-tiny.md"):
|
|
128
|
+
lp = ROOT / rel
|
|
129
|
+
if not lp.is_file():
|
|
130
|
+
continue
|
|
131
|
+
b = lp.read_bytes()
|
|
132
|
+
nb, cnt = re.subn(rb"^version:\s*[\d.]+",
|
|
133
|
+
f"version: {new_ver}".encode(), b, count=1, flags=re.M)
|
|
134
|
+
if cnt:
|
|
135
|
+
lp.write_bytes(nb)
|
|
136
|
+
print(f"[release] {rel} version → {new_ver}")
|
|
137
|
+
|
|
124
138
|
# CHANGELOG 首节改写为新版本(占位,正文留空由维护者补)
|
|
125
139
|
cl = ROOT / "CHANGELOG.md"
|
|
126
140
|
t = cl.read_text(encoding="utf-8")
|
|
@@ -324,10 +324,33 @@ def is_interactive() -> bool:
|
|
|
324
324
|
return False
|
|
325
325
|
|
|
326
326
|
|
|
327
|
+
def require_token(action: str, given: str, expected: str, *, hint: str = "") -> None:
|
|
328
|
+
"""破坏性操作的一次性确认码校验(与 confirm_destructive 同属 safety 的一套原语)。
|
|
329
|
+
|
|
330
|
+
为什么不并进 y/N:这类操作要能被**程序 / AI 调用时强制显式写下指纹**,
|
|
331
|
+
而那种场合 stdin 不是终端,交互提示根本不会出现。
|
|
332
|
+
这样说清分工,比"两套逻辑各写各的"更难出错:
|
|
333
|
+
· confirm_destructive —— 有终端时的人机确认(--yes 或 y)
|
|
334
|
+
· require_token —— 任何场合都必须匹配的指纹
|
|
335
|
+
|
|
336
|
+
不匹配抛 ValueError(调用方负责转成退出码)。
|
|
337
|
+
"""
|
|
338
|
+
if not expected:
|
|
339
|
+
raise ValueError(f"[{action}] 缺少确认码基准(内部错误)")
|
|
340
|
+
if not given or str(given) != str(expected):
|
|
341
|
+
msg = (f"[{action}] 需显式确认:确认码不匹配"
|
|
342
|
+
f"(应为目标 id 的前 {len(str(expected))} 位)")
|
|
343
|
+
if hint:
|
|
344
|
+
msg += f"。{hint}"
|
|
345
|
+
raise ValueError(msg)
|
|
346
|
+
|
|
347
|
+
|
|
327
348
|
def confirm_destructive(action: str, impact: str | list[str], *,
|
|
328
349
|
assume_yes: bool = False,
|
|
329
350
|
hint: str = "",
|
|
330
|
-
stream=None
|
|
351
|
+
stream=None,
|
|
352
|
+
token: str = "",
|
|
353
|
+
expect_token: str = "") -> bool:
|
|
331
354
|
"""破坏性操作的统一确认。返回 True=可以继续,False=调用方应中止(或被取消)。
|
|
332
355
|
|
|
333
356
|
参数:
|
|
@@ -343,6 +366,11 @@ def confirm_destructive(action: str, impact: str | list[str], *,
|
|
|
343
366
|
for line in lines:
|
|
344
367
|
print(f" - {line}", file=out)
|
|
345
368
|
|
|
369
|
+
# 指纹校验放在最前:设了 expect_token 就必须匹配,--yes 也绕不过。
|
|
370
|
+
# 这样"确认码"与"影响面提示"是同一处代码,不会出现某个入口忘了校验。
|
|
371
|
+
if expect_token:
|
|
372
|
+
require_token(action, token, expect_token, hint=hint)
|
|
373
|
+
|
|
346
374
|
if assume_yes:
|
|
347
375
|
print(f"[{action}] 已通过 --yes 确认。", file=out)
|
|
348
376
|
if hint:
|
|
@@ -339,6 +339,13 @@ def guarded_write(reason: str, writer, names=None, allow_shrink=()) -> dict:
|
|
|
339
339
|
report["error"] = f"写入异常已回滚:{err}"
|
|
340
340
|
except Exception as rexc: # noqa: BLE001
|
|
341
341
|
report["error"] = f"写入异常且回滚失败:{err} / {rexc}"
|
|
342
|
+
# 最危险的一档:写入出了问题、回滚也没成功 ⇒ 数据处于脏状态,
|
|
343
|
+
# 却只体现在返回值里。计一次数,让 doctor 的 swallowed 项能看见。
|
|
344
|
+
try:
|
|
345
|
+
import core as _c
|
|
346
|
+
_c.swallow("safety.rollback", rexc, where="safety_net.guarded_write")
|
|
347
|
+
except Exception: # noqa: BLE001
|
|
348
|
+
pass
|
|
342
349
|
return report
|
|
343
350
|
if _verify_enabled():
|
|
344
351
|
v = verify(names, allow_shrink=allow_shrink)
|
|
@@ -352,4 +359,9 @@ def guarded_write(reason: str, writer, names=None, allow_shrink=()) -> dict:
|
|
|
352
359
|
report["ok"] = True # 已回滚,数据一致
|
|
353
360
|
except Exception as rexc: # noqa: BLE001
|
|
354
361
|
report["issues"].append(f"回滚失败:{rexc}")
|
|
362
|
+
try:
|
|
363
|
+
import core as _c
|
|
364
|
+
_c.swallow("safety.rollback", rexc, where="safety_net.guarded_write")
|
|
365
|
+
except Exception: # noqa: BLE001
|
|
366
|
+
pass
|
|
355
367
|
return report
|
package/scripts/check_version.py
CHANGED
|
@@ -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():
|
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
|
@@ -523,13 +523,27 @@ _REDACT_PATTERNS: list[tuple[str, re.Pattern]] = [
|
|
|
523
523
|
# npm 2026 granular token:npm_ + 36 位(本会话实测裸 token 贴进对话被
|
|
524
524
|
# capture 原文落盘——泛化 kv-secret 只认 "token=" 形态,裸发漏网,补具名规则)
|
|
525
525
|
("npm-token", re.compile(r"npm_[A-Za-z0-9]{30,}")),
|
|
526
|
-
("api-key", re.compile(r"sk-[A-Za-z0-
|
|
526
|
+
("api-key", re.compile(r"sk-[A-Za-z0-9_-]{16,}")), # 新版是 sk-proj-xxx,值里带连字符
|
|
527
527
|
("github-pat", re.compile(r"github_pat_[A-Za-z0-9_]{20,}")),
|
|
528
528
|
("github-token", re.compile(r"ghp_[A-Za-z0-9]{20,}")),
|
|
529
529
|
("slack-token", re.compile(r"xox[baprs]-[A-Za-z0-9-]{10,}")),
|
|
530
530
|
("aws-key", re.compile(r"AKIA[0-9A-Z]{16}")),
|
|
531
531
|
("bearer", re.compile(r"(?i)bearer\s+[A-Za-z0-9._\-]{20,}")),
|
|
532
|
-
|
|
532
|
+
# URL 内嵌凭据:scheme://user:pass@host 与 ?token=xxx / &access_token=xxx
|
|
533
|
+
# (`(?i)` 只能出现在表达式最前面,中间用它会报 PatternError,故用 re.I)
|
|
534
|
+
("url-cred", re.compile(
|
|
535
|
+
r"(?:[a-z][a-z0-9+.-]*://)[^\s/:@]+:[^\s/@]{6,}@"
|
|
536
|
+
r"|[?&](?:access_token|token|key|secret)=[A-Za-z0-9._~-]{12,}", re.I)),
|
|
537
|
+
# PEM 私钥整块(多行):这类东西一旦进记忆库/备份,等于把私钥复制了一份
|
|
538
|
+
("private-key", re.compile(
|
|
539
|
+
r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]{20,}?-----END [A-Z ]*PRIVATE KEY-----")),
|
|
540
|
+
# 泛化兜底:key=value 形态。**值必须是"像凭据的串"**——原式 `\s*\S+` 过宽,
|
|
541
|
+
# 会把中文正文一起脱掉("token: 加到请求头" → 连"加到请求头"都变占位符),
|
|
542
|
+
# 记忆文本被误伤比漏掉更难查,所以收紧成"引号包裹或 ≥8 位 ASCII 凭据字符"。
|
|
543
|
+
("kv-secret", re.compile(
|
|
544
|
+
r"(?i)(password|passwd|token|secret|api_key|apikey|access_key|access_key_id"
|
|
545
|
+
r"|private_key|client_secret)\s*[=:]\s*"
|
|
546
|
+
r"(?:[\"'][^\"']{8,}[\"']|[A-Za-z0-9._~+/=-]{8,})")),
|
|
533
547
|
]
|
|
534
548
|
|
|
535
549
|
_REDACT_KEEP = 3 # 保留首尾 3 字符(不足 8 字符全遮)
|
|
@@ -557,6 +571,80 @@ def redact(text: str) -> str:
|
|
|
557
571
|
return text
|
|
558
572
|
|
|
559
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
|
+
|
|
560
648
|
def log_event(kind: str, message: str, level: str = "info", **extra) -> None:
|
|
561
649
|
"""轻量运行日志(lingshu.log):锁冲突、内部异常、解析报错等留痕,面板「日志」页可看。
|
|
562
650
|
|
|
@@ -0,0 +1,167 @@
|
|
|
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
|
+
if __name__ == "__main__":
|
|
167
|
+
sys.exit(main())
|