lingshu-skill 5.18.0 → 5.20.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.
@@ -197,6 +197,42 @@ def _backup_drill(zip_path: Path, password: str | None) -> bool:
197
197
  return False
198
198
 
199
199
 
200
+ def _cleanup_own_tempfile(path: str, enabled: bool) -> None:
201
+ """只删**我们自己创建的**临时文件;其它一律保留(规矩:只移不删)。
202
+
203
+ 判据全部满足才删:
204
+ · enabled(调用方显式要求清理,插件会传;CLI 手工调用默认不传)
205
+ · 文件名带我们自己的前缀 lingshu-(prior/extract/speak-up 的临时文件都这么命名)
206
+ · 位于系统临时目录或调用方给的目录下
207
+ 否则只提示"已保留",绝不静默删除用户的文件。
208
+ """
209
+ import tempfile as _tf
210
+ from pathlib import Path as _Path
211
+ if not path:
212
+ return
213
+ try:
214
+ p_ = _Path(path).expanduser()
215
+ if not p_.is_file():
216
+ return
217
+ name = p_.name
218
+ if not name.startswith("lingshu-"):
219
+ if enabled:
220
+ print(f"[提示] 已保留 {p_}(不是灵枢创建的临时文件,不删除)",
221
+ file=sys.stderr)
222
+ return
223
+ try:
224
+ in_tmp = p_.resolve().parent == _Path(_tf.gettempdir()).resolve()
225
+ except OSError:
226
+ in_tmp = False
227
+ if not in_tmp:
228
+ if enabled:
229
+ print(f"[提示] 已保留 {p_}(不在系统临时目录,不删除)", file=sys.stderr)
230
+ return
231
+ p_.unlink(missing_ok=True)
232
+ except OSError:
233
+ pass
234
+
235
+
200
236
  def cmd_backup(target: str | None = None, keep: int = 20, password: str | None = None,
201
237
  assume_yes: bool = False) -> int:
