lingshu-skill 5.11.0 → 5.17.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 +217 -0
  2. package/README.md +121 -1
  3. package/SKILL.md +3 -1
  4. package/assets/panel.html +94 -2
  5. package/cordis-plugin/lingshu-cron/plugin.js +59 -0
  6. package/docs/panel-api.md +106 -13
  7. package/docs//345/200/237/351/211/264/345/276/205/345/212/236-DSH/346/217/222/344/273/266/347/224/237/346/200/201.md +224 -0
  8. package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +38 -1
  9. package/package.json +1 -1
  10. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +13 -12
  11. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +217 -0
  12. package/scripts/astrbot_plugin_lingshu/engine/README.md +121 -1
  13. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +3 -1
  14. package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +94 -2
  15. package/scripts/astrbot_plugin_lingshu/engine/docs/panel-api.md +106 -13
  16. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +100 -0
  17. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +51 -8
  18. package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +75 -1
  19. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +332 -76
  20. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +312 -16
  21. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +104 -0
  22. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_settings.py +9 -0
  23. package/scripts/astrbot_plugin_lingshu/engine/scripts/speak_up.py +186 -0
  24. package/scripts/cli.py +100 -0
  25. package/scripts/core.py +51 -8
  26. package/scripts/emotion.py +75 -1
  27. package/scripts/growth.py +332 -76
  28. package/scripts/memory.py +312 -16
  29. package/scripts/panel_server.py +104 -0
  30. package/scripts/panel_settings.py +9 -0
  31. package/scripts/speak_up.py +186 -0
package/scripts/growth.py CHANGED
@@ -1986,10 +1986,16 @@ def _npm_meta_cache_path() -> Path:
1986
1986
  return brain.HOME / "npm-meta.json"
1987
1987
 
1988
1988
 
1989
- def npm_latest(force: bool = False, timeout: int = 20) -> dict:
1989
+ def npm_latest(force: bool = False, timeout: int = 20, retries: int = 1) -> dict:
1990
1990
  """查 npm 上 lingshu-skill 的最新版本(只读,带缓存)。
1991
1991
 
1992
1992
  返回 {ok, version, tarball, shasum, unpacked, fetched_at} 或 {ok: False, error}。
1993
+
1994
+ 2026-11-25 加:
1995
+ - 限流重试(403/429 时 sleep 2s 重试 1 次)——npm registry 对匿名请求 1h 60 次,
1996
+ 面板启动时后台 force_pull 写缓存 + 浏览器刷新 auto 读缓存,偶发撞限额是常态;
1997
+ 重试一次能把"偶发 403"变成"真 403 才失败",用户感知好一截。
1998
+ - User-Agent 带版本号 + 仓库地址——npm 能统计真实下载来源。
1993
1999
  """
1994
2000
  cache_p = _npm_meta_cache_path()
1995
2001
  if not force:
@@ -2000,29 +2006,43 @@ def npm_latest(force: bool = False, timeout: int = 20) -> dict:
2000
2006
  except (OSError, ValueError, TypeError):
2001
2007
  pass
2002
2008
  url = f"{NPM_REGISTRY}/{NPM_PACKAGE}/latest"
2003
- try:
2004
- req = urllib.request.Request(url, headers={
2005
- "User-Agent": "lingshu-skill-updater",
2006
- "Accept": "application/json",
2007
- })
2008
- with urllib.request.urlopen(req, timeout=timeout) as r:
2009
- data = json.loads(r.read().decode("utf-8", "replace"))
2010
- dist = data.get("dist") or {}
2011
- out = {"ok": True, "version": str(data.get("version") or ""),
2012
- "tarball": str(dist.get("tarball") or ""),
2013
- "shasum": str(dist.get("shasum") or ""),
2014
- "unpacked": int(dist.get("unpackedSize") or 0),
2015
- "fetched_at": int(time.time())}
2016
- if not out["version"] or not out["tarball"]:
2017
- return {"ok": False, "error": "npm 返回的版本信息不完整"}
2009
+ _ua = "lingshu-skill/5.13 (+https://github.com/Q2667671398/lingshu-skill)"
2010
+ last_err = None
2011
+ for attempt in range(retries + 1):
2018
2012
  try:
2019
- cache_p.parent.mkdir(parents=True, exist_ok=True)
2020
- cache_p.write_text(json.dumps(out, ensure_ascii=False), encoding="utf-8")
2021
- except OSError:
2022
- pass
2023
- return out
2024
- except Exception as exc: # noqa: BLE001
2025
- return {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
2013
+ req = urllib.request.Request(url, headers={
2014
+ "User-Agent": _ua,
2015
+ "Accept": "application/json",
2016
+ })
2017
+ with urllib.request.urlopen(req, timeout=timeout) as r:
2018
+ data = json.loads(r.read().decode("utf-8", "replace"))
2019
+ dist = data.get("dist") or {}
2020
+ out = {"ok": True, "version": str(data.get("version") or ""),
2021
+ "tarball": str(dist.get("tarball") or ""),
2022
+ "shasum": str(dist.get("shasum") or ""),
2023
+ "unpacked": int(dist.get("unpackedSize") or 0),
2024
+ "fetched_at": int(time.time())}
2025
+ if not out["version"] or not out["tarball"]:
2026
+ return {"ok": False, "error": "npm 返回的版本信息不完整"}
2027
+ try:
2028
+ cache_p.parent.mkdir(parents=True, exist_ok=True)
2029
+ cache_p.write_text(json.dumps(out, ensure_ascii=False), encoding="utf-8")
2030
+ except OSError:
2031
+ pass
2032
+ return out
2033
+ except urllib.error.HTTPError as exc: # noqa: F821
2034
+ last_err = f"HTTP {exc.code}: {exc.reason}"
2035
+ if exc.code in (403, 429, 502, 503) and attempt < retries:
2036
+ time.sleep(2)
2037
+ continue
2038
+ return {"ok": False, "error": last_err}
2039
+ except Exception as exc: # noqa: BLE001
2040
+ last_err = f"{type(exc).__name__}: {exc}"
2041
+ if attempt < retries and any(k in last_err for k in ("URLError", "timed out", "Connection", "getaddrinfo")):
2042
+ time.sleep(2)
2043
+ continue
2044
+ return {"ok": False, "error": last_err}
2045
+ return {"ok": False, "error": last_err or "未知错误"}
2026
2046
 
2027
2047
 
2028
2048
  def _safe_extract_tgz(tgz_path: Path, dest: Path) -> Path:
@@ -2059,7 +2079,13 @@ def _safe_extract_tgz(tgz_path: Path, dest: Path) -> Path:
2059
2079
 
2060
2080
 
2061
2081
  def _lingshu_npm_source(force: bool = False) -> tuple[Path, str]:
2062
- """下载并解出 npm 版灵枢,返回 (源目录, "npm");失败抛 KeyError 带原因。"""
2082
+ """下载并解出 npm 版灵枢,返回 (源目录, "npm");失败抛 KeyError 带原因。
2083
+
2084
+ 2026-11-25:
2085
+ - tarball 下载加 1 次重试(网络抖动时 sleep 2s 重连)——大 tarball 下载中途断连
2086
+ 是常见情况,重试一次能把"偶发网络抖动"变成"真失败才抛";
2087
+ - User-Agent 与 npm_latest 统一(带版本号 + 仓库地址)。
2088
+ """
2063
2089
  meta = npm_latest(force=force)
2064
2090
  if not meta.get("ok"):
2065
2091
  raise KeyError(f"npm 版本查询失败:{meta.get('error')}")
@@ -2069,51 +2095,58 @@ def _lingshu_npm_source(force: bool = False) -> tuple[Path, str]:
2069
2095
  return dest, "npm" # 已经下过这个版本,直接复用
2070
2096
  tmp_dir = dest.parent / f".npm-tmp-{ver}-{uuid.uuid4().hex[:8]}"
2071
2097
  tgz = tmp_dir.with_suffix(".tgz")
2072
- try:
2073
- tmp_dir.parent.mkdir(parents=True, exist_ok=True)
2074
- req = urllib.request.Request(meta["tarball"],
2075
- headers={"User-Agent": "lingshu-skill-updater"})
2076
- h = hashlib.sha1()
2077
- got = 0
2078
- with urllib.request.urlopen(req, timeout=60) as r, open(tgz, "wb") as out:
2079
- while True:
2080
- chunk = r.read(256 * 1024)
2081
- if not chunk:
2082
- break
2083
- got += len(chunk)
2084
- if got > NPM_MAX_BYTES:
2085
- raise KeyError(f"npm 包体超过上限(>{NPM_MAX_BYTES // (1024 * 1024)}MB),已中止")
2086
- h.update(chunk)
2087
- out.write(chunk)
2088
- want = str(meta.get("shasum") or "")
2089
- if want and h.hexdigest() != want:
2090
- raise KeyError(f"npm 包校验失败(sha1 不符):期望 {want[:12]}…,实得 {h.hexdigest()[:12]}…")
2091
- _safe_extract_tgz(tgz, tmp_dir)
2092
- if not (tmp_dir / "SKILL.md").is_file():
2093
- raise KeyError("npm 包里没有 SKILL.md,可能不是灵枢技能包")
2094
- if dest.exists():
2095
- shutil.rmtree(dest, ignore_errors=True)
2096
- tmp_dir.rename(dest)
2097
- try:
2098
- brain.log_event("update", f"已从 npm 下载灵枢 v{ver}({got // 1024} KB,sha1 校验通过)")
2099
- except Exception:
2100
- pass
2101
- return dest, "npm"
2102
- except KeyError:
2103
- raise
2104
- except Exception as exc: # noqa: BLE001
2105
- raise KeyError(f"npm 下载失败:{type(exc).__name__}: {exc}") from exc
2106
- finally:
2098
+ _ua = "lingshu-skill/5.13 (+https://github.com/Q2667671398/lingshu-skill)"
2099
+ _last_err = None
2100
+ for _attempt in range(2): # 1 次初始 + 1 次重试
2107
2101
  try:
2108
- if tgz.is_file():
2109
- tgz.unlink()
2110
- except OSError:
2111
- pass
2112
- try:
2113
- if tmp_dir.is_dir():
2114
- shutil.rmtree(tmp_dir, ignore_errors=True)
2115
- except OSError:
2116
- pass
2102
+ tmp_dir.parent.mkdir(parents=True, exist_ok=True)
2103
+ req = urllib.request.Request(meta["tarball"],
2104
+ headers={"User-Agent": _ua})
2105
+ h = hashlib.sha1()
2106
+ got = 0
2107
+ with urllib.request.urlopen(req, timeout=60) as r, open(tgz, "wb") as out:
2108
+ while True:
2109
+ chunk = r.read(256 * 1024)
2110
+ if not chunk:
2111
+ break
2112
+ got += len(chunk)
2113
+ if got > NPM_MAX_BYTES:
2114
+ raise KeyError(f"npm 包体超过上限(>{NPM_MAX_BYTES // (1024 * 1024)}MB),已中止")
2115
+ h.update(chunk)
2116
+ out.write(chunk)
2117
+ want = str(meta.get("shasum") or "")
2118
+ if want and h.hexdigest() != want:
2119
+ raise KeyError(f"npm 包校验失败(sha1 不符):期望 {want[:12]}…,实得 {h.hexdigest()[:12]}…")
2120
+ _safe_extract_tgz(tgz, tmp_dir)
2121
+ if not (tmp_dir / "SKILL.md").is_file():
2122
+ raise KeyError("npm 包里没有 SKILL.md,可能不是灵枢技能包")
2123
+ break # 成功 → 跳出重试
2124
+ except (KeyError, OSError) as exc:
2125
+ # KeyError 是路径穿越 / 包体太大 / sha1 不符 / SKILL.md 缺失——这些是"包本身有问题",
2126
+ # 重试没用,直接 re-raise 给 install_skill 让它抛异常。
2127
+ raise
2128
+ except Exception as exc: # noqa: BLE001 — 网络抖动 / 超时 / 断连
2129
+ _last_err = f"{type(exc).__name__}: {exc}"
2130
+ if _attempt == 0:
2131
+ time.sleep(2)
2132
+ # 重试前先删掉半截 tarball(否则会走校验失败而不是重新下载)
2133
+ try: tgz.unlink(missing_ok=True)
2134
+ except OSError: pass
2135
+ else:
2136
+ raise KeyError(f"npm 包下载失败:{_last_err}")
2137
+ # 成功跳出循环后:把 tmp_dir 重命名为正式 dest、清理临时文件。
2138
+ # 这段在 for 循环外——不管循环里重试了几次,最后一次成功后统一走。
2139
+ if dest.exists():
2140
+ shutil.rmtree(dest, ignore_errors=True)
2141
+ tmp_dir.rename(dest)
2142
+ try:
2143
+ brain.log_event("update", f"已从 npm 下载灵枢 v{ver}({got // 1024} KB,sha1 校验通过)")
2144
+ except Exception:
2145
+ pass
2146
+ # 清理临时 tgz(已解包完成,留着占地)
2147
+ try: tgz.unlink()
2148
+ except OSError: pass
2149
+ return dest, "npm"
2117
2150
 
2118
2151
 
2119
2152
  def _update_check_live(name: str = "lingshu", force_pull: bool = False) -> dict:
@@ -2168,13 +2201,40 @@ def _update_check_live(name: str = "lingshu", force_pull: bool = False) -> dict:
2168
2201
  except (ValueError, KeyError):
2169
2202
  installed_dir = Path()
2170
2203
  if not (installed_dir / "SKILL.md").exists():
2171
- return {"name": name, "installed": False, "outdated": False,
2172
- "stale_source": False,
2173
- "version": _ver(meta.get("version", 1)),
2174
- "source_version": _ver(meta.get("version", 1)),
2175
- "installed_version": "",
2176
- "checked_at": int(time.time()), "cached_at": 0,
2177
- "global_path": str(installed_dir)}
2204
+ # 没装全局副本。若源是**本地开发仓库**(dev),"仓库 vs 空"毫无意义——
2205
+ # 这时和 **npm** 最新版比,更新按钮才有内容可给(否则永远"已是最新")。
2206
+ _dev_ver = _ver(meta.get("version", 1))
2207
+ _base = {"name": name, "installed": False, "outdated": False,
2208
+ "stale_source": False,
2209
+ "version": _dev_ver, "source_version": _dev_ver,
2210
+ "installed_version": "",
2211
+ "checked_at": int(time.time()), "cached_at": 0,
2212
+ "global_path": str(installed_dir)}
2213
+ if out_src == "dev":
2214
+ _base["source"] = "dev"
2215
+ _base["dev_repo"] = True
2216
+ try:
2217
+ _nm = npm_latest(force=force_pull)
2218
+ except Exception as exc: # noqa: BLE001
2219
+ _nm = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
2220
+ if _nm.get("ok"):
2221
+ _nm_ver = str(_nm.get("version") or "")
2222
+ _base["npm"] = {"version": _nm_ver, "unpacked": _nm.get("unpacked")}
2223
+ try:
2224
+ # 必须补零到三段再比:5.11 与 5.11.0 是同一版本,
2225
+ # 但 (5,11,0) > (5,11) 为 True,会误报"有更新"。
2226
+ _dv = tuple(([int(x) for x in str(_dev_ver).split(".")] + [0, 0, 0])[:3])
2227
+ _nv = tuple(([int(x) for x in _nm_ver.split(".")] + [0, 0, 0])[:3])
2228
+ except (TypeError, ValueError):
2229
+ _dv = _nv = None
2230
+ if _dv is not None and _nv is not None and _nv > _dv:
2231
+ # 仓库比 npm 旧:提示可装 npm 上的新版
2232
+ _base.update({"outdated": True, "source": "npm",
2233
+ "installed_version": _dev_ver,
2234
+ "source_version": _nm_ver, "version": _nm_ver})
2235
+ else:
2236
+ _base["npm_error"] = _nm.get("error") or "npm 版本查询失败"
2237
+ return _base
2178
2238
 
2179
2239
  src_sig = _diff_signature(src_dir)
2180
2240
  dst_sig = _diff_signature(installed_dir)
@@ -2189,10 +2249,19 @@ def _update_check_live(name: str = "lingshu", force_pull: bool = False) -> dict:
2189
2249
  # 同版本就是没有新版本。否则会出现「v2.87 → v2.87 还报有更新」的怪弹窗
2190
2250
  # (面板标题两个版本号一样,内容差异却让 outdated=true)。
2191
2251
  def _ver_tuple(v) -> tuple | None:
2252
+ """版本号 → **定长三段**元组。
2253
+
2254
+ 必须补零到三段:`"5.11"` 与 `"5.11.0"` 是同一个版本,但 Python 元组比较里
2255
+ (5, 11, 0) > (5, 11) 为 True——曾导致「仓库 5.11 / npm 5.11.0」误报有更新。
2256
+ """
2192
2257
  try:
2193
- return tuple(int(x) for x in str(v).strip().split("."))
2258
+ parts = [int(x) for x in str(v).strip().split(".")]
2194
2259
  except (TypeError, ValueError):
2195
2260
  return None
2261
+ if not parts:
2262
+ return None
2263
+ parts = (parts + [0, 0, 0])[:3]
2264
+ return tuple(parts)
2196
2265
  src_v, inst_v = _ver_tuple(meta.get("version", 1)), _ver_tuple(inst_meta.get("version", 1))
2197
2266
  same_version = (src_v is not None and inst_v is not None and src_v == inst_v)
2198
2267
  outdated = bool(src_sig != dst_sig) and not same_version and (
@@ -2243,6 +2312,24 @@ def _update_check_live(name: str = "lingshu", force_pull: bool = False) -> dict:
2243
2312
  cached_at = int((src_dir / "SKILL.md").stat().st_mtime)
2244
2313
  except OSError:
2245
2314
  cached_at = 0
2315
+ # —— dev 模式:仓库即源,没有"已装副本"可比。这时和 **npm** 比才有意义,
2316
+ # 否则从仓库直接跑面板的人会看到一个永远"已是最新"的死按钮。
2317
+ dev_npm = None
2318
+ dev_npm_error = None
2319
+ if out_src == "dev" and src_v is not None:
2320
+ try:
2321
+ _nm = npm_latest(force=force_pull)
2322
+ except Exception as exc: # noqa: BLE001
2323
+ _nm = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
2324
+ if _nm.get("ok"):
2325
+ _nm_v = _ver_tuple(_nm.get("version"))
2326
+ dev_npm = {"version": _nm.get("version"),
2327
+ "unpacked": _nm.get("unpacked")}
2328
+ if _nm_v is not None and _nm_v > src_v:
2329
+ outdated = True
2330
+ else:
2331
+ dev_npm_error = _nm.get("error") or "npm 版本查询失败"
2332
+
2246
2333
  out = {
2247
2334
  "name": name,
2248
2335
  "installed": True,
@@ -2258,6 +2345,23 @@ def _update_check_live(name: str = "lingshu", force_pull: bool = False) -> dict:
2258
2345
  "cached_at": cached_at,
2259
2346
  "global_path": str(installed_dir),
2260
2347
  }
2348
+ if dev_npm:
2349
+ # dev 模式下 npm 查询成功就必须设这两个字段——不管 npm 版本比本地新还是旧。
2350
+ # 之前只在 npm 真更新(outdated=True)或 npm 查失败时才设,导致 npm 版本
2351
+ # 落后于本地时(本地正在开发新版本、npm 还没同步)dev_repo 和 npm 字段
2352
+ # 都丢失,前端和测试都懵。
2353
+ out["dev_repo"] = True
2354
+ out["npm"] = dev_npm
2355
+ if out.get("outdated"):
2356
+ # 仓库 vX → npm vY:明确"能装的版本在 npm 上",别让人以为仓库自己会变
2357
+ out["source"] = "npm"
2358
+ out["installed_version"] = out["installed_version"] or out["version"]
2359
+ out["source_version"] = dev_npm.get("version") or out["source_version"]
2360
+ out["version"] = out["source_version"]
2361
+ elif dev_npm_error:
2362
+ # npm 查询失败(限流 / 网络 / npm 短暂挂掉),把原因透传给前端
2363
+ out["dev_repo"] = True
2364
+ out["npm_error"] = dev_npm_error
2261
2365
  if stale_source:
2262
2366
  detail = f"远程源不可用,缓存源版本(v{out['version']})不比已装" \
2263
2367
  f"(v{out['installed_version']})新,已忽略这次检查,不倒退更新"
@@ -3336,6 +3440,158 @@ def _upgrade_hint(c: dict) -> str:
3336
3440
  return 'python scripts/brain.py skill install lingshu --from "<当前目录>" --force --yes'
3337
3441
 
3338
3442
 
3443
+ # ---------------------------------------------------------------- 成长阶段(P2-4)
3444
+
3445
+ DOCTOR_HISTORY = "doctor-history.jsonl"
3446
+ STAGES = ("蛋", "幼体", "少年", "成年", "传奇")
3447
+
3448
+
3449
+ def _dh_path() -> Path:
3450
+ return brain.HOME / DOCTOR_HISTORY
3451
+
3452
+
3453
+ def record_doctor_run(passed: int, warned: int, failed: int,
3454
+ kind: str = "doctor") -> None:
3455
+ """追加一条体检/自审历史。只增不改,失败静默(观测代码绝不能拖累体检本身)。"""
3456
+ try:
3457
+ path = _dh_path()
3458
+ path.parent.mkdir(parents=True, exist_ok=True)
3459
+ row = {"ts": int(time.time()), "kind": str(kind or "doctor"),
3460
+ "pass": int(passed), "warn": int(warned), "fail": int(failed)}
3461
+ with open(path, "a", encoding="utf-8", newline="\n") as f:
3462
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
3463
+ except (OSError, ValueError, TypeError):
3464
+ pass
3465
+
3466
+
3467
+ def doctor_history(limit: int = 0) -> list:
3468
+ """读体检历史(旧的在前)。limit>0 只取最近 N 条。"""
3469
+ path = _dh_path()
3470
+ if not path.is_file():
3471
+ return []
3472
+ rows = []
3473
+ try:
3474
+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
3475
+ line = line.strip()
3476
+ if not line:
3477
+ continue
3478
+ try:
3479
+ rows.append(json.loads(line))
3480
+ except ValueError:
3481
+ continue
3482
+ except OSError:
3483
+ return []
3484
+ return rows[-limit:] if limit and limit > 0 else rows
3485
+
3486
+
3487
+ def _recent_failures(days: int = 7) -> int:
3488
+ """近 N 天的被吞异常条数(failures.jsonl)。拿不到返回 0。"""
3489
+ try:
3490
+ import failures as _f
3491
+ return len(_f.recent(days=days, limit=10000) or [])
3492
+ except Exception: # noqa: BLE001
3493
+ pass
3494
+ try:
3495
+ path = brain.HOME / "failures.jsonl"
3496
+ if not path.is_file():
3497
+ return 0
3498
+ cutoff = time.time() - days * 86400
3499
+ n = 0
3500
+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
3501
+ line = line.strip()
3502
+ if not line:
3503
+ continue
3504
+ try:
3505
+ if float(json.loads(line).get("ts") or 0) >= cutoff:
3506
+ n += 1
3507
+ except (ValueError, TypeError):
3508
+ continue
3509
+ return n
3510
+ except OSError:
3511
+ return 0
3512
+
3513
+
3514
+ def _tag_coverage() -> float:
3515
+ """记忆里"有标签或实体"的占比(0~1)。这是"被结构化过"的粗略度量。"""
3516
+ try:
3517
+ import memory as _m
3518
+ rows = [r for r in _m.load_all() if isinstance(r, dict) and r.get("id")]
3519
+ except Exception: # noqa: BLE001
3520
+ return 0.0
3521
+ if not rows:
3522
+ return 0.0
3523
+ good = sum(1 for r in rows if (r.get("tags") or r.get("entities")))
3524
+ return good / len(rows)
3525
+
3526
+
3527
+ def stage_state() -> dict:
3528
+ """算出当前成长阶段 + 依据(面板/CLI 都读它)。"""
3529
+ hist = doctor_history()
3530
+ doc_runs = sum(1 for r in hist if str(r.get("kind") or "doctor") == "doctor")
3531
+ self_reviews = sum(1 for r in hist if str(r.get("kind")) == "self-review")
3532
+ fails = _recent_failures(7)
3533
+ # 发布漂移"修过":历史里出现过 fail>0,之后又出现 fail==0
3534
+ drift_fixed = False
3535
+ seen_bad = False
3536
+ for r in hist:
3537
+ try:
3538
+ f = int(r.get("fail") or 0)
3539
+ except (TypeError, ValueError):
3540
+ f = 0
3541
+ if f > 0:
3542
+ seen_bad = True
3543
+ elif seen_bad:
3544
+ drift_fixed = True
3545
+ break
3546
+ cov = _tag_coverage()
3547
+
3548
+ stage = "蛋"
3549
+ if doc_runs >= 5 and fails < 3:
3550
+ stage = "幼体"
3551
+ if doc_runs >= 30 and fails < 10 and self_reviews >= 5:
3552
+ stage = "少年"
3553
+ if doc_runs >= 100 and fails < 20 and self_reviews >= 20 and drift_fixed:
3554
+ stage = "成年"
3555
+ if stage == "成年" and cov >= 0.45:
3556
+ stage = "传奇"
3557
+
3558
+ # 下一阶段还差什么(面板上给人看,避免"为什么我不是成年"的困惑)
3559
+ need = []
3560
+ if stage == "蛋":
3561
+ # 别只说"去跑 doctor"——如果已经跑了很多次而是 failures 卡住,必须说清楚,
3562
+ # 否则用户看到"蛋"会以为系统没记录他的操作。
3563
+ if doc_runs < 5:
3564
+ need.append(f"doctor 还差 {5 - doc_runs} 次(≥5 次进幼体)")
3565
+ if fails >= 3:
3566
+ need.append(f"近 7 天 failures {fails} 条(需 <3 才能进幼体)")
3567
+ elif stage == "幼体":
3568
+ if doc_runs < 30:
3569
+ need.append(f"doctor 还差 {30 - doc_runs} 次")
3570
+ if fails >= 10:
3571
+ need.append(f"近 7 天 failures {fails} 条(需 <10)")
3572
+ if self_reviews < 5:
3573
+ need.append(f"self-review 还差 {5 - self_reviews} 次")
3574
+ elif stage == "少年":
3575
+ if doc_runs < 100:
3576
+ need.append(f"doctor 还差 {100 - doc_runs} 次")
3577
+ if fails >= 20:
3578
+ need.append(f"近 7 天 failures {fails} 条(需 <20)")
3579
+ if self_reviews < 20:
3580
+ need.append(f"self-review 还差 {20 - self_reviews} 次")
3581
+ if not drift_fixed:
3582
+ need.append("还没出现过「漂移被修复」的记录")
3583
+ elif stage == "成年":
3584
+ need.append(f"标签/实体覆盖率 {cov * 100:.0f}%(需 ≥45% 进传奇)")
3585
+
3586
+ label = f"{stage}(doctor {doc_runs} 次 / failures {fails} 条)"
3587
+ # 跑了不少次却还在"蛋":明说是被 failures 卡住,不是没在记录
3588
+ if stage == "蛋" and doc_runs >= 5:
3589
+ label += "·卡在 failures"
3590
+ return {"stage": stage, "doctor_runs": doc_runs, "self_reviews": self_reviews,
3591
+ "failures_7d": fails, "coverage": round(cov, 3),
3592
+ "drift_fixed": drift_fixed, "next": need, "label": label}
3593
+
3594
+
3339
3595
  def release_drift() -> dict:
3340
3596
  """发布漂移自检:**源码版本 vs 本机已安装副本**(doctor 用)。
3341
3597