lingshu-skill 4.1.0 → 4.2.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 +32 -1
- package/README.md +697 -697
- package/SKILL.md +380 -380
- package/assets/panel.html +1 -1
- package/cordis-plugin/lingshu-cron/plugin.js +1074 -1040
- package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +32 -1
- package/package.json +52 -52
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +11 -9
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +32 -1
- package/scripts/astrbot_plugin_lingshu/engine/README.md +697 -697
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +380 -380
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +131 -8
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +16 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/desktop_shortcut.py +136 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_data.py +75 -4
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_settings.py +23 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_update.py +81 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/release.py +10 -0
- package/scripts/cli.py +131 -8
- package/scripts/core.py +16 -0
- package/scripts/desktop_shortcut.py +136 -0
- package/scripts/panel_data.py +75 -4
- package/scripts/panel_settings.py +23 -0
- package/scripts/panel_update.py +81 -0
- package/scripts/release.py +10 -0
- package/scripts/run_tests.py +36 -0
|
@@ -2979,7 +2979,7 @@ async function renderData(force){
|
|
|
2979
2979
|
${it.suspicious ? '<span class="set-badge">疑似空壳</span>' : ""}
|
|
2980
2980
|
${it.has_sha ? "" : '<span class="set-badge">无校验</span>'}
|
|
2981
2981
|
</div>
|
|
2982
|
-
<div class="sub">${esc(it.mtime_text)} · ${_fmtSize(it.size)}</div>
|
|
2982
|
+
<div class="sub">${esc(it.mtime_text)} · ${_fmtSize(it.size)} · ${it.records != null ? it.records + " 条" : "记录数未知"} · ${it.age_hours != null ? it.age_hours + " 小时前" : ""}${it.suspicious_why ? " · " + esc(it.suspicious_why) : ""}</div>
|
|
2983
2983
|
</div>
|
|
2984
2984
|
<button class="ghost" data-restore="${esc(it.name)}" ${it.suspicious ? "disabled" : ""}>恢复</button>
|
|
2985
2985
|
</div>`).join("")}</div>`;
|
|
@@ -256,6 +256,39 @@ def cmd_backup(target: str | None = None, keep: int = 20, password: str | None =
|
|
|
256
256
|
continue
|
|
257
257
|
zf.write(f, rel)
|
|
258
258
|
n += 1
|
|
259
|
+
# 包内清单:把"这个包到底装了什么、有多少条"写进去,
|
|
260
|
+
# 事后(以及面板恢复前)不必解包就能判断它是不是空壳。
|
|
261
|
+
try:
|
|
262
|
+
import json as _json
|
|
263
|
+
_counts = {}
|
|
264
|
+
for _name in ("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl",
|
|
265
|
+
"archive.jsonl", "knowledge.jsonl", "notes.jsonl",
|
|
266
|
+
"emotions.jsonl"):
|
|
267
|
+
_f = HOME / _name
|
|
268
|
+
if _f.is_file():
|
|
269
|
+
try:
|
|
270
|
+
_counts[_name] = sum(
|
|
271
|
+
1 for _ln in _f.open(encoding="utf-8", errors="replace")
|
|
272
|
+
if _ln.strip())
|
|
273
|
+
except OSError:
|
|
274
|
+
_counts[_name] = -1
|
|
275
|
+
_ver = ""
|
|
276
|
+
try:
|
|
277
|
+
for _ln in (HOME / "VERSION").read_text(encoding="utf-8").splitlines():
|
|
278
|
+
_ver = _ln.strip()
|
|
279
|
+
break
|
|
280
|
+
except OSError:
|
|
281
|
+
pass
|
|
282
|
+
zf.writestr("_backup_manifest.json", _json.dumps({
|
|
283
|
+
"created": datetime.now().isoformat(timespec="seconds"),
|
|
284
|
+
"files": n,
|
|
285
|
+
"counts": _counts,
|
|
286
|
+
"total_records": sum(v for v in _counts.values() if v > 0),
|
|
287
|
+
"version": _ver,
|
|
288
|
+
"home": str(HOME),
|
|
289
|
+
}, ensure_ascii=False, indent=2))
|
|
290
|
+
except Exception as exc: # noqa: BLE001
|
|
291
|
+
log_event("backup", f"包内清单写入失败(备份本身完好):{exc}", level="warn")
|
|
259
292
|
except Exception as exc:
|
|
260
293
|
print(f"[错误] 备份失败:{exc}", file=sys.stderr)
|
|
261
294
|
return 2
|
|
@@ -298,19 +331,56 @@ def cmd_backup(target: str | None = None, keep: int = 20, password: str | None =
|
|
|
298
331
|
print(f"[错误] 备份加密失败:{exc}", file=sys.stderr)
|
|
299
332
|
return 2
|
|
300
333
|
removed = 0
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
# 还会留下没有 zip 的孤儿 sha256(P10 #69)。
|
|
334
|
+
# 分层保留(GFS,P11 #72):小时内留最近 N 个、天内每天留 1 个、周内每周留 1 个,
|
|
335
|
+
# 再叠加显式 keep(兼容旧行为)。既避免"只留 5 个"丢掉整周历史,也不会无限膨胀。
|
|
336
|
+
# 只按**真备份文件**计数(P10 #69:glob 曾把 .sha256 也算进去)。
|
|
337
|
+
try:
|
|
306
338
|
existing = sorted(
|
|
307
339
|
[p for p in out_dir.glob("brain-memory_*.zip*")
|
|
308
340
|
if p.name.endswith(".zip") or p.name.endswith(".zip.enc")],
|
|
309
341
|
key=lambda p: p.stat().st_mtime, reverse=True)
|
|
310
|
-
|
|
342
|
+
except OSError:
|
|
343
|
+
existing = []
|
|
344
|
+
if existing:
|
|
345
|
+
try:
|
|
346
|
+
cfg = load_config()
|
|
347
|
+
except Exception:
|
|
348
|
+
cfg = {}
|
|
349
|
+
keep_h = int(cfg.get("backup_keep_hourly") or 0)
|
|
350
|
+
keep_d = int(cfg.get("backup_keep_daily") or 0)
|
|
351
|
+
keep_w = int(cfg.get("backup_keep_weekly") or 0)
|
|
352
|
+
drop: set = set()
|
|
353
|
+
if keep_h > 0:
|
|
354
|
+
drop.update(existing[keep_h:])
|
|
355
|
+
if keep_d > 0:
|
|
356
|
+
seen_days, kept_d = set(), 0
|
|
357
|
+
for p in existing:
|
|
358
|
+
day = datetime.fromtimestamp(p.stat().st_mtime).strftime("%Y%m%d")
|
|
359
|
+
if day in seen_days:
|
|
360
|
+
continue
|
|
361
|
+
seen_days.add(day)
|
|
362
|
+
kept_d += 1
|
|
363
|
+
if kept_d > keep_d:
|
|
364
|
+
drop.add(p)
|
|
365
|
+
if keep_w > 0:
|
|
366
|
+
seen_weeks, kept_w = set(), 0
|
|
367
|
+
for p in existing:
|
|
368
|
+
wk = datetime.fromtimestamp(p.stat().st_mtime).strftime("%G%V")
|
|
369
|
+
if wk in seen_weeks:
|
|
370
|
+
continue
|
|
371
|
+
seen_weeks.add(wk)
|
|
372
|
+
kept_w += 1
|
|
373
|
+
if kept_w > keep_w:
|
|
374
|
+
drop.add(p)
|
|
375
|
+
if keep and keep > 0:
|
|
376
|
+
drop.update(existing[keep:])
|
|
377
|
+
# 最新那份永不删(否则备份完立刻把自己删了)
|
|
378
|
+
drop.discard(existing[0])
|
|
379
|
+
for p in existing:
|
|
380
|
+
if p not in drop:
|
|
381
|
+
continue
|
|
311
382
|
try:
|
|
312
383
|
p.unlink()
|
|
313
|
-
# 连带清掉它的 sha256 边车,别留孤儿
|
|
314
384
|
side = p.with_name(p.name + ".sha256")
|
|
315
385
|
if side.is_file():
|
|
316
386
|
side.unlink()
|
|
@@ -331,7 +401,7 @@ def cmd_backup(target: str | None = None, keep: int = 20, password: str | None =
|
|
|
331
401
|
if not password:
|
|
332
402
|
print("[提示] 备份未加密,含全部记忆原文;加 --password 可生成加密备份。", file=sys.stderr)
|
|
333
403
|
if removed:
|
|
334
|
-
print(f"修剪旧备份 {removed}
|
|
404
|
+
print(f"修剪旧备份 {removed} 个(分层保留:小时/天/周;最新一份永不删)")
|
|
335
405
|
return 0
|
|
336
406
|
|
|
337
407
|
|
|
@@ -1488,6 +1558,18 @@ def _main(argv=None) -> int:
|
|
|
1488
1558
|
p_ck.add_argument("--force", action="store_true", help="即使和上次一致也写一条")
|
|
1489
1559
|
p_ck.add_argument("--json", action="store_true")
|
|
1490
1560
|
|
|
1561
|
+
# P11 #76 桌面快捷方式「灵枢面板」
|
|
1562
|
+
p_sc = sub.add_parser("shortcut", help="在桌面生成/删除「灵枢面板」快捷方式(静默启动面板)")
|
|
1563
|
+
p_sc.add_argument("--name", default="灵枢面板", help="快捷方式名字(默认 灵枢面板)")
|
|
1564
|
+
p_sc.add_argument("--port", type=int, default=0, help="固定端口(默认读 config.panel_port)")
|
|
1565
|
+
p_sc.add_argument("--remove", action="store_true", help="删除桌面快捷方式")
|
|
1566
|
+
|
|
1567
|
+
# P11 #75 自动更新灵枢
|
|
1568
|
+
p_au = sub.add_parser("auto-update", help="检查/执行自动更新灵枢(默认跟随 config.auto_update)")
|
|
1569
|
+
p_au.add_argument("--check", action="store_true", help="只检查有没有新版本,不安装")
|
|
1570
|
+
p_au.add_argument("--force", action="store_true", help="忽略 auto_update 开关强制执行一次")
|
|
1571
|
+
p_au.add_argument("--json", action="store_true")
|
|
1572
|
+
|
|
1491
1573
|
# 附录 C P2 收尾:触发 + 落盘 + 回滚
|
|
1492
1574
|
p_ss = sub.add_parser("session-summary",
|
|
1493
1575
|
help="会话摘要:触发判断 / 生成落盘 / 查看 / 回滚(每 N 轮或水位≥60%%)")
|
|
@@ -2012,6 +2094,8 @@ def _main(argv=None) -> int:
|
|
|
2012
2094
|
or (args.cmd == "rebuild-embeds") # 重建向量写回各层文件
|
|
2013
2095
|
or (args.cmd == "drift") # 漂移走 persona.json 写盘
|
|
2014
2096
|
or (args.cmd == "auto-archive" and not args.dry_run)
|
|
2097
|
+
or (args.cmd == "shortcut") # 写桌面 .lnk
|
|
2098
|
+
or (args.cmd == "auto-update" and not args.check) # 改自身代码
|
|
2015
2099
|
)
|
|
2016
2100
|
if writing:
|
|
2017
2101
|
print(f"[只读] 记忆库当前不可写,{args.cmd} 需要写盘。"
|
|
@@ -2457,6 +2541,45 @@ def _main(argv=None) -> int:
|
|
|
2457
2541
|
else f"OK {rep}")
|
|
2458
2542
|
return 0
|
|
2459
2543
|
|
|
2544
|
+
if args.cmd == "shortcut":
|
|
2545
|
+
import desktop_shortcut as _ds
|
|
2546
|
+
if args.remove:
|
|
2547
|
+
r = _ds.remove(args.name)
|
|
2548
|
+
print(f"已删除桌面快捷方式:{r.get('path')}" if r.get("removed")
|
|
2549
|
+
else "桌面没有该快捷方式(无需删除)")
|
|
2550
|
+
return 0 if r.get("ok") else 1
|
|
2551
|
+
r = _ds.create(args.name, args.port or None)
|
|
2552
|
+
if r.get("ok"):
|
|
2553
|
+
print(f"已在桌面创建「{args.name}」:{r['path']}")
|
|
2554
|
+
print(f" 启动器:{r['launcher']}")
|
|
2555
|
+
print(" 双击即可静默启动面板(不会弹黑窗)")
|
|
2556
|
+
return 0
|
|
2557
|
+
print(f"[错误] 创建失败:{r.get('reason')}", file=sys.stderr)
|
|
2558
|
+
return 1
|
|
2559
|
+
|
|
2560
|
+
if args.cmd == "auto-update":
|
|
2561
|
+
import panel_update as _pu
|
|
2562
|
+
if args.check:
|
|
2563
|
+
res = _pu.check(force_pull=True)
|
|
2564
|
+
if args.json:
|
|
2565
|
+
print(json.dumps(res, ensure_ascii=False, indent=2))
|
|
2566
|
+
return 0
|
|
2567
|
+
print(f"当前 {res.get('current')} / 最新 {res.get('latest')} "
|
|
2568
|
+
f"→ {'有新版可更新' if res.get('update_available') else '已是最新'}")
|
|
2569
|
+
return 0
|
|
2570
|
+
res = _pu.run(force=args.force)
|
|
2571
|
+
if args.json:
|
|
2572
|
+
print(json.dumps(res, ensure_ascii=False, indent=2))
|
|
2573
|
+
return 0 if res.get("ok") else 1
|
|
2574
|
+
if res.get("skipped"):
|
|
2575
|
+
print(f"跳过:{res.get('reason')}")
|
|
2576
|
+
return 0
|
|
2577
|
+
if res.get("ok"):
|
|
2578
|
+
print(f"已更新:{res.get('from')} → {res.get('to')};更新前备份 {res.get('backup')}")
|
|
2579
|
+
return 0
|
|
2580
|
+
print(f"[错误] {res.get('reason')}", file=sys.stderr)
|
|
2581
|
+
return 1
|
|
2582
|
+
|
|
2460
2583
|
if args.cmd == "checkpoint":
|
|
2461
2584
|
from checkpoint import checkpoint
|
|
2462
2585
|
rep = checkpoint(args.repo or None, args.note,
|
|
@@ -316,6 +316,22 @@ DEFAULT_CONFIG = {
|
|
|
316
316
|
# 补进 DEFAULT_CONFIG:原来只有读取方 .get(key, False) 兜底,config 里没有这个键,
|
|
317
317
|
# 面板设置页会显示成"未设置"、默认值也拿不到(P10 #68)。
|
|
318
318
|
"extensions_enabled": False,
|
|
319
|
+
# —— 备份策略(P11 #72)——
|
|
320
|
+
# 按小时驱动而不是按天:原来 days=1 只在"当天第一次回合"跑一次,
|
|
321
|
+
# 之后十几小时的写入完全裸奔(实测缺 17%)。
|
|
322
|
+
"backup_interval_hours": 6,
|
|
323
|
+
# 变更量驱动:新增记录达到这个数就补一次备份(高频写入时不必等满 6 小时)
|
|
324
|
+
"backup_min_new_records": 50,
|
|
325
|
+
# 保留分层:小时内 / 天内 / 周内各留几份(GFS 思路,省空间又能回溯)
|
|
326
|
+
"backup_keep_hourly": 6,
|
|
327
|
+
"backup_keep_daily": 7,
|
|
328
|
+
"backup_keep_weekly": 4,
|
|
329
|
+
# —— 自动更新(P11 #75)——
|
|
330
|
+
# 默认关:自动改自己的代码风险高,必须用户显式开启。
|
|
331
|
+
# 开启后 cron 每 N 小时查一次,发现新版本才走 apply_update
|
|
332
|
+
# (原子 staging + 全量备份 + 回滚兜底),更新前强制先备份记忆库。
|
|
333
|
+
"auto_update": False,
|
|
334
|
+
"auto_update_interval_hours": 24,
|
|
319
335
|
"session_state_cache": False,
|
|
320
336
|
"session_state_ttl": 300,
|
|
321
337
|
# 候选7 跨对话上下文摄取:把别的会话/宿主导出的对话(.jsonl/.md/.txt)
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""桌面快捷键「灵枢面板」(P11 #76)。
|
|
3
|
+
|
|
4
|
+
做法:在数据目录生成一个隐藏窗口的启动器(.vbs),再在桌面放一个 .lnk 指向它。
|
|
5
|
+
为什么用 .vbs 包一层:直接指向 python.exe 会弹出黑色控制台窗口,用户点桌面图标
|
|
6
|
+
不该看到命令行;pythonw + vbs 双层保证静默启动。
|
|
7
|
+
|
|
8
|
+
桌面路径优先读注册表(OneDrive 重定向时 USERPROFILE\\Desktop 可能不是真桌面)。
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import core
|
|
18
|
+
|
|
19
|
+
SHORTCUT_NAME = "灵枢面板"
|
|
20
|
+
LAUNCHER_NAME = "灵枢面板启动器.vbs"
|
|
21
|
+
ICON_NAME = "lingshu.ico"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _pythonw() -> str:
|
|
25
|
+
"""优先用 pythonw.exe(无控制台窗口)。"""
|
|
26
|
+
exe = Path(sys.executable)
|
|
27
|
+
cand = exe.with_name("pythonw.exe")
|
|
28
|
+
return str(cand if cand.is_file() else exe)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _desktop_dir() -> Path:
|
|
32
|
+
"""桌面真实路径:先读注册表 Shell Folders,再退回 USERPROFILE\\Desktop。"""
|
|
33
|
+
try:
|
|
34
|
+
import winreg
|
|
35
|
+
with winreg.OpenKey(
|
|
36
|
+
winreg.HKEY_CURRENT_USER,
|
|
37
|
+
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") as k:
|
|
38
|
+
val, _ = winreg.QueryValueEx(k, "Desktop")
|
|
39
|
+
if val:
|
|
40
|
+
p = Path(os.path.expandvars(val))
|
|
41
|
+
if p.is_dir():
|
|
42
|
+
return p
|
|
43
|
+
except Exception:
|
|
44
|
+
pass
|
|
45
|
+
for name in ("Desktop", "桌面"):
|
|
46
|
+
p = Path.home() / name
|
|
47
|
+
if p.is_dir():
|
|
48
|
+
return p
|
|
49
|
+
return Path.home() / "Desktop"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _panel_script() -> Path:
|
|
53
|
+
root = Path(__file__).resolve().parent
|
|
54
|
+
return root / "panel_server.py"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _write_launcher(port: int | None = None) -> Path:
|
|
58
|
+
"""在数据目录写一个静默启动器的 .vbs。"""
|
|
59
|
+
home = Path(core.HOME)
|
|
60
|
+
home.mkdir(parents=True, exist_ok=True)
|
|
61
|
+
launcher = home / LAUNCHER_NAME
|
|
62
|
+
pyw = _pythonw()
|
|
63
|
+
script = _panel_script()
|
|
64
|
+
arg = f" --port {port}" if port else ""
|
|
65
|
+
# VBS:0 = 隐藏窗口运行;路径含空格用双引号包住(VBS 里 "" 表示一个 ")。
|
|
66
|
+
# ⚠ 必须以 **UTF-16LE + BOM** 写盘:wscript 默认按 ANSI 解析 .vbs,
|
|
67
|
+
# 而本项目路径常含中文(如 E:\丁厚同\...),UTF-8 会被当成 GBK 曲解,
|
|
68
|
+
# 于是 pythonw 收到一个不存在的路径、静默退出(实测踩过)。
|
|
69
|
+
lines = [
|
|
70
|
+
"' 由灵枢生成:静默启动可视化面板",
|
|
71
|
+
'Set sh = CreateObject("WScript.Shell")',
|
|
72
|
+
f'sh.Run """{pyw}"" ""{script}""{arg}", 0, False',
|
|
73
|
+
]
|
|
74
|
+
launcher.write_text("\r\n".join(lines) + "\r\n", encoding="utf-16-le")
|
|
75
|
+
# 手动补 BOM(pathlib 的 utf-16-le 不写 BOM)
|
|
76
|
+
raw = launcher.read_bytes()
|
|
77
|
+
if not raw.startswith(b"\xff\xfe"):
|
|
78
|
+
launcher.write_bytes(b"\xff\xfe" + raw)
|
|
79
|
+
return launcher
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _ps_quote(s: str) -> str:
|
|
83
|
+
return "'" + str(s).replace("'", "''") + "'"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def create(name: str = SHORTCUT_NAME, port: int | None = None) -> dict:
|
|
87
|
+
"""在桌面创建「灵枢面板」快捷方式;已存在则覆盖。返回结果字典。"""
|
|
88
|
+
if os.name != "nt":
|
|
89
|
+
return {"ok": False, "reason": "只支持 Windows"}
|
|
90
|
+
desktop = _desktop_dir()
|
|
91
|
+
if not desktop.is_dir():
|
|
92
|
+
return {"ok": False, "reason": f"桌面目录不存在:{desktop}"}
|
|
93
|
+
launcher = _write_launcher(port)
|
|
94
|
+
lnk = desktop / f"{name}.lnk"
|
|
95
|
+
ps = (
|
|
96
|
+
"$ws = New-Object -ComObject WScript.Shell; "
|
|
97
|
+
f"$s = $ws.CreateShortcut({_ps_quote(str(lnk))}); "
|
|
98
|
+
f"$s.TargetPath = 'wscript.exe'; "
|
|
99
|
+
f"$s.Arguments = '\"{launcher}\"'; "
|
|
100
|
+
f"$s.WorkingDirectory = {_ps_quote(str(Path(launcher).parent))}; "
|
|
101
|
+
f"$s.Description = '启动灵枢可视化面板'; "
|
|
102
|
+
"$s.WindowStyle = 7; "
|
|
103
|
+
"$s.Save(); "
|
|
104
|
+
"Write-Output 'ok'"
|
|
105
|
+
)
|
|
106
|
+
try:
|
|
107
|
+
r = subprocess.run(["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass",
|
|
108
|
+
"-Command", ps],
|
|
109
|
+
capture_output=True, text=True, encoding="utf-8",
|
|
110
|
+
errors="replace", timeout=60)
|
|
111
|
+
except Exception as exc: # noqa: BLE001
|
|
112
|
+
return {"ok": False, "reason": f"创建快捷方式失败:{exc}"}
|
|
113
|
+
ok = lnk.is_file() and "ok" in (r.stdout or "")
|
|
114
|
+
if ok:
|
|
115
|
+
core.log_event("shortcut", f"桌面快捷方式已创建:{lnk}")
|
|
116
|
+
return {"ok": ok, "path": str(lnk), "launcher": str(launcher),
|
|
117
|
+
"desktop": str(desktop),
|
|
118
|
+
"reason": "" if ok else (r.stderr or r.stdout or "未知失败")[:300]}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def remove(name: str = SHORTCUT_NAME) -> dict:
|
|
122
|
+
"""删除桌面快捷方式(启动器保留在数据目录,可再生成)。"""
|
|
123
|
+
desktop = _desktop_dir()
|
|
124
|
+
lnk = desktop / f"{name}.lnk"
|
|
125
|
+
removed = False
|
|
126
|
+
try:
|
|
127
|
+
if lnk.is_file():
|
|
128
|
+
lnk.unlink()
|
|
129
|
+
removed = True
|
|
130
|
+
except OSError as exc:
|
|
131
|
+
return {"ok": False, "reason": f"删除失败:{exc}"}
|
|
132
|
+
return {"ok": True, "removed": removed, "path": str(lnk)}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def shortcut_exists(name: str = SHORTCUT_NAME) -> bool:
|
|
136
|
+
return (_desktop_dir() / f"{name}.lnk").is_file()
|
|
@@ -27,9 +27,66 @@ def _backup_dir() -> Path:
|
|
|
27
27
|
return Path(core.HOME) / "backups"
|
|
28
28
|
|
|
29
29
|
|
|
30
|
+
def _manifest_of(path: Path) -> dict | None:
|
|
31
|
+
"""读备份包内的 _backup_manifest.json(拿记录数);读不到返回 None。"""
|
|
32
|
+
try:
|
|
33
|
+
import zipfile
|
|
34
|
+
with zipfile.ZipFile(path) as zf:
|
|
35
|
+
if "_backup_manifest.json" not in zf.namelist():
|
|
36
|
+
return None
|
|
37
|
+
return json.loads(zf.read("_backup_manifest.json").decode("utf-8"))
|
|
38
|
+
except Exception:
|
|
39
|
+
return None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
_COUNTABLE = ("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl",
|
|
43
|
+
"archive.jsonl", "knowledge.jsonl", "notes.jsonl")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _count_in_zip(path: Path) -> int | None:
|
|
47
|
+
"""兜底:老备份没有清单,就从包里数各层行数(包很小,代价可接受)。"""
|
|
48
|
+
try:
|
|
49
|
+
import zipfile
|
|
50
|
+
total = 0
|
|
51
|
+
with zipfile.ZipFile(path) as zf:
|
|
52
|
+
for n in zf.namelist():
|
|
53
|
+
if not any(n.endswith(x) for x in _COUNTABLE):
|
|
54
|
+
continue
|
|
55
|
+
try:
|
|
56
|
+
data = zf.read(n).decode("utf-8", "replace")
|
|
57
|
+
except Exception:
|
|
58
|
+
continue
|
|
59
|
+
total += sum(1 for ln in data.splitlines() if ln.strip())
|
|
60
|
+
return total
|
|
61
|
+
except Exception:
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _current_records() -> int:
|
|
66
|
+
"""当前库的有效记录总数(用于判断某个备份"是否明显不全")。"""
|
|
67
|
+
total = 0
|
|
68
|
+
for name in ("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl",
|
|
69
|
+
"archive.jsonl", "knowledge.jsonl", "notes.jsonl"):
|
|
70
|
+
p = core.HOME / name
|
|
71
|
+
if not p.is_file():
|
|
72
|
+
continue
|
|
73
|
+
try:
|
|
74
|
+
total += sum(1 for ln in p.open(encoding="utf-8", errors="replace") if ln.strip())
|
|
75
|
+
except OSError:
|
|
76
|
+
pass
|
|
77
|
+
return total
|
|
78
|
+
|
|
79
|
+
|
|
30
80
|
def list_backups(limit: int = 30) -> dict:
|
|
31
|
-
"""列出备份目录里的 zip
|
|
81
|
+
"""列出备份目录里的 zip:大小/时间/sha/记录数/是否可疑。
|
|
82
|
+
|
|
83
|
+
"疑似空壳"改成**按记录数**判定(P11 #73):原来只看 size<1024,
|
|
84
|
+
实测有个 3327 B、只有 2 条记录的测试包逃过检测,还因为最新而被当成
|
|
85
|
+
"最新备份"——恢复它会直接把库打回 2 条。
|
|
86
|
+
"""
|
|
32
87
|
d = _backup_dir()
|
|
88
|
+
cur = _current_records()
|
|
89
|
+
threshold = max(10, int(cur * 0.2)) # 不足当前库 20% 就标可疑
|
|
33
90
|
items = []
|
|
34
91
|
try:
|
|
35
92
|
files = sorted(d.glob("*.zip"), key=lambda p: p.stat().st_mtime, reverse=True)
|
|
@@ -41,18 +98,32 @@ def list_backups(limit: int = 30) -> dict:
|
|
|
41
98
|
except OSError:
|
|
42
99
|
continue
|
|
43
100
|
sha_file = p.with_name(p.name + ".sha256")
|
|
101
|
+
man = _manifest_of(p)
|
|
102
|
+
records = None
|
|
103
|
+
if man:
|
|
104
|
+
records = int(man.get("total_records") or 0)
|
|
105
|
+
if records is None:
|
|
106
|
+
records = _count_in_zip(p) # 老备份没清单:解包数一遍
|
|
107
|
+
age_h = max(0.0, (time.time() - st.st_mtime) / 3600.0)
|
|
108
|
+
# 可疑判定:空壳字节 / 记录数明显少于当前库
|
|
109
|
+
bad_size = st.st_size < 2048
|
|
110
|
+
bad_records = records is not None and records < threshold
|
|
44
111
|
items.append({
|
|
45
112
|
"name": p.name,
|
|
46
113
|
"path": str(p),
|
|
47
114
|
"size": st.st_size,
|
|
48
115
|
"mtime": int(st.st_mtime),
|
|
49
116
|
"mtime_text": time.strftime("%Y-%m-%d %H:%M", time.localtime(st.st_mtime)),
|
|
50
|
-
|
|
51
|
-
"
|
|
117
|
+
"age_hours": round(age_h, 1),
|
|
118
|
+
"records": records,
|
|
119
|
+
"suspicious": bool(bad_size or bad_records),
|
|
120
|
+
"suspicious_why": ("包体过小" if bad_size
|
|
121
|
+
else (f"记录数 {records} < 阈值 {threshold}" if bad_records else "")),
|
|
52
122
|
"has_sha": sha_file.is_file(),
|
|
53
123
|
})
|
|
54
124
|
return {"dir": str(d), "dir_exists": d.is_dir(), "items": items,
|
|
55
|
-
"count": len(items)
|
|
125
|
+
"count": len(items), "current_records": cur,
|
|
126
|
+
"suspicious_threshold": threshold}
|
|
56
127
|
|
|
57
128
|
|
|
58
129
|
def make_backup(keep: int = 0) -> dict:
|
|
@@ -82,6 +82,29 @@ CONFIG_SCHEMA: list[dict[str, Any]] = [
|
|
|
82
82
|
{"key": "extensions_enabled", "group": "面板与宿主", "label": "启用扩展模块",
|
|
83
83
|
"kind": "bool",
|
|
84
84
|
"hint": "扩展是任意本地 Python 代码,等于完全信任本机——只装你自己写的"},
|
|
85
|
+
|
|
86
|
+
# —— 自动更新与备份 ——
|
|
87
|
+
{"key": "auto_update", "group": "自动更新与备份", "label": "自动更新灵枢",
|
|
88
|
+
"kind": "bool",
|
|
89
|
+
"hint": "开启后定期检查新版本并自动更新;更新前会先备份记忆库,失败自动回滚"},
|
|
90
|
+
{"key": "auto_update_interval_hours", "group": "自动更新与备份",
|
|
91
|
+
"label": "检查更新间隔(小时)", "kind": "int", "min": 1, "max": 720, "step": 1,
|
|
92
|
+
"hint": "每隔多久查一次新版本(默认 24 小时)"},
|
|
93
|
+
{"key": "backup_interval_hours", "group": "自动更新与备份", "label": "自动备份间隔(小时)",
|
|
94
|
+
"kind": "int", "min": 1, "max": 168, "step": 1,
|
|
95
|
+
"hint": "每隔多久自动备份一次记忆库(默认 6 小时;原来是每天一次)"},
|
|
96
|
+
{"key": "backup_min_new_records", "group": "自动更新与备份", "label": "新增记录触发阈值",
|
|
97
|
+
"kind": "int", "min": 0, "max": 10000, "step": 10,
|
|
98
|
+
"hint": "新增这么多条记录就补一次备份(0=只看时间间隔)"},
|
|
99
|
+
{"key": "backup_keep_hourly", "group": "自动更新与备份", "label": "保留:最近几份",
|
|
100
|
+
"kind": "int", "min": 1, "max": 100, "step": 1,
|
|
101
|
+
"hint": "小时层保留份数;最新一份永不删"},
|
|
102
|
+
{"key": "backup_keep_daily", "group": "自动更新与备份", "label": "保留:每天几份",
|
|
103
|
+
"kind": "int", "min": 0, "max": 90, "step": 1,
|
|
104
|
+
"hint": "天层保留(每天最多留 1 份,这里填天数)"},
|
|
105
|
+
{"key": "backup_keep_weekly", "group": "自动更新与备份", "label": "保留:每周几份",
|
|
106
|
+
"kind": "int", "min": 0, "max": 52, "step": 1,
|
|
107
|
+
"hint": "周层保留(每周最多留 1 份,这里填周数)"},
|
|
85
108
|
]
|
|
86
109
|
|
|
87
110
|
_BY_KEY = {x["key"]: x for x in CONFIG_SCHEMA}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""自动更新灵枢(P11 #75)。
|
|
3
|
+
|
|
4
|
+
安全顺序(任一步失败都不留半新半旧):
|
|
5
|
+
1. 先查是否有新版本(growth.update_check,不联网就不动手)
|
|
6
|
+
2. **先备份记忆库**(记忆比代码重要,更新失败至少记忆在)
|
|
7
|
+
3. growth.apply_update 原子替换(内部:SHA256 校验 → 全量备份 → 回滚兜底)
|
|
8
|
+
4. 写审计日志 + 结果
|
|
9
|
+
默认关闭(config.auto_update=false):自动改自己的代码风险高,必须用户显式开启。
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
import core
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _cfg() -> dict:
|
|
20
|
+
try:
|
|
21
|
+
return core.load_config()
|
|
22
|
+
except Exception:
|
|
23
|
+
return {}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def enabled() -> bool:
|
|
27
|
+
return bool(_cfg().get("auto_update"))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def check(force_pull: bool = False) -> dict:
|
|
31
|
+
"""查有没有新版本(只读)。"""
|
|
32
|
+
import growth
|
|
33
|
+
try:
|
|
34
|
+
return growth.update_check("lingshu", force_pull=force_pull)
|
|
35
|
+
except Exception as exc: # noqa: BLE001
|
|
36
|
+
core.log_event("update", f"检查更新失败:{exc}", level="warn")
|
|
37
|
+
return {"ok": False, "error": str(exc)}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def run(force: bool = False) -> dict:
|
|
41
|
+
"""执行一次自动更新(含更新前备份)。返回结果字典。"""
|
|
42
|
+
if core.READONLY:
|
|
43
|
+
return {"ok": False, "reason": "记忆库只读,跳过自动更新"}
|
|
44
|
+
if not force and not enabled():
|
|
45
|
+
return {"ok": False, "skipped": True, "reason": "auto_update 未开启"}
|
|
46
|
+
|
|
47
|
+
chk = check(force_pull=True)
|
|
48
|
+
if not chk or not chk.get("update_available"):
|
|
49
|
+
return {"ok": True, "skipped": True,
|
|
50
|
+
"reason": "已是最新", "current": chk.get("current"),
|
|
51
|
+
"latest": chk.get("latest")}
|
|
52
|
+
|
|
53
|
+
# ① 更新前先备份记忆库(失败就不更新:宁可旧代码,不能丢记忆)
|
|
54
|
+
bak = None
|
|
55
|
+
try:
|
|
56
|
+
import cli
|
|
57
|
+
code = cli.cmd_backup(target=None, keep=0, password=None, assume_yes=True)
|
|
58
|
+
if code != 0:
|
|
59
|
+
return {"ok": False, "reason": "更新前备份失败,已中止(不冒险)"}
|
|
60
|
+
import panel_data
|
|
61
|
+
lst = panel_data.list_backups(limit=1)
|
|
62
|
+
bak = (lst.get("items") or [{}])[0].get("name")
|
|
63
|
+
except Exception as exc: # noqa: BLE001
|
|
64
|
+
core.log_event("update", f"更新前备份异常:{exc}", level="error")
|
|
65
|
+
return {"ok": False, "reason": f"更新前备份异常,已中止:{exc}"}
|
|
66
|
+
|
|
67
|
+
# ② 原子更新
|
|
68
|
+
try:
|
|
69
|
+
import growth
|
|
70
|
+
src, kind = growth.resolve_source("lingshu", force_pull=False)
|
|
71
|
+
res = growth.install_skill("lingshu", force=True, from_dir=str(src))
|
|
72
|
+
except Exception as exc: # noqa: BLE001
|
|
73
|
+
core.log_event("update", f"自动更新失败:{exc}", level="error")
|
|
74
|
+
return {"ok": False, "reason": f"更新失败(已回滚):{exc}", "backup": bak}
|
|
75
|
+
|
|
76
|
+
core.log_event("update", f"自动更新完成:{chk.get('current')} → {chk.get('latest')};"
|
|
77
|
+
f"更新前备份 {bak}")
|
|
78
|
+
return {"ok": True, "updated": True, "backup": bak,
|
|
79
|
+
"from": chk.get("current"), "to": chk.get("latest"),
|
|
80
|
+
"detail": res if isinstance(res, dict) else str(res),
|
|
81
|
+
"at": int(time.time())}
|
|
@@ -93,6 +93,16 @@ def do_bump(new_ver: str, title: str) -> int:
|
|
|
93
93
|
if not re.fullmatch(r"\d+\.\d+", new_ver):
|
|
94
94
|
print(f"[release] 版本格式应为 X.Y,收到 {new_ver!r}", file=sys.stderr)
|
|
95
95
|
return 1
|
|
96
|
+
# semver 不允许前导零:npm 会把 4.01.0 规范化成 4.1.0 发布出去,
|
|
97
|
+
# 而本地 package.json 仍写 4.01.0,publish 轮询 registry 就永远等不到
|
|
98
|
+
# 4.01.0(v4.01 就这么卡死过一次)。在这里挡掉。
|
|
99
|
+
_bad = [seg for seg in new_ver.split(".")
|
|
100
|
+
if len(seg) > 1 and seg.startswith("0") and seg.isdigit()]
|
|
101
|
+
if _bad:
|
|
102
|
+
fixed = ".".join(str(int(s)) if s.isdigit() else s for s in new_ver.split("."))
|
|
103
|
+
print(f"[release] 版本号 {new_ver} 含前导零段 {_bad}(semver 不允许),"
|
|
104
|
+
f"请改用 {fixed}", file=sys.stderr)
|
|
105
|
+
return 1
|
|
96
106
|
old = cur_version()
|
|
97
107
|
if _ver_tuple(new_ver) <= _ver_tuple(old):
|
|
98
108
|
print(f"[release] 新版本 {new_ver} 必须大于当前 {old}", file=sys.stderr)
|