202
238
  """把整个记忆库打成 zip。保留最近 keep 份,旧的自动修剪。
@@ -1517,6 +1553,8 @@ def _main(argv=None) -> int:
1517
1553
  p_prior.add_argument("--json", action="store_true")
1518
1554
  p_prior.add_argument("--render", action="store_true",
1519
1555
  help="只输出可直接注入的紧凑文本(插件用)")
1556
+ p_prior.add_argument("--cleanup", action="store_true",
1557
+ help="用完删除 --task-file(仅删自家 lingshu-* 临时文件;默认不删)")
1520
1558
 
1521
1559
  p_deref = sub.add_parser("deref", help="按需解引用:取一条记忆的证据原文(#46 Memex)")
1522
1560
  p_deref.add_argument("memory_id", help="记忆 id(通常是合并/蒸馏产物的 id)")
@@ -1589,6 +1627,12 @@ def _main(argv=None) -> int:
1589
1627
  p_tr.add_argument("--json", action="store_true")
1590
1628
 
1591
1629
  # P11 #76 桌面快捷方式「灵枢面板」
1630
+ p_sk_evo = sub.add_parser(
1631
+ "skill-evolve", help="技能自我进化(P2-2):把记忆里的踩坑经验回灌到技能旁的贴士文件")
1632
+ p_sk_evo.add_argument("--days", type=int, default=7)
1633
+ p_sk_evo.add_argument("--dry-run", action="store_true")
1634
+ p_sk_evo.add_argument("--json", action="store_true")
1635
+
1592
1636
  p_stage = sub.add_parser("stage", help="灵枢成长阶段(P2-4):蛋/幼体/少年/成年/传奇")
1593
1637
  p_stage.add_argument("--json", action="store_true")
1594
1638
 
@@ -1921,6 +1965,8 @@ def _main(argv=None) -> int:
1921
1965
  p_ext.add_argument("--tag", default="即记", help="自动封存的标签")
1922
1966
  p_ext.add_argument("--min-chars", type=int, default=80,
1923
1967
  help="惊异门控下限:文本短于该值视为无新信息,直接跳过")
1968
+ p_ext.add_argument("--cleanup", action="store_true",
1969
+ help="用完删除 --file(仅删自家 lingshu-* 临时文件;默认不删)")
1924
1970
 
1925
1971
  p_serve = sub.add_parser("serve", help="启动可视化面板")
1926
1972
  p_serve.add_argument("--port", type=int, default=None)
@@ -2298,7 +2344,8 @@ def _main(argv=None) -> int:
2298
2344
  fp = Path(args.file).expanduser()
2299
2345
  text = fp.read_text(encoding="utf-8", errors="replace").strip() if fp.exists() else ""
2300
2346
  try:
2301
- fp.unlink(missing_ok=True) # 用完即删,临时文件不留痕
2347
+ # 只删自家临时文件:调用方传进来的真实文件绝不删(规矩:只移不删)
2348
+ _cleanup_own_tempfile(str(fp), bool(getattr(args, "cleanup", False)))
2302
2349
  except Exception:
2303
2350
  pass
2304
2351
  if len(text) < args.min_chars:
@@ -2311,7 +2358,26 @@ def _main(argv=None) -> int:
2311
2358
  # 整段兜住:心情没记住是小事,对话没封存才是大事。
2312
2359
  try:
2313
2360
  from emotion import auto_appraise
2314
- auto_appraise(text)
2361
+ # 契约:返回 {emotion, intensity, polarity, hits};不写时返回 None
2362
+ # (门槛:≥80 字、≥2 个命中词、正负混说不猜)。**不含 valence**。
2363
+ ev = auto_appraise(text)
2364
+ # P2-3 情绪驱动的记忆权重:判出**负面**时给刚封存那批记忆加权
2365
+ # ("记仇"效应)。valence 用常量 -0.6 明确越过负面阈值;
2366
+ # 正面/中性一律不碰。
2367
+ try:
2368
+ if (isinstance(ev, dict)
2369
+ and ev.get("polarity") == "negative"
2370
+ and core.load_config().get("emotion_memory_weight", True)):
2371
+ _i = float(ev.get("intensity") or 0)
2372
+ import memory as _mem_mod
2373
+ # capture() 的 saved 是**记录列表**(不是 id 列表),显式取 id
2374
+ for _it in (res.get("saved") or [])[:20]:
2375
+ _mid = _it.get("id") if isinstance(_it, dict) else _it
2376
+ if _mid:
2377
+ _mem_mod.touch_by_emotion(_mid, -0.6, _i)
2378
+ except Exception as exc: # noqa: BLE001
2379
+ log_event("emotion-auto", f"情绪加权失败(封存已成功,可忽略):{exc}",
2380
+ level="warn")
2315
2381
  except Exception as exc:
2316
2382
  log_event("emotion-auto", f"extract 情绪评价失败(封存已成功,可忽略):{exc}",
2317
2383
  level="warn")
@@ -2337,7 +2403,8 @@ def _main(argv=None) -> int:
2337
2403
  return 1
2338
2404
  finally:
2339
2405
  try:
2340
- _P(_tf).unlink(missing_ok=True) # 用完即删,别留临时文件
2406
+ # 只删自家临时文件;读取失败也**不删**调用方给的路径
2407
+ _cleanup_own_tempfile(_tf, bool(getattr(args, "cleanup", False)))
2341
2408
  except OSError:
2342
2409
  pass
2343
2410
  if not task:
@@ -2640,6 +2707,26 @@ def _main(argv=None) -> int:
2640
2707
  print("没有删除任何东西;要清空请你自己动手。")
2641
2708
  return 0 if res["ok"] else 1
2642
2709
 
2710
+ if args.cmd == "skill-evolve":
2711
+ import growth as _g_evo
2712
+ r = _g_evo.skill_evolve(days=args.days, dry_run=args.dry_run)
2713
+ if args.json:
2714
+ print(json.dumps(r, ensure_ascii=False, indent=2))
2715
+ return 0 if r.get("ok") else 1
2716
+ if not r.get("ok"):
2717
+ print(f"[错误] {r.get('error')}", file=sys.stderr)
2718
+ return 1
2719
+ if not r["skills"]:
2720
+ print("没有标了 `skill:<名字>` 标签的记忆(至少 2 条才会生成贴士)。")
2721
+ return 0
2722
+ for s in r["skills"]:
2723
+ note = s.get("skipped") or f"贴士 {s['tips']} 条,新写入 {s['written']} 条"
2724
+ print(f" {s['name']}:{s['memories']} 条相关记忆 → {note}")
2725
+ if s.get("path"):
2726
+ print(f" {s['path']}")
2727
+ print(f"合计新写入 {r['total_written']} 条" + ("(dry-run,未落盘)" if args.dry_run else ""))
2728
+ return 0
2729
+
2643
2730
  if args.cmd == "stage":
2644
2731
  import growth as _g
2645
2732
  s = _g.stage_state()
@@ -2664,11 +2751,8 @@ def _main(argv=None) -> int:
2664
2751
  print(f"[错误] 读不了 --statement-file:{exc}", file=sys.stderr)
2665
2752
  return 1
2666
2753
  finally:
2667
- # 临时文件用完即删(插件创建的,不该留在磁盘上)
2668
- try:
2669
- Path(_sf).unlink()
2670
- except OSError:
2671
- pass
2754
+ # 临时文件用完即删——但只删**自家**创建的(lingshu- 前缀 + 在系统临时目录)
2755
+ _cleanup_own_tempfile(_sf, True)
2672
2756
  r = _su.maybe(_stmt,
2673
2757
  force=bool(getattr(args, "force", False)))
2674
2758
  if args.json:
@@ -4109,9 +4193,17 @@ def _main(argv=None) -> int:
4109
4193
  if not isinstance(days, dict) or not days:
4110
4194
  return ("runtime-liveness", "WARN", f"状态文件里没有 days:{state_p}")
4111
4195
 
4196
+ # 按**小时**驱动的任务(如 backup)有独立的 hours 标记,不能拿 days 判落后:
4197
+ # days 里那条是改造前的旧残留,会让自检每天报一次假警(实测 backup 停在
4198
+ # 11-23,而 hours 标记一直是最新的)。
4199
+ hours_markers = st.get("hours") if isinstance(st, dict) else None
4200
+ hour_driven = set(hours_markers) if isinstance(hours_markers, dict) else set()
4201
+
4112
4202
  today = _dt.date.today()
4113
4203
  lag: dict[str, int] = {}
4114
4204
  for task, last in days.items():
4205
+ if str(task) in hour_driven:
4206
+ continue # 小时驱动:交给 hours 判定,跳过 days
4115
4207
  try:
4116
4208
  lag[str(task)] = max(0, (today - _dt.date.fromisoformat(str(last)[:10])).days)
4117
4209
  except ValueError:
@@ -4163,6 +4255,25 @@ def _main(argv=None) -> int:
4163
4255
  return ("runtime-liveness", "WARN", ";".join(parts))
4164
4256
  return ("runtime-liveness", "PASS", ";".join(parts))
4165
4257
 
4258
+ def _doctor_skill_evolve() -> tuple:
4259
+ """P2-2:技能贴士文件是否存在(有经验被回灌过)。只读,无贴士不算错误。"""
4260
+ try:
4261
+ import growth as _g_se
4262
+ dirs = []
4263
+ try:
4264
+ for d in _g_se.SKILLS_DIR.iterdir():
4265
+ if (d / _g_se.TIPS_FILENAME).is_file():
4266
+ dirs.append(d.name)
4267
+ except OSError:
4268
+ return ("skill-evolve", "PASS", "技能库不可读(跳过)")
4269
+ if dirs:
4270
+ return ("skill-evolve", "PASS",
4271
+ f"{len(dirs)} 个技能已有贴士:{('、'.join(dirs[:3]))}")
4272
+ return ("skill-evolve", "PASS",
4273
+ "暂无贴士(记忆里还没有 ≥2 条同一 `skill:` 标签的经历)")
4274
+ except Exception as exc: # noqa: BLE001
4275
+ return ("skill-evolve", "WARN", f"检查失败:{exc}")
4276
+
4166
4277
  def _doctor_desktop_shortcut() -> tuple:
4167
4278
  """桌面「灵枢面板」快捷方式还在不在。
