lingshu-skill 5.14.0 → 5.18.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 (30) hide show
  1. package/CHANGELOG.md +175 -0
  2. package/README.md +107 -1
  3. package/SKILL.md +3 -1
  4. package/assets/panel.html +13 -0
  5. package/cordis-plugin/lingshu-cron/plugin.js +59 -0
  6. package/docs/panel-api.md +106 -13
  7. package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +29 -0
  8. package/package.json +1 -1
  9. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +13 -12
  10. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +175 -0
  11. package/scripts/astrbot_plugin_lingshu/engine/README.md +107 -1
  12. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +3 -1
  13. package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +13 -0
  14. package/scripts/astrbot_plugin_lingshu/engine/docs/panel-api.md +106 -13
  15. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +60 -0
  16. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +54 -8
  17. package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +1381 -1180
  18. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +5232 -5055
  19. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +7 -0
  20. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +24 -0
  21. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_settings.py +15 -0
  22. package/scripts/astrbot_plugin_lingshu/engine/scripts/speak_up.py +186 -0
  23. package/scripts/cli.py +60 -0
  24. package/scripts/core.py +54 -8
  25. package/scripts/emotion.py +1381 -1180
  26. package/scripts/growth.py +5232 -5055
  27. package/scripts/memory.py +7 -0
  28. package/scripts/panel_server.py +24 -0
  29. package/scripts/panel_settings.py +15 -0
  30. package/scripts/speak_up.py +186 -0
@@ -1364,6 +1364,13 @@ def remember(text: str, kind: str = "fact", importance: float | None = None,
1364
1364
  # 第四轮#3:合并路径补项目标记——旧条目还挂着 "default" 时趁机挂上真实项目
1365
1365
  if project and str(project).strip() and str(m.get("project") or "default") == "default":
1366
1366
  m["project"] = str(project).strip()[:64]
1367
+ # P1-4:合并时若分支变了,说明这条已是**跨分支知识** → 清掉 branch,
1368
+ # 否则它在另一个分支上会被平白降权 50%(误伤)。
1369
+ if _branch_memory_on():
1370
+ _cur_br = _git_branch()
1371
+ _old_br = str(m.get("branch") or "")
1372
+ if _cur_br and _old_br and _cur_br != _old_br:
1373
+ m.pop("branch", None)
1367
1374
  save_all(records)
1368
1375
  # P1:异步补/更新 embedding(文本变了或还没有向量才调度;
1369
1376
  # 未配置 embed 服务时 _embed_wanted 直接 False,零开销跳过)
@@ -170,7 +170,14 @@ def overview() -> dict:
170
170
  except (OSError, ValueError):
171
171
  continue
172
172
  st = _safe("stats", brain.stats, {}) or {}
173
+ # P2-4 成长阶段:面板概览一行"灵枢健康度:少年(doctor 32 次 / failures 7 条)"
174
+ try:
175
+ _stage = growth.stage_state()
176
+ except Exception: # noqa: BLE001
177
+ _stage = None
178
+
173
179
  return {
180
+ "stage": _stage,
174
181
  "stats": st,
175
182
  # 层分布统计条用:各层记忆数(含归档),纯计数不做降级分支
176
183
  "layer_counts": {"hippo": st.get("hippo", 0), "cortex": st.get("cortex", 0),
@@ -955,6 +962,18 @@ class Handler(BaseHTTPRequestHandler):
955
962
  limit = _int_param(url, "limit", 60, 1, 300)
956
963
  self._json(brain.growth_timeline(days, limit))
957
964
  return
965
+ if path == "/api/doctor-history":
966
+ # P2-4:体检历史(成长阶段/健康度都基于它)。limit 默认 90 条。
967
+ try:
968
+ lim = _int_param(url, "limit", 90, 1, 1000)
969
+ hist = growth.doctor_history(limit=lim)
970
+ st = growth.stage_state()
971
+ except Exception as exc: # noqa: BLE001
972
+ self._json({"error": f"读取体检历史失败:{exc}"}, 500)
973
+ return
974
+ self._json({"items": hist, "count": len(hist),
975
+ "stage": st, "health": st.get("health")})
976
+ return
958
977
  if path == "/api/logs":
959
978
  limit = _int_param(url, "limit", 200, 1, 2000)
960
979
  level = (parse_qs(url.query).get("level") or [""])[0] or None
@@ -1480,6 +1499,11 @@ def _api_daily(self, path, data):
1480
1499
 
1481
1500
 
1482
1501
  def _api_skill_self_review(self, path, data):
1502
+ # P2-4:自审也记一笔(成长阶段要用"self-review 次数")
1503
+ try:
1504
+ growth.record_doctor_run(0, 0, 0, kind="self-review")
1505
+ except Exception: # noqa: BLE001
1506
+ pass
1483
1507
  r = growth.self_review(force=bool(data.get("force")),
1484
1508
  days=_to_int(data.get("days", 3) or 3, 3) or 3)
1485
1509
  self._json({"ok": True, "result": r})
@@ -76,6 +76,21 @@ CONFIG_SCHEMA: list[dict[str, Any]] = [
76
76
  "hint": "送进 rerank 的候选条数,越大越准也越慢"},
77
77
 
78
78
  # —— 面板与宿主 ——
79
+ {"key": "emotion_inertia_enabled", "group": "情绪与人格", "label": "情绪惯性",
80
+ "kind": "bool",
81
+ "hint": "情绪上来快、下去慢:负面衰减更慢 + 强情绪冷却 + 标签需 2 条事件才切换"},
82
+ {"key": "emotion_negative_slow", "group": "情绪与人格", "label": "负面情绪更耐放",
83
+ "kind": "bool", "hint": "负面情绪衰减速率更慢(半衰期 ×1.25)"},
84
+ {"key": "emotion_cooldown_enabled", "group": "情绪与人格", "label": "强情绪冷却",
85
+ "kind": "bool", "hint": "强度>0.7 之后 3 个事件内同组增益减半,防越说越气"},
86
+ {"key": "emotion_label_gate_enabled", "group": "情绪与人格", "label": "心情标签防跳变",
87
+ "kind": "bool", "hint": "标签需 ≥2 条情绪事件支撑才切换,避免单句话横跳"},
88
+ {"key": "speak_up_prob", "group": "水位与节奏", "label": "主动搭话概率",
89
+ "kind": "float", "min": 0, "max": 1, "step": 0.05,
90
+ "hint": "每轮结束按此概率让灵枢自己说一句(纯模板、不进模型);0=关闭"},
91
+ {"key": "speak_up_cooldown_min", "group": "水位与节奏", "label": "主动搭话冷却(分钟)",
92
+ "kind": "int", "min": 0, "max": 1440, "step": 5,
93
+ "hint": "两次主动搭话之间至少间隔多久,防刷屏"},
79
94
  {"key": "use_index_memory", "group": "注入与预算", "label": "索引法记忆",
80
95
  "kind": "enum", "options": ["auto", "always", "off"],
81
96
  "hint": "注入只送一句索引+id,正文用 recall 取;auto=水位≥60% 才切(省 40%+ 注入量)"},
@@ -0,0 +1,186 @@
1
+ # -*- coding: utf-8 -*-
2
+ """灵枢主动搭话(P1-3):会话之间按概率自己说一句。
3
+
4
+ 借鉴 dsh-speak-up 的"本地掷骰子"——**不进模型、不花 token**,纯模板 + 词表。
5
+
6
+ 四条闸门,缺一不可(任何一条不满足就安静,绝不刷屏):
7
+ ① `speak_up_prob` > 0(默认 0.10;设 0 永不出声)
8
+ ② 用户这一轮**只是陈述**(没在问问题)
9
+ ③ 灵枢此刻情绪不激动(`rationality.effective > 30`)
10
+ ④ 距上次主动搭话 ≥ `speak_up_cooldown_min`(默认 15 分钟)
11
+
12
+ 模板库取值:从最近记忆里挑一个关键词/主题,塞进句子里——避免"干巴巴的固定话术"。
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import random
18
+ import re
19
+ import time
20
+
21
+ import brain
22
+ import core
23
+
24
+ STATE_FILE = "speak-up.json"
25
+ DEFAULT_PROB = 0.10
26
+ DEFAULT_COOLDOWN_MIN = 15
27
+
28
+ # 模板库:{关键词} 会被替换成最近记忆里的一个主题词。刻意写得短、不油腻。
29
+ TEMPLATES = (
30
+ "你好像在忙{kw},要不要说说?",
31
+ "刚才提到{kw},我有点感兴趣。",
32
+ "关于{kw},要我帮你翻翻以前的记录吗?",
33
+ "{kw}那件事,你后来怎么定的?",
34
+ "我留意到{kw},需要我记一笔吗?",
35
+ "说到{kw}——我之前是不是也碰过?",
36
+ )
37
+
38
+ # 判定"在提问"的标志:有问号、或出现这些请求词
39
+ _QUESTION_RE = re.compile(r"[??]|(吗|呢|怎么|如何|为什么|为何|是否|能不能|可不可以|要不要|帮我|请问)")
40
+ # 主题词排除:整词黑名单 + 子串黑名单(含这些基本不是"话题词")
41
+ _STOP = {"这个", "那个", "什么", "现在", "就是", "然后", "可以", "需要", "一下",
42
+ "我们", "你们", "他们", "自己", "时候", "问题", "东西", "事情", "系统",
43
+ "内容", "部分", "方式", "情况", "方法", "功能", "代码"}
44
+ _STOP_SUB = ("你", "我", "他", "她", "它", "咱", "您", "的", "了", "着", "吗",
45
+ "呢", "吧", "啊", "哦", "嗯", "是", "在", "有", "和", "与", "或",
46
+ "把", "被", "对", "从", "到", "会", "能", "要", "就", "也", "都",
47
+ "很", "太", "更", "最", "但", "而", "如", "若", "因", "所", "这",
48
+ "那", "哪", "什", "么", "怎", "为", "用", "做", "说", "看", "想")
49
+
50
+
51
+ def _state_path():
52
+ return core.HOME / STATE_FILE
53
+
54
+
55
+ def _load_state() -> dict:
56
+ try:
57
+ d = json.loads(_state_path().read_text(encoding="utf-8"))
58
+ return d if isinstance(d, dict) else {}
59
+ except (OSError, ValueError):
60
+ return {}
61
+
62
+
63
+ def _save_state(st: dict) -> None:
64
+ try:
65
+ core.atomic_json(_state_path(), st)
66
+ except (OSError, ValueError):
67
+ pass
68
+
69
+
70
+ def _cfg() -> dict:
71
+ try:
72
+ return core.load_config()
73
+ except Exception: # noqa: BLE001
74
+ return {}
75
+
76
+
77
+ def prob() -> float:
78
+ """触发概率(0~1)。坏配置回落默认值。"""
79
+ try:
80
+ v = float(_cfg().get("speak_up_prob", DEFAULT_PROB))
81
+ except (TypeError, ValueError):
82
+ return DEFAULT_PROB
83
+ return max(0.0, min(1.0, v))
84
+
85
+
86
+ def cooldown_sec() -> float:
87
+ try:
88
+ v = float(_cfg().get("speak_up_cooldown_min", DEFAULT_COOLDOWN_MIN))
89
+ except (TypeError, ValueError):
90
+ v = DEFAULT_COOLDOWN_MIN
91
+ return max(0.0, v) * 60.0
92
+
93
+
94
+ def is_question(text: str) -> bool:
95
+ """这一轮用户是不是在提问/请求(那就别主动搭话,先回答)。"""
96
+ return bool(_QUESTION_RE.search(str(text or "")))
97
+
98
+
99
+ def _good_topic(w: str) -> bool:
100
+ """一个候选是否适合当话题词(人/物/概念,而不是代词+动词碎片)。"""
101
+ w = str(w or "").strip().lstrip("#")
102
+ if not (2 <= len(w) <= 12):
103
+ return False
104
+ if w in _STOP:
105
+ return False
106
+ # 含任何虚词/代词字符就不是话题词("你可以用" 这类就是被这条挡掉的)
107
+ if any(ch in w for ch in _STOP_SUB):
108
+ return False
109
+ # 至少一半得是汉字/字母/数字,排除纯符号
110
+ core_chars = [c for c in w if c.isalnum()]
111
+ if len(core_chars) < 2 or len(core_chars) < len(w) / 2:
112
+ return False
113
+ return True
114
+
115
+
116
+ def _topic_from_recent() -> str:
117
+ """从最近记忆的**实体/标签**里抽一个话题词;抽不到返回 ""(宁可不说)。"""
118
+ try:
119
+ rows = brain.recent(12) or []
120
+ except Exception: # noqa: BLE001
121
+ return ""
122
+ cands = []
123
+ for m in rows:
124
+ for w in (m.get("entities") or []):
125
+ if _good_topic(w):
126
+ cands.append(str(w).strip().lstrip("#"))
127
+ for w in (m.get("tags") or []):
128
+ if _good_topic(w):
129
+ cands.append(str(w).strip().lstrip("#"))
130
+ if not cands:
131
+ return ""
132
+ # 去重后从"较新"的候选里挑,避免老话题反复出现
133
+ uniq = list(dict.fromkeys(cands))
134
+ return uniq[-1] if len(uniq) == 1 else random.choice(uniq[-6:])
135
+
136
+
137
+ def maybe(last_user_text: str = "", force: bool = False,
138
+ rng: random.Random | None = None, now: float | None = None) -> dict:
139
+ """决定是否主动搭话。返回 {triggered, text, reason}。
140
+
141
+ `force=True` 跳过概率与冷却(调试/验收用),但仍守"不是提问"这条。
142
+ """
143
+ now = time.time() if now is None else now
144
+ rng = rng or random
145
+
146
+ p = prob()
147
+ if p <= 0 and not force:
148
+ return {"triggered": False, "reason": "speak_up_prob=0(已关闭)"}
149
+ if last_user_text and is_question(last_user_text):
150
+ return {"triggered": False, "reason": "这一轮是提问,先回答"}
151
+ try:
152
+ import emotion
153
+ eff = float((emotion.rationality() or {}).get("effective") or 0)
154
+ except Exception: # noqa: BLE001
155
+ eff = 100.0
156
+ if not force and eff <= 30:
157
+ return {"triggered": False, "reason": f"情绪太激动(理智 {eff:.0f} ≤ 30)"}
158
+ st = _load_state()
159
+ last = float(st.get("last_at") or 0)
160
+ cd = cooldown_sec()
161
+ if not force and now - last < cd:
162
+ left = int((cd - (now - last)) / 60) + 1
163
+ return {"triggered": False, "reason": f"冷却中(还需 {left} 分钟)"}
164
+ if not force and rng.random() >= p:
165
+ return {"triggered": False, "reason": f"掷骰子未中(p={p:.2f})"}
166
+
167
+ kw = _topic_from_recent()
168
+ if not kw:
169
+ return {"triggered": False, "reason": "没有可用的主题词(库太新/太干净)"}
170
+ text = rng.choice(TEMPLATES).format(kw=kw)
171
+ st["last_at"] = now
172
+ st["last_text"] = text
173
+ st["count"] = int(st.get("count") or 0) + 1
174
+ _save_state(st)
175
+ # 留痕:doctor / 面板日志能看到"它什么时候自己开过口"
176
+ try:
177
+ import failures
178
+ failures.record("speak_up.triggered", text[:120], level="info")
179
+ except Exception: # noqa: BLE001
180
+ pass
181
+ try:
182
+ brain.log_event("speak_up", f"主动搭话:{text[:80]}")
183
+ except Exception: # noqa: BLE001
184
+ pass
185
+ return {"triggered": True, "text": text, "topic": kw,
186
+ "count": st["count"], "prob": p}
package/scripts/cli.py CHANGED
@@ -1589,6 +1589,19 @@ def _main(argv=None) -> int:
1589
1589
  p_tr.add_argument("--json", action="store_true")
1590
1590
 
1591
1591
  # P11 #76 桌面快捷方式「灵枢面板」
1592
+ p_stage = sub.add_parser("stage", help="灵枢成长阶段(P2-4):蛋/幼体/少年/成年/传奇")
1593
+ p_stage.add_argument("--json", action="store_true")
1594
+
1595
+ p_su = sub.add_parser(
1596
+ "speak-up",
1597
+ help="主动搭话(P1-3):按概率决定灵枢要不要自己说一句(纯模板、不进模型)")
1598
+ p_su.add_argument("--statement", default="",
1599
+ help="这一轮用户的输入(用于判定是不是在提问;提问就不搭话)")
1600
+ p_su.add_argument("--statement-file", default="",
1601
+ help="从文件读这一轮用户输入(插件用:避免把文本拼进命令行)")
1602
+ p_su.add_argument("--force", action="store_true", help="跳过概率与冷却(验收/调试用)")
1603
+ p_su.add_argument("--json", action="store_true")
1604
+
1592
1605
  p_tc = sub.add_parser(
1593
1606
  "token-calib",
1594
1607
  help="水位估算标定(盈不足/双假设法):看样本与拟合值,并与插件写入值对账")
@@ -2627,6 +2640,46 @@ def _main(argv=None) -> int:
2627
2640
  print("没有删除任何东西;要清空请你自己动手。")
2628
2641
  return 0 if res["ok"] else 1
2629
2642
 
2643
+ if args.cmd == "stage":
2644
+ import growth as _g
2645
+ s = _g.stage_state()
2646
+ if args.json:
2647
+ print(json.dumps(s, ensure_ascii=False, indent=2))
2648
+ return 0
2649
+ print(f"灵枢健康度:{s['label']}")
2650
+ print(f" 自审 {s['self_reviews']} 次 · 标签/实体覆盖 {s['coverage'] * 100:.0f}%"
2651
+ f" · 漂移修复过《{'是' if s['drift_fixed'] else '否'}》".replace("《", "").replace("》", ""))
2652
+ if s["next"]:
2653
+ print(" 下一步:" + ";".join(s["next"]))
2654
+ return 0
2655
+
2656
+ if args.cmd == "speak-up":
2657
+ import speak_up as _su
2658
+ _stmt = getattr(args, "statement", "") or ""
2659
+ _sf = getattr(args, "statement_file", "") or ""
2660
+ if _sf:
2661
+ try:
2662
+ _stmt = Path(_sf).read_text(encoding="utf-8", errors="replace")
2663
+ except OSError as exc:
2664
+ print(f"[错误] 读不了 --statement-file:{exc}", file=sys.stderr)
2665
+ return 1
2666
+ finally:
2667
+ # 临时文件用完即删(插件创建的,不该留在磁盘上)
2668
+ try:
2669
+ Path(_sf).unlink()
2670
+ except OSError:
2671
+ pass
2672
+ r = _su.maybe(_stmt,
2673
+ force=bool(getattr(args, "force", False)))
2674
+ if args.json:
2675
+ print(json.dumps(r, ensure_ascii=False))
2676
+ return 0
2677
+ if r.get("triggered"):
2678
+ print(r["text"])
2679
+ return 0
2680
+ print(f"(不搭话:{r.get('reason')})")
2681
+ return 0
2682
+
2630
2683
  if args.cmd == "token-calib":
2631
2684
  import token_calib as _tcal
2632
2685
  rep = _tcal.refit(write=args.refit)
@@ -4394,6 +4447,13 @@ def _main(argv=None) -> int:
4394
4447
 
4395
4448
  fails = sum(1 for _, s, _ in checks if s == "FAIL")
4396
4449
  warns = sum(1 for _, s, _ in checks if s == "WARN")
4450
+ # P2-4:每次体检追加一条历史(成长阶段的"doctor 次数"就来自这里)
4451
+ try:
4452
+ import growth as _g_stage
4453
+ _g_stage.record_doctor_run(len(checks) - fails - warns, warns, fails,
4454
+ kind="doctor")
4455
+ except Exception: # noqa: BLE001
4456
+ pass
4397
4457
  if args.json:
4398
4458
  print(json.dumps({"checks": [{"name": n, "status": s, "detail": dt} for n, s, dt in checks],
4399
4459
  "summary": {"pass": len(checks) - fails - warns,
package/scripts/core.py CHANGED
@@ -347,6 +347,18 @@ DEFAULT_CONFIG = {
347
347
  "use_index_memory": "auto",
348
348
  # P1-4 Git 分支感知:remember 记下当前分支,召回时跨分支分数 ×0.5(不硬过滤)
349
349
  "git_branch_memory": True,
350
+ # —— 情绪惯性(拟人化):让情绪"上来快、下去慢",不因单句话横跳 ——
351
+ "emotion_inertia_enabled": True, # 总开关;关掉则下面三项全部失效
352
+ "emotion_negative_slow": True, # 负面情绪衰减更慢("坏事记得久")
353
+ "emotion_negative_decay_factor": 0.8, # 负面衰减速率 = 0.8 倍 → 半衰期 ×1.25
354
+ "emotion_cooldown_enabled": True, # 强情绪后同组增益减半,防"越说越气"
355
+ "emotion_cooldown_events": 3, # 冷却窗口 = 之后 N 个情绪事件
356
+ "emotion_label_gate_enabled": True, # 标签要 ≥2 条情绪事件支撑才切换
357
+ "emotion_transition_threshold": 0.25, # 且 |Δvalence| 至少这么大
358
+ # P1-3 主动搭话:每轮结束按概率决定灵枢要不要自己说一句(纯模板、不进模型)。
359
+ # 0 = 关闭;还会受"不是提问 / 理智 >30 / 冷却 15 分钟"三道闸约束。
360
+ "speak_up_prob": 0.10,
361
+ "speak_up_cooldown_min": 15,
350
362
  "auto_update_interval_hours": 24,
351
363
  "session_state_cache": False,
352
364
  "session_state_ttl": 300,
@@ -1633,7 +1645,29 @@ def _locked(path: Path, timeout: float = 10.0):
1633
1645
  acquired = True
1634
1646
  break
1635
1647
  except FileExistsError:
1636
- # 陈旧锁(持锁进程已死):久到不可能是正常写盘(正常持锁 <2s)才接管。
1648
+ # ① 孤儿锁快通道:锁里写的是**本进程 pid**,但本进程没有持有它
1649
+ # (_held() 已为 False 才会走到这里)→ 这是我们自己遗留的锁,立刻接管。
1650
+ # 否则会等满 timeout 才失败,实测能把同进程的 remember 循环卡死。
1651
+ try:
1652
+ _owner = _lock_owner(lock)
1653
+ _age = time.time() - lock.stat().st_mtime
1654
+ # 通道 A:本进程遗留的孤儿锁(含"空锁文件"——O_CREAT 与写 pid
1655
+ # 之间有窗口,活着的进程不会把锁空着超过宽限期)。
1656
+ _owner_self = (_owner == os.getpid()) or (_owner is None)
1657
+ # 通道 B:**持锁进程已死**。与时间无关(只要过了宽限),
1658
+ # 否则会撞上"STALE_LOCK_SECONDS(30) > timeout(10)"的死角:
1659
+ # 一次崩溃留下的锁会让后续写入连续超时,永远等不到 30 秒。
1660
+ _owner_dead = (_owner is not None and _owner != os.getpid()
1661
+ and not _pid_alive(_owner))
1662
+ if _age > ORPHAN_LOCK_GRACE and (_owner_self or _owner_dead):
1663
+ try:
1664
+ lock.unlink()
1665
+ except OSError:
1666
+ pass
1667
+ continue
1668
+ except OSError:
1669
+ pass
1670
+ # ② 陈旧锁(持锁进程已死):久到不可能是正常写盘(正常持锁 <2s)才接管。
1637
1671
  # 阈值别设太小:dream 整理记忆时持锁会久一点,抢早了就是两个进程同时写。
1638
1672
  try:
1639
1673
  if time.time() - lock.stat().st_mtime > STALE_LOCK_SECONDS:
@@ -1671,17 +1705,24 @@ def _locked(path: Path, timeout: float = 10.0):
1671
1705
  if _lock_owner(lock) == os.getpid():
1672
1706
  _owns = True # 锁文件里确实记着自己是持有者
1673
1707
  if _owns:
1674
- try:
1675
- lock.unlink()
1676
- except FileNotFoundError:
1677
- pass # 锁文件刚被别的流程删掉:无需处理
1678
- except OSError:
1679
- pass
1708
+ # 重试几次:Windows 上偶发共享冲突会让 unlink 抛 OSError。
1709
+ # 删不掉就等于留下孤儿锁,而 _HELD_LOCKS 已清 → 下次自己写会 10 秒超时。
1710
+ for _attempt in range(5):
1711
+ try:
1712
+ lock.unlink()
1713
+ break
1714
+ except FileNotFoundError:
1715
+ break # 刚被别的流程删掉:无需处理
1716
+ except OSError:
1717
+ time.sleep(0.02 * (_attempt + 1))
1680
1718
  else:
1681
1719
  log_event("lock", f"释放跳过:锁 {path.name} 不归本进程(pid 不符或读不到持有者)", path=path.name)
1682
1720
 
1683
1721
 
1684
1722
  STALE_LOCK_SECONDS = 30.0
1723
+ # 孤儿锁宽限:锁文件写着本进程 pid 却不持有它时,等这么久才接管——
1724
+ # 给"刚创建、还没登记"的瞬间留窗口,又不至于让自锁死拖满 timeout。
1725
+ ORPHAN_LOCK_GRACE = 1.0
1685
1726
 
1686
1727
 
1687
1728
  def _pid_alive(pid: int) -> bool:
@@ -1696,7 +1737,12 @@ def _pid_alive(pid: int) -> bool:
1696
1737
  kernel32 = ctypes.windll.kernel32
1697
1738
  h = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
1698
1739
  if not h:
1699
- # 打不开句柄(权限拒绝/跨会话):保守视为存活,避免误判陈旧锁抢走别人的锁
1740
+ # 关键区分:**进程不存在**(ERROR_INVALID_PARAMETER=87)必须判死,
1741
+ # 否则崩溃留下的锁永远不算陈旧,后续写入会连续超时。
1742
+ # 只有"权限不足/跨会话"(ERROR_ACCESS_DENIED=5 等)才保守判活。
1743
+ err = kernel32.GetLastError()
1744
+ if err == 87: # ERROR_INVALID_PARAMETER:没有这个进程
1745
+ return False
1700
1746
  return True
1701
1747
  code = ctypes.c_ulong()
1702
1748
  ok = kernel32.GetExitCodeProcess(h, ctypes.byref(code))