4168
4279
 
@@ -4423,6 +4534,12 @@ def _main(argv=None) -> int:
4423
4534
  except Exception as e:
4424
4535
  checks.append(("runtime-liveness", "WARN", f"自检失败:{e}"))
4425
4536
 
4537
+ # 13b. P2-2:技能贴士(自我进化的落点)
4538
+ try:
4539
+ checks.append(_doctor_skill_evolve())
4540
+ except Exception as e:
4541
+ checks.append(("skill-evolve", "WARN", f"自检失败:{e}"))
4542
+
4426
4543
  # 14. 桌面快捷方式是否还在(用户可能不小心删了)
4427
4544
  try:
4428
4545
  checks.append(_doctor_desktop_shortcut())
@@ -4468,6 +4585,14 @@ def _main(argv=None) -> int:
4468
4585
 
4469
4586
  if args.cmd == "lesson":
4470
4587
  # 一条命令三写:memory(kind=mistake) + knowledge(pending, source_ids) + note
4588
+ # 只读闸:这条路径**三处都要写盘**,必须先拦。原先只在 `remember` 那条有
4589
+ # CLI 级 guard,`lesson` 没有 → `--ro lesson` 退出码 0 且真的写进了库
4590
+ # (实测:--ro remember 被正确拒绝,--ro lesson 却成功)。
4591
+ if READONLY:
4592
+ print("[只读] 记忆库当前不可写,lesson 需要写盘"
4593
+ "(教训要同时写记忆/知识/笔记)。改用 --home 指向可写目录,"
4594
+ "或先解除写保护。", file=sys.stderr)
4595
+ return 1
4471
4596
  import growth
4472
4597
  text = " ".join(args.text)
4473
4598
  try:
@@ -355,6 +355,9 @@ DEFAULT_CONFIG = {
355
355
  "emotion_cooldown_events": 3, # 冷却窗口 = 之后 N 个情绪事件
356
356
  "emotion_label_gate_enabled": True, # 标签要 ≥2 条情绪事件支撑才切换
357
357
  "emotion_transition_threshold": 0.25, # 且 |Δvalence| 至少这么大
358
+ # P2-3 情绪驱动的记忆权重("记仇"):负面且有分量的情绪 → 相关记忆 importance +0.06,
359
+ # recall 时按影响均值给 importance 加成;累计增量封顶 0.30。
360
+ "emotion_memory_weight": True,
358
361
  # P1-3 主动搭话:每轮结束按概率决定灵枢要不要自己说一句(纯模板、不进模型)。
359
362
  # 0 = 关闭;还会受"不是提问 / 理智 >30 / 冷却 15 分钟"三道闸约束。
360
363
  "speak_up_prob": 0.10,
@@ -1373,6 +1376,19 @@ def _held(lock: Path) -> bool:
1373
1376
  return (str(lock), threading.get_ident()) in _HELD_LOCKS
1374
1377
 
1375
1378
 
1379
+ def _held_any_thread(lock: Path) -> bool:
1380
+ """本进程里**任意线程**是否正持有这把锁。
1381
+
1382
+ 区分"孤儿锁"与"活锁"必须用它:只比当前线程 id 的话,B 线程看不到 A 线程
1383
+ 正持有的锁,会把活锁当孤儿删掉 → 两线程同时读-改-写 → 静默丢数据。
1384
+ """
1385
+ key = str(lock)
1386
+ for path, _tid in list(_HELD_LOCKS):
1387
+ if path == key:
1388
+ return True
1389
+ return False
1390
+
1391
+
1376
1392
  # Windows 瞬时占用类错误:杀软/搜索索引器会在文件刚写完的瞬间短暂持有句柄,
1377
1393
  # 读操作被拒通常是瞬时的(短退避重试即过),不能当成"文件不存在"或直接放弃。
1378
1394
  # 5=拒绝访问 32=共享冲突 33=锁冲突 145=目录非空(清理/替换竞态时的表象)。
@@ -1645,21 +1661,45 @@ def _locked(path: Path, timeout: float = 10.0):
1645
1661
  acquired = True
1646
1662
  break
1647
1663
  except FileExistsError:
1664
+ # ★ 权威守卫(必须放在最前):本进程**任意线程**正持有这把锁 ⇒ 活锁。
1665
+ # 面板是 ThreadingHTTPServer,多线程写同一批 jsonl;若这里放行去抢,
1666
+ # 两个线程会同时读-改-写,后写者覆盖先写者 → 静默丢记忆。
1667
+ # 这条与下面各子路径无关,任何未来的改动都绕不过它。
1668
+ if _held_any_thread(lock):
1669
+ if time.time() > deadline:
1670
+ log_event("lock", f"等不到写锁:{path.name}({timeout:.0f}s 超时,"
1671
+ f"本进程另有线程持锁)", level="error", path=path.name)
1672
+ raise TimeoutError(f"等不到写锁:{path}")
1673
+ time.sleep(0.05)
1674
+ continue
1648
1675
  # ① 孤儿锁快通道:锁里写的是**本进程 pid**,但本进程没有持有它
1649
1676
  # (_held() 已为 False 才会走到这里)→ 这是我们自己遗留的锁,立刻接管。
1650
1677
  # 否则会等满 timeout 才失败,实测能把同进程的 remember 循环卡死。
1651
1678
  try:
1652
1679
  _owner = _lock_owner(lock)
1653
1680
  _age = time.time() - lock.stat().st_mtime
1654
- # 通道 A:本进程遗留的孤儿锁(含"空锁文件"——O_CREAT 与写 pid
1655
- # 之间有窗口,活着的进程不会把锁空着超过宽限期)。
1656
- _owner_self = (_owner == os.getpid()) or (_owner is None)
1681
+ # ⚠ 本进程的锁**绝不能只按 pid 判孤儿**:面板是 ThreadingHTTPServer,
1682
+ # 多个线程会写同一批 jsonl。A 线程持锁超过宽限期时(全量重写上万条、
1683
+ # _replace_retry 退避都可能 >1s),B 线程会读到 owner pid == 自己进程
1684
+ # 而误判"遗留孤儿锁",把 A 的活锁删掉 → 两线程同时读-改-写 → 静默丢记忆。
1685
+ # 正确判据是"**本线程是否真持有**"(_held 里有 (锁路径, 线程id))。
1686
+ _held_by_me = _held_any_thread(lock)
1687
+ _same_proc = (_owner == os.getpid())
1688
+ # 通道 A:空锁文件(O_CREAT 与写 pid 之间的窗口)。
1689
+ # 活着的进程不会把锁空着超过宽限期,所以可接管;
1690
+ # 但若本线程正持有(重入已在函数开头 return),这里不涉及。
1691
+ # 空锁文件:本进程没人持有它,且已过宽限期 → 是遗留孤儿,可接管。
1692
+ # 若本进程有线程正持有(刚 create、还没写 pid 的一瞬)→ 是活锁,别动。
1693
+ _orphan_empty = (_owner is None and not _held_by_me)
1657
1694
  # 通道 B:**持锁进程已死**。与时间无关(只要过了宽限),
1658
- # 否则会撞上"STALE_LOCK_SECONDS(30) > timeout(10)"的死角:
1659
- # 一次崩溃留下的锁会让后续写入连续超时,永远等不到 30 秒。
1660
- _owner_dead = (_owner is not None and _owner != os.getpid()
1695
+ # 否则会撞上"STALE_LOCK_SECONDS(30) > timeout(10)"的死角。
1696
+ _owner_dead = (_owner is not None and not _same_proc
1661
1697
  and not _pid_alive(_owner))
1662
- if _age > ORPHAN_LOCK_GRACE and (_owner_self or _owner_dead):
1698
+ # 本进程 + **没有线程持有** = 真孤儿(守卫已在上面排除"有线程持有"),
1699
+ # 可以安全接管:否则崩溃/异常后同进程后续写入会一直超时。
1700
+ _owner_self_orphan = _same_proc and not _held_by_me
1701
+ if _age > ORPHAN_LOCK_GRACE and (
1702
+ _orphan_empty or _owner_dead or _owner_self_orphan):
1663
1703
  try:
1664
1704
  lock.unlink()
1665
1705
  except OSError:
@@ -1910,14 +1950,19 @@ def _patch_memory_fields(rec: dict) -> bool:
1910
1950
  ARCHIVE_LAYER: "archive.jsonl"}
1911
1951
  for layer in ("hippo", "cortex", "dust", ARCHIVE_LAYER):
1912
1952
  p = HOME / fname[layer]
1913
- rows = read_jsonl(p)
1914
- for r in rows:
1915
- if r.get("id") == rec["id"]:
1916
- for f in patch_fields:
1917
- if f in rec:
1918
- r[f] = rec[f]
1919
- write_jsonl(p, rows)
1920
- return True
1953
+ # 必须进锁 + **锁内重读**:锁外 read_jsonl 拿到的是旧快照,
1954
+ # 期间若有并发删除(purge/forget/drop),回写会把那条记录**复活**
1955
+ # (实测让"删掉后恢复"的流程撞上"已经在库里"而失败)。
1956
+ with _locked(p):
1957
+ rows = read_jsonl(p)
1958
+ hit = next((r for r in rows if r.get("id") == rec["id"]), None)
1959
+ if hit is None:
1960
+ continue
1961
+ for f in patch_fields:
1962
+ if f in rec:
1963
+ hit[f] = rec[f]
1964
+ write_jsonl(p, rows)
1965
+ return True
1921
1966
  log_event("memory", f"放弃复核确认 {rec['id']}:各层都找不到", level="warn")
1922
1967
  return False
1923
1968
 
@@ -2111,6 +2156,28 @@ def _override_home(argv: list) -> list:
2111
2156
  _SYNC_TARGETS: list = []
2112
2157
 
2113
2158
 
2159
+ # 只同步"状态名"的目标模块(拆分出去的 mem_* 子模块)。
2160
+ # 为什么不整份同步:`_sync_state` 的全量 globals 覆盖会顶掉模块自己的私有 helper
2161
+ # ——实测把 `mem_dialogue._mem()`(惰性取 memory 模块的函数)顶成了 core 里同名的
2162
+ # `_mem` 模块,对话摄取因此每条都写失败('module' object is not callable)。
2163
+ _SYNC_STATE_ONLY: list = []
2164
+
2165
+ # 状态名白名单:派生路径/常量(全大写)+ 只读三兄弟。
2166
+ # 一条明确规则比"猜哪些名字重要"可靠:全大写 = 常量/路径,小写 = 函数或私有变量。
2167
+ _STATE_EXTRA_NAMES = ("READONLY", "READONLY_FORCED", "READONLY_REASON")
2168
+
2169
+
2170
+ def _state_snapshot() -> dict:
2171
+ """只挑"状态名"的快照(供 _SYNC_STATE_ONLY 用)。"""
2172
+ snap = {}
2173
+ for k, v in dict(globals()).items():
2174
+ if k.startswith("__"):
2175
+ continue
2176
+ if k.isupper() or k in _STATE_EXTRA_NAMES:
2177
+ snap[k] = v
2178
+ return snap
2179
+
2180
+
2114
2181
  def _sync_state() -> None:
2115
2182
  """把 core 的当前全局状态同步到各子模块(brain.py 启动时登记同步目标)。
2116
2183
 
@@ -2118,11 +2185,15 @@ def _sync_state() -> None:
2118
2185
  (测试/宿主/面板迁移都会这么用)也不会把旧目录的路径同步出去。
2119
2186
  """
2120
2187
  _rebind_paths()
2121
- if not _SYNC_TARGETS:
2122
- return
2123
2188
  snap = {k: v for k, v in dict(globals()).items() if not k.startswith("__")}
2124
- for m in _SYNC_TARGETS:
2125
- m.__dict__.update(snap)
2189
+ if _SYNC_TARGETS:
2190
+ for m in _SYNC_TARGETS:
2191
+ m.__dict__.update(snap)
2192
+ # mem_* 拆分模块:只同步状态名,绝不碰它们的私有 helper/函数
2193
+ if _SYNC_STATE_ONLY:
2194
+ narrow = _state_snapshot()
2195
+ for m in _SYNC_STATE_ONLY:
2196
+ m.__dict__.update(narrow)
2126
2197
  # growth.py 不在 _SYNC_TARGETS(它在 brain 之后 import brain,会形成循环导入),
2127
2198
  # 但它缓存了 HOME 与一批派生路径常量;这里 import 一次并调用它的重算入口,
2128
2199
  # 让 --home 切换后 growth 的 knowledge/notes/skills 等路径也指向新目录
@@ -3077,6 +3077,145 @@ def check_skill(name: str | None = None) -> list:
3077
3077
  # 用户要求"每隔 2-3 天就总结下自己的灵枢技能":这里生成一份自省素材,
3078
3078
  # 由 AI 写进成长笔记,并把 last_self_review 记到 config,注入包据此提醒。
3079
3079
 
3080
+ # ---------------------------------------------------------------- 技能自我进化(P2-2)
3081
+
3082
+ TIPS_FILENAME = ".lingshu-tips.md"
3083
+ SKILL_TAG_PREFIXES = ("skill:", "skill/")
3084
+ TIPS_MIN_MEMORIES = 2 # 同一技能至少几条相关记忆才成"经验"
3085
+ TIPS_MAX_CHARS = 150 # 单条贴士正文上限
3086
+
3087
+
3088
+ def _skill_tags_of(m: dict) -> list:
3089
+ """一条记忆里标了哪些 skill(`skill:name` / `skill/name` 两种写法都认)。"""
3090
+ out = []
3091
+ for raw in (m.get("tags") or []):
3092
+ s = str(raw).strip()
3093
+ for pref in SKILL_TAG_PREFIXES:
3094
+ if s.lower().startswith(pref):
3095
+ name = s[len(pref):].strip()
3096
+ if name:
3097
+ out.append(name)
3098
+ return out
3099
+
3100
+
3101
+ def _skill_dir_of(name: str) -> Path | None:
3102
+ """已安装的技能目录;不存在返回 None(绝不新建)。"""
3103
+ try:
3104
+ d = SKILLS_DIR / str(name)
3105
+ if (d / "SKILL.md").is_file():
3106
+ return d
3107
+ except OSError:
3108
+ pass
3109
+ return None
3110
+
3111
+
3112
+ def _tip_line(m: dict) -> str:
3113
+ """把一条相关记忆压成一句"可能踩的坑"(引用索引原文,不自己编)。"""
3114
+ idx = str(m.get("index") or "").strip()
3115
+ if not idx:
3116
+ try:
3117
+ idx = _make_gist(str(m.get("text") or ""))
3118
+ except Exception: # noqa: BLE001
3119
+ idx = str(m.get("text") or "")[:40]
3120
+ kind = str(m.get("kind") or "")
3121
+ tag = {"mistake": "踩过的坑", "correction": "被纠正过", "emotion": "情绪高点"}.get(kind, "相关记录")
3122
+ line = f"{tag}:{idx}"
3123
+ return line[:TIPS_MAX_CHARS]
3124
+
3125
+
3126
+ def _make_gist(text: str, limit: int = 40) -> str:
3127
+ """极简取首句(growth 侧没有 memory 的 _make_index,这里就地实现一份)。"""
3128
+ s = " ".join(str(text or "").split())
3129
+ for ch in "。!?!?\n;;,,":
3130
+ i = s.find(ch)
3131
+ if 0 < i <= limit:
3132
+ return s[:i]
3133
+ return s[:limit]
3134
+
3135
+
3136
+ def _tips_append(skill_dir: Path, lines: list, stamp: str) -> int:
3137
+ """追加贴士,按正文 sha256 去重。返回新写入条数。"""
3138
+ path = skill_dir / TIPS_FILENAME
3139
+ existing = ""
3140
+ if path.is_file():
3141
+ try:
3142
+ existing = path.read_text(encoding="utf-8", errors="replace")
3143
+ except OSError:
3144
+ existing = ""
3145
+ seen = set()
3146
+ for ln in existing.splitlines():
3147
+ ln = ln.strip()
3148
+ if ln.startswith("- "):
3149
+ seen.add(hashlib.sha256(ln[2:].strip().encode("utf-8")).hexdigest()[:12])
3150
+ fresh = []
3151
+ for ln in lines:
3152
+ key = hashlib.sha256(ln.strip().encode("utf-8")).hexdigest()[:12]
3153
+ if key in seen:
3154
+ continue
3155
+ seen.add(key)
3156
+ fresh.append(ln)
3157
+ if not fresh:
3158
+ return 0
3159
+ try:
3160
+ if not existing:
3161
+ head = ("# 灵枢给这个技能的贴士(自动追加,保留历史)\n\n"
3162
+ "> 来源:记忆里标了 `skill:` 标签的真实经历。只引用索引原文,不臆造。\n")
3163
+ path.write_text(head, encoding="utf-8", newline="\n")
3164
+ with open(path, "a", encoding="utf-8", newline="\n") as f:
3165
+ f.write(f"\n## {stamp}\n")
3166
+ for ln in fresh:
3167
+ f.write(f"- {ln}\n")
3168
+ except OSError:
3169
+ return 0
3170
+ return len(fresh)
3171
+
3172
+
3173
+ def skill_evolve(days: int = 7, dry_run: bool = False) -> dict:
3174
+ """扫描最近记忆里的 `skill:` 标记,给对应技能追加贴士(P2-2)。
3175
+
3176
+ 返回 {ok, skills: [{name, memories, tips, written, path}], total_written}。
3177
+ 任何异常都不抛出:这是锦上添花的能力,不该让 self-review 挂掉。
3178
+ """
3179
+ try:
3180
+ import memory as _mem
3181
+ rows = [m for m in _mem.load_all() if isinstance(m, dict) and m.get("id")]
3182
+ except Exception as exc: # noqa: BLE001
3183
+ return {"ok": False, "error": f"读记忆失败:{exc}", "skills": [],
3184
+ "total_written": 0}
3185
+ cutoff = brain.now_ts() - max(1, int(days)) * brain.DAY
3186
+ by_skill: dict[str, list] = {}
3187
+ for m in rows:
3188
+ try:
3189
+ if int(m.get("created") or 0) < cutoff:
3190
+ continue
3191
+ except (TypeError, ValueError):
3192
+ continue
3193
+ for name in _skill_tags_of(m):
3194
+ by_skill.setdefault(name, []).append(m)
3195
+
3196
+ stamp = time.strftime("%Y-%m-%d")
3197
+ out, total = [], 0
3198
+ for name, mems in sorted(by_skill.items()):
3199
+ if len(mems) < TIPS_MIN_MEMORIES:
3200
+ continue
3201
+ d = _skill_dir_of(name)
3202
+ if d is None:
3203
+ out.append({"name": name, "memories": len(mems), "tips": 0,
3204
+ "written": 0, "path": "", "skipped": "技能目录不存在"})
3205
+ continue
3206
+ # 优先 mistake / correction(那才是"坑"),再补其它,最多 5 条
3207
+ ranked = sorted(mems, key=lambda m: (0 if str(m.get("kind")) in ("mistake", "correction") else 1,
3208
+ -_num(m.get("importance"), 0.5)))
3209
+ lines = [_tip_line(m) for m in ranked[:5]]
3210
+ lines = [ln for ln in lines if ln]
3211
+ written = 0 if dry_run else _tips_append(d, lines, stamp)
3212
+ total += written
3213
+ out.append({"name": name, "memories": len(mems), "tips": len(lines),
3214
+ "written": written, "path": str(d / TIPS_FILENAME)})
3215
+ return {"ok": True, "skills": out, "total_written": total,
3216
+ "scanned": len(rows), "days": days, "dry_run": bool(dry_run)}
3217
+
3218
+
3080
3219
  def self_review(force: bool = False, days: int = 3) -> dict:
3081
3220
  cfg = brain.load_config()
3082
3221
  now = brain.now_ts()
@@ -3138,7 +3277,14 @@ def self_review(force: bool = False, days: int = 3) -> dict:
3138
3277
  saved = True
3139
3278
  except OSError:
3140
3279
  saved = False
3141
- return {"due": True, "last": last, "days": days, "summary": summary, "saved": saved}
3280
+ # P2-2 技能自我进化:把这一轮的"踩坑经验"回灌到对应技能旁边。
3281
+ # 整段兜住——回灌失败绝不能让自我总结挂掉。
3282
+ try:
3283
+ _evolve = skill_evolve(days=max(2, days))
3284
+ except Exception as _exc: # noqa: BLE001
3285
+ _evolve = {"ok": False, "error": str(_exc), "total_written": 0}
3286
+ return {
3287
+ "skill_evolve": _evolve,"due": True, "last": last, "days": days, "summary": summary, "saved": saved}
3142
3288
 
3143
3289
 
3144
3290
  def _readonly() -> bool: