lingshu-skill 5.30.0 → 5.31.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 +79 -0
- package/README.md +1 -1
- package/SKILL-lite.md +1 -1
- package/SKILL-tiny.md +1 -1
- package/SKILL.md +341 -405
- package/assets/panel.html +490 -18
- package/cordis-plugin/lingshu-cron/plugin.js +195 -29
- package/docs//344/275/277/347/224/250/346/214/207/345/215/227.md +229 -0
- package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +73 -31
- package/docs//345/276/205/345/212/236/346/250/241/346/235/277.md +140 -0
- package/package.json +1 -1
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +20 -17
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +79 -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 +341 -405
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +490 -18
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +47 -18
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +32 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +7 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +14 -6
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +27 -5
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +15 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +462 -14
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_icon.py +220 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_launcher.py +114 -10
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +165 -41
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_shortcut.py +330 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_splash.py +181 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +19 -5
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety_net.py +29 -3
- package/scripts/cli.py +47 -18
- package/scripts/core.py +32 -0
- package/scripts/dream.py +7 -1
- package/scripts/emotion.py +14 -6
- package/scripts/growth.py +27 -5
- package/scripts/mem_dialogue.py +15 -0
- package/scripts/memory.py +462 -14
- package/scripts/panel_icon.py +220 -0
- package/scripts/panel_launcher.py +114 -10
- package/scripts/panel_server.py +165 -41
- package/scripts/panel_shortcut.py +330 -0
- package/scripts/panel_splash.py +181 -0
- package/scripts/persona.py +19 -5
- package/scripts/safety_net.py +29 -3
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""面板快捷方式的全局快捷键:读 / 写 `灵枢面板.lnk` 的 Hotkey 字段。
|
|
3
|
+
|
|
4
|
+
Windows 的 .lnk 自带一个「快捷键」字段,写上 `CTRL+ALT+L` 这类组合,系统就会在
|
|
5
|
+
**任何程序里**都响应它——这正是用户想要的"能自定义的快捷键",不需要常驻热键服务、
|
|
6
|
+
不需要第三方库。
|
|
7
|
+
|
|
8
|
+
为什么用 PowerShell 子进程而不是 pywin32:
|
|
9
|
+
· 灵枢是零依赖技能,不能要求装 pywin32;
|
|
10
|
+
· `WScript.Shell` 的 `CreateShortcut()` 是 Windows 自带的 COM,PowerShell 一行就能调。
|
|
11
|
+
|
|
12
|
+
安全边界:只写 **Hotkey** 与 **IconLocation** 两个字段,其余(TargetPath/Arguments/
|
|
13
|
+
WorkingDirectory)原样保留——改错一个字段就会让快捷方式指向别处。
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import re
|
|
19
|
+
import subprocess
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
# .lnk 里允许的按键写法:CTRL/ALT/SHIFT/WIN + 一个按键
|
|
23
|
+
_MODS = ("CTRL", "ALT", "SHIFT", "WIN", "EXT")
|
|
24
|
+
_KEYS = (
|
|
25
|
+
[chr(c) for c in range(ord("A"), ord("Z") + 1)]
|
|
26
|
+
+ [str(d) for d in range(10)]
|
|
27
|
+
+ [f"F{i}" for i in range(1, 25)]
|
|
28
|
+
+ ["INSERT", "DELETE", "HOME", "END", "PGUP", "PGDN",
|
|
29
|
+
"LEFT", "RIGHT", "UP", "DOWN", "TAB", "SPACE", "ENTER", "BACK", "ESC"]
|
|
30
|
+
)
|
|
31
|
+
_ALIAS = {"CONTROL": "CTRL", "CTL": "CTRL", "WINKEY": "WIN", "WINDOWS": "WIN",
|
|
32
|
+
"DEL": "DELETE", "INS": "INSERT", "ESCAPE": "ESC", "RETURN": "ENTER"}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ShortcutError(RuntimeError):
|
|
36
|
+
"""快捷方式读写失败(找不到 .lnk / PowerShell 不可用 / 格式不对)。"""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def normalize_hotkey(raw: str) -> str:
|
|
40
|
+
"""把用户写法归一成 .lnk 认识的 `CTRL+ALT+L`。
|
|
41
|
+
|
|
42
|
+
接受 `ctrl+alt+l` / `Ctrl + Alt + L` / `control-alt-l` 等写法;
|
|
43
|
+
空字符串表示"清除快捷键"(合法)。
|
|
44
|
+
"""
|
|
45
|
+
s = (raw or "").strip().upper().replace(" ", "")
|
|
46
|
+
if not s:
|
|
47
|
+
return ""
|
|
48
|
+
parts = [p for p in re.split(r"[+\-]", s) if p]
|
|
49
|
+
if not parts:
|
|
50
|
+
return ""
|
|
51
|
+
mods, keys = [], []
|
|
52
|
+
for p in parts:
|
|
53
|
+
p = _ALIAS.get(p, p)
|
|
54
|
+
if p in _MODS:
|
|
55
|
+
if p not in mods:
|
|
56
|
+
mods.append(p)
|
|
57
|
+
elif p in _KEYS:
|
|
58
|
+
keys.append(p)
|
|
59
|
+
else:
|
|
60
|
+
raise ShortcutError(
|
|
61
|
+
f"不认识的按键「{p}」。可用:CTRL / ALT / SHIFT / WIN + 一个字母、"
|
|
62
|
+
f"数字或 F1–F24(例如 CTRL+ALT+L)")
|
|
63
|
+
if len(keys) != 1:
|
|
64
|
+
raise ShortcutError("需要且只能有一个主键,例如 CTRL+ALT+L")
|
|
65
|
+
if not mods:
|
|
66
|
+
raise ShortcutError("至少要有一个修饰键(CTRL / ALT / SHIFT / WIN),"
|
|
67
|
+
"否则会抢掉普通打字")
|
|
68
|
+
# .lnk 要求固定顺序:CTRL、ALT、SHIFT、WIN
|
|
69
|
+
order = [m for m in ("CTRL", "ALT", "SHIFT", "WIN", "EXT") if m in mods]
|
|
70
|
+
return "+".join(order + keys)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def find_shortcut() -> Path:
|
|
74
|
+
"""按优先级找出面板快捷方式。"""
|
|
75
|
+
home = Path.home()
|
|
76
|
+
for p in (home / "Desktop" / "灵枢面板.lnk",
|
|
77
|
+
Path(r"C:\Users\Public\Desktop") / "灵枢面板.lnk",
|
|
78
|
+
home / "Desktop" / "lingshu-panel.lnk"):
|
|
79
|
+
if p.is_file():
|
|
80
|
+
return p
|
|
81
|
+
raise ShortcutError("找不到桌面上的「灵枢面板.lnk」。"
|
|
82
|
+
"请先在面板「诊断 → 数据目录」旁点「创建桌面快捷方式」。")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
_PS_READ = r"""
|
|
86
|
+
$ErrorActionPreference='Stop'
|
|
87
|
+
# 强制 UTF-8 输出:中文路径(灵枢面板启动器.vbs)否则会按 GBK 吐出来,
|
|
88
|
+
# Python 侧拿到乱码字符串,完整性比对(逐字段相等)就会假报"被改动"。
|
|
89
|
+
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
90
|
+
$OutputEncoding = [System.Text.Encoding]::UTF8
|
|
91
|
+
$sh = New-Object -ComObject WScript.Shell
|
|
92
|
+
$l = $sh.CreateShortcut('{lnk}')
|
|
93
|
+
$o = [ordered]@{{
|
|
94
|
+
target=$l.TargetPath; args=$l.Arguments; wd=$l.WorkingDirectory;
|
|
95
|
+
icon=$l.IconLocation; hotkey=$l.Hotkey; style=$l.WindowStyle
|
|
96
|
+
}}
|
|
97
|
+
$o | ConvertTo-Json -Compress
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
_PS_WRITE = r"""
|
|
101
|
+
$ErrorActionPreference='Stop'
|
|
102
|
+
$sh = New-Object -ComObject WScript.Shell
|
|
103
|
+
$l = $sh.CreateShortcut('{lnk}')
|
|
104
|
+
$l.Hotkey = '{hotkey}'
|
|
105
|
+
$l.Save()
|
|
106
|
+
Write-Output 'saved'
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
_PS_REPAIR = r"""
|
|
110
|
+
$ErrorActionPreference='Stop'
|
|
111
|
+
$sh = New-Object -ComObject WScript.Shell
|
|
112
|
+
$l = $sh.CreateShortcut('{lnk}')
|
|
113
|
+
$l.TargetPath = 'C:\WINDOWS\system32\wscript.exe'
|
|
114
|
+
$l.Arguments = '"{vbs}"'
|
|
115
|
+
$l.WorkingDirectory = '{wd}'
|
|
116
|
+
$l.IconLocation = '{icon}'
|
|
117
|
+
$l.Description = '{desc}'
|
|
118
|
+
$l.WindowStyle = 7
|
|
119
|
+
$l.Save()
|
|
120
|
+
Write-Output 'repaired'
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
# 改图标 + 让资源管理器立刻重读。
|
|
124
|
+
# Explorer 会缓存图标:只写 .lnk 经常「没变化」,所以补一次 SHChangeNotify
|
|
125
|
+
# (SHCNE_ASSOCCHANGED / SHCNF_IDLIST),这是不重启 explorer 就能刷新的标准做法。
|
|
126
|
+
_PS_SET_ICON = r"""
|
|
127
|
+
$ErrorActionPreference='Stop'
|
|
128
|
+
$sh = New-Object -ComObject WScript.Shell
|
|
129
|
+
$l = $sh.CreateShortcut('{lnk}')
|
|
130
|
+
$l.IconLocation = '{icon}'
|
|
131
|
+
$l.Save()
|
|
132
|
+
try {{
|
|
133
|
+
Add-Type -Namespace W32 -Name U -MemberDefinition @'
|
|
134
|
+
[System.Runtime.InteropServices.DllImport("shell32.dll")]
|
|
135
|
+
public static extern void SHChangeNotify(int eventId, uint flags, System.IntPtr a, System.IntPtr b);
|
|
136
|
+
'@ -ErrorAction Stop | Out-Null
|
|
137
|
+
[W32.U]::SHChangeNotify(0x08000000, 0x0000, [IntPtr]::Zero, [IntPtr]::Zero) | Out-Null
|
|
138
|
+
}} catch {{ }}
|
|
139
|
+
Write-Output 'ok'
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _run_ps(script: str, timeout: int = 60) -> str:
|
|
144
|
+
"""跑一段 PowerShell。
|
|
145
|
+
|
|
146
|
+
为什么用 `-EncodedCommand`(base64/UTF-16LE)而不是 `-Command`:
|
|
147
|
+
脚本里带**中文路径**(`灵枢面板启动器.vbs`、`灵枢面板.lnk`)。`-Command` 走命令行
|
|
148
|
+
编码,中文容易在中途被按 ANSI 解释,`CreateShortcut()` 于是拿到一个错的路径、
|
|
149
|
+
建出一个**空 shortcut 对象**,`Save()` 一写就把原来的字段全冲掉——实测就是这么
|
|
150
|
+
把用户的桌面快捷方式清空的(图标变白、点了没反应)。EncodedCommand 是二进制安全的,
|
|
151
|
+
彻底绕开这一层。
|
|
152
|
+
|
|
153
|
+
`timeout` 给到 60s:首次 `New-Object -ComObject WScript.Shell` 冷启动实测能到 30s。
|
|
154
|
+
超时**不做强杀**——强杀会把 `Save()` 卡在半途,留下写坏的 .lnk。
|
|
155
|
+
"""
|
|
156
|
+
import base64
|
|
157
|
+
blob = base64.b64encode(script.encode("utf-16-le")).decode("ascii")
|
|
158
|
+
try:
|
|
159
|
+
r = subprocess.run(
|
|
160
|
+
["powershell", "-NoProfile", "-NonInteractive", "-EncodedCommand", blob],
|
|
161
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace",
|
|
162
|
+
timeout=timeout, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
|
163
|
+
except subprocess.TimeoutExpired as exc:
|
|
164
|
+
raise ShortcutError(
|
|
165
|
+
f"PowerShell 超时({timeout}s)。快捷方式可能已被改动,"
|
|
166
|
+
f"请点「刷新」确认;若目标/图标丢了,点「修复快捷方式」还原。") from exc
|
|
167
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
168
|
+
raise ShortcutError(f"调用 PowerShell 失败:{exc}") from exc
|
|
169
|
+
if r.returncode != 0:
|
|
170
|
+
raise ShortcutError((r.stderr or r.stdout or "").strip()[:300] or "PowerShell 失败")
|
|
171
|
+
return (r.stdout or "").strip()
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _same_hotkey(a: str, b: str) -> bool:
|
|
175
|
+
"""两个热键写法是否等价(**顺序无关**)。
|
|
176
|
+
|
|
177
|
+
Windows 会把 `CTRL+ALT+SHIFT+F12` 存成 `Alt+Ctrl+Shift+F12`——直接比字符串
|
|
178
|
+
会永远判"写入未生效"(实测踩过)。按 `+` 拆成集合比大小写无关的 token。
|
|
179
|
+
"""
|
|
180
|
+
def toks(s):
|
|
181
|
+
return {t for t in (s or "").upper().replace(" ", "").split("+") if t}
|
|
182
|
+
return toks(a) == toks(b)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# 快捷方式必须完好的字段。只写 Hotkey 时这几个**一个字都不许变**——
|
|
186
|
+
# 变了就说明 Save() 写坏了一个空对象(真实事故:桌面图标变白、点了没反应)。
|
|
187
|
+
_INTEGRITY_FIELDS = ("target", "args", "wd", "icon")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _backup_dir() -> Path:
|
|
191
|
+
"""快捷方式备份放数据目录下:更新技能不会覆盖它,也不会脏了桌面。"""
|
|
192
|
+
d = Path.home() / ".brain-memory" / "shortcut-backup"
|
|
193
|
+
try:
|
|
194
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
195
|
+
except OSError:
|
|
196
|
+
pass
|
|
197
|
+
return d
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _backup(lnk: Path) -> Path | None:
|
|
201
|
+
try:
|
|
202
|
+
dst = _backup_dir() / (lnk.stem + ".lnk.bak")
|
|
203
|
+
dst.write_bytes(lnk.read_bytes())
|
|
204
|
+
return dst
|
|
205
|
+
except OSError:
|
|
206
|
+
return None
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _restore_from(backup: Path, lnk: Path) -> bool:
|
|
210
|
+
try:
|
|
211
|
+
lnk.write_bytes(backup.read_bytes())
|
|
212
|
+
return True
|
|
213
|
+
except OSError:
|
|
214
|
+
return False
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def read_shortcut(lnk: Path | None = None) -> dict:
|
|
218
|
+
"""读取快捷方式的全部关键字段(含当前 Hotkey)。"""
|
|
219
|
+
lk = lnk or find_shortcut()
|
|
220
|
+
raw = _run_ps(_PS_READ.format(lnk=str(lk).replace("'", "''")))
|
|
221
|
+
try:
|
|
222
|
+
data = json.loads(raw)
|
|
223
|
+
except ValueError:
|
|
224
|
+
data = {}
|
|
225
|
+
data["path"] = str(lk)
|
|
226
|
+
data["hotkey"] = (data.get("hotkey") or "").strip()
|
|
227
|
+
# 完整性:四个关键字段都在才算"没被写坏"
|
|
228
|
+
data["intact"] = all(str(data.get(k) or "").strip() for k in _INTEGRITY_FIELDS)
|
|
229
|
+
return data
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def set_hotkey(hotkey: str, lnk: Path | None = None) -> dict:
|
|
233
|
+
"""设置(或清除)全局快捷键,**并保证不损坏快捷方式本身**。
|
|
234
|
+
|
|
235
|
+
三步防线(都是这次真实事故换来的):
|
|
236
|
+
1. 写之前把 .lnk 原样备份到数据目录;
|
|
237
|
+
2. 写完之后回读,逐个核对 TargetPath / Arguments / WorkingDirectory / IconLocation
|
|
238
|
+
有没有变——只改 Hotkey 时它们一个字都不该动;
|
|
239
|
+
3. 一旦发现丢了字段,**立刻用备份还原**并把错误报出去,绝不留下一个空白快捷方式。
|
|
240
|
+
"""
|
|
241
|
+
norm = normalize_hotkey(hotkey)
|
|
242
|
+
lk = lnk or find_shortcut()
|
|
243
|
+
before = read_shortcut(lk)
|
|
244
|
+
if not before.get("intact"):
|
|
245
|
+
raise ShortcutError(
|
|
246
|
+
"当前快捷方式本身已经不完整(目标/参数/图标有缺失),先点「修复快捷方式」再说,"
|
|
247
|
+
"否则改热键只会把它写得更坏。")
|
|
248
|
+
bak = _backup(lk)
|
|
249
|
+
_run_ps(_PS_WRITE.format(lnk=str(lk).replace("'", "''"), hotkey=norm))
|
|
250
|
+
after = read_shortcut(lk)
|
|
251
|
+
|
|
252
|
+
# —— 完整性核对 ——
|
|
253
|
+
broken = [k for k in _INTEGRITY_FIELDS
|
|
254
|
+
if str(before.get(k) or "") != str(after.get(k) or "")]
|
|
255
|
+
if broken:
|
|
256
|
+
restored = _restore_from(bak, lk) if bak else False
|
|
257
|
+
brain_note = ("已用备份还原" if restored else "备份还原失败,请手动修复")
|
|
258
|
+
raise ShortcutError(
|
|
259
|
+
f"写入热键时破坏了快捷方式(字段变化:{'、'.join(broken)})。{brain_note}。")
|
|
260
|
+
|
|
261
|
+
applied = (after.get("hotkey") or "").strip()
|
|
262
|
+
return {
|
|
263
|
+
"ok": True,
|
|
264
|
+
"requested": norm,
|
|
265
|
+
"applied": applied,
|
|
266
|
+
"before": before.get("hotkey", ""),
|
|
267
|
+
"path": str(lk),
|
|
268
|
+
"intact": after.get("intact", False),
|
|
269
|
+
"backup": str(bak) if bak else "",
|
|
270
|
+
# 写不进 Hotkey 时 Windows 会给回空串——如实报告,别假装成功。
|
|
271
|
+
"verified": (not norm and not applied) or _same_hotkey(norm, applied),
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def set_icon_location(icon_value: str, lnk: Path | None = None) -> dict:
|
|
276
|
+
"""只改 `.lnk` 的 IconLocation,其余字段一个字不动。
|
|
277
|
+
|
|
278
|
+
`icon_value` 形如 `C:\\path\\x.ico,0`(.ico 用 0;.exe/.dll 用资源序号)。
|
|
279
|
+
沿用 set_hotkey 的三步防线:备份 → 写 → 逐字段核对 → 坏了自动还原。
|
|
280
|
+
"""
|
|
281
|
+
lk = lnk or find_shortcut()
|
|
282
|
+
before = read_shortcut(lk)
|
|
283
|
+
if not before.get("intact"):
|
|
284
|
+
raise ShortcutError(
|
|
285
|
+
"当前快捷方式本身已经不完整(目标/参数/图标有缺失),先点「修复快捷方式」再说。")
|
|
286
|
+
bak = _backup(lk)
|
|
287
|
+
_run_ps(_PS_SET_ICON.format(lnk=str(lk).replace("'", "''"),
|
|
288
|
+
icon=icon_value.replace("'", "''")))
|
|
289
|
+
after = read_shortcut(lk)
|
|
290
|
+
# 只有 icon 允许变,target/args/wd 必须原样
|
|
291
|
+
broken = [k for k in ("target", "args", "wd")
|
|
292
|
+
if str(before.get(k) or "") != str(after.get(k) or "")]
|
|
293
|
+
if broken:
|
|
294
|
+
restored = _restore_from(bak, lk) if bak else False
|
|
295
|
+
raise ShortcutError(
|
|
296
|
+
f"写图标时破坏了快捷方式(字段变化:{'、'.join(broken)})。"
|
|
297
|
+
f"{'已用备份还原' if restored else '备份还原失败,请点「修复快捷方式」'}。")
|
|
298
|
+
return {
|
|
299
|
+
"ok": True,
|
|
300
|
+
"icon": after.get("icon", ""),
|
|
301
|
+
"previous": before.get("icon", ""),
|
|
302
|
+
"path": str(lk),
|
|
303
|
+
"intact": after.get("intact", False),
|
|
304
|
+
"backup": str(bak) if bak else "",
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def repair_shortcut(lnk: Path | None = None) -> dict:
|
|
309
|
+
"""把被写坏的快捷方式重建回来(目标/参数/图标/窗口样式按灵枢的标准值)。
|
|
310
|
+
|
|
311
|
+
真实事故:热键写入把 .lnk 清空 → 桌面图标变白、双击没反应。
|
|
312
|
+
这里的值来自灵枢自己生成的启动器约定(wscript + 启动器.vbs + lingshu.ico)。
|
|
313
|
+
"""
|
|
314
|
+
lk = lnk or (Path.home() / "Desktop" / "灵枢面板.lnk")
|
|
315
|
+
home = Path.home()
|
|
316
|
+
vbs = home / ".brain-memory" / "灵枢面板启动器.vbs"
|
|
317
|
+
ico = home / ".brain-memory" / "lingshu.ico"
|
|
318
|
+
if not vbs.is_file():
|
|
319
|
+
raise ShortcutError(f"启动器不存在:{vbs}(面板「诊断」页可重新生成)")
|
|
320
|
+
script = _PS_REPAIR.format(
|
|
321
|
+
lnk=str(lk).replace("'", "''"),
|
|
322
|
+
vbs=str(vbs).replace("'", "''"),
|
|
323
|
+
wd=str(home / ".brain-memory").replace("'", "''"),
|
|
324
|
+
icon=(str(ico).replace("'", "''") + ",0") if ico.is_file() else "",
|
|
325
|
+
desc="灵枢 · 类脑记忆面板",
|
|
326
|
+
)
|
|
327
|
+
_run_ps(script)
|
|
328
|
+
after = read_shortcut(lk)
|
|
329
|
+
return {"ok": bool(after.get("intact")), **after,
|
|
330
|
+
"vbs_exists": vbs.is_file(), "icon_exists": ico.is_file()}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""灵枢启动光晕:点开快捷方式后**立刻**出现的加载态。
|
|
3
|
+
|
|
4
|
+
为什么要有(用户反馈):快捷方式走 wscript → pythonw(隐藏进程),从点击到浏览器
|
|
5
|
+
出画面这几秒里屏幕上什么都没发生,用户以为"点了没作用",会连点好几次。
|
|
6
|
+
|
|
7
|
+
设计取向「符合灵枢」:不是一个转圈的进度条,而是一枚**呼吸的星核**——三层同心环
|
|
8
|
+
以不同速率明灭,中心一颗暖金色 orb,下面一行小字说明现在在做什么。
|
|
9
|
+
和面板里的星图、人格星核是同一套视觉语言。
|
|
10
|
+
|
|
11
|
+
实现约束:
|
|
12
|
+
· 只用标准库 tkinter(零依赖),**拿不到就静默跳过**,绝不让启动失败;
|
|
13
|
+
· 无边框 + 置顶 + 居中,尺寸小(400×190),不抢焦点;
|
|
14
|
+
· 主线程跑 tkinter 事件循环,真实工作在别的线程做(Windows 上 tkinter 必须在
|
|
15
|
+
主线程才能稳定响应,所以不能反过来)。
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import tkinter as tk
|
|
20
|
+
|
|
21
|
+
# 与面板同一套色:--bg #0a0c0f / --amber #d9a441 / --faint #5d646e
|
|
22
|
+
BG = "#0a0c0f"
|
|
23
|
+
AMBER = "#d9a441"
|
|
24
|
+
AMBER_DIM = "#8a6423"
|
|
25
|
+
TEXT = "#e9e6df"
|
|
26
|
+
FAINT = "#5d646e"
|
|
27
|
+
|
|
28
|
+
W, H = 400, 190
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _center(win: tk.Tk) -> None:
|
|
32
|
+
win.update_idletasks()
|
|
33
|
+
try:
|
|
34
|
+
sw = win.winfo_screenwidth()
|
|
35
|
+
sh = win.winfo_screenheight()
|
|
36
|
+
x = (sw - W) // 2
|
|
37
|
+
y = (sh - H) // 2 - 40 # 略微偏上,视觉重心更舒服
|
|
38
|
+
win.geometry(f"{W}x{H}+{x}+{y}")
|
|
39
|
+
except Exception:
|
|
40
|
+
win.geometry(f"{W}x{H}")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Splash:
|
|
44
|
+
"""三环呼吸 + 中心星核的可关闭加载窗。
|
|
45
|
+
|
|
46
|
+
用法:
|
|
47
|
+
sp = Splash("正在唤醒记忆…")
|
|
48
|
+
sp.start() # 非阻塞,装上事件循环的定时器
|
|
49
|
+
...做正事...
|
|
50
|
+
sp.set_text("正在打开面板…")
|
|
51
|
+
sp.close()
|
|
52
|
+
sp.run() # 真正驱动界面(阻塞到 close 之后)
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(self, text: str = "正在唤醒记忆…", sub: str = "灵枢 · 类脑记忆"):
|
|
56
|
+
self._closed = False
|
|
57
|
+
self._phase = 0.0
|
|
58
|
+
self._text = text
|
|
59
|
+
self._sub = sub
|
|
60
|
+
self.root = None
|
|
61
|
+
self.canvas = None
|
|
62
|
+
try:
|
|
63
|
+
self.root = tk.Tk()
|
|
64
|
+
# 先隐藏再搭界面:Tk 建窗后默认是系统白底,若先显示再画布上色,
|
|
65
|
+
# 会闪一下白框(实测用户会以为"白屏/没反应")。先 withdraw →
|
|
66
|
+
# 全部画好 → update → 再显示,观感是"直接出现一枚黑底光晕"。
|
|
67
|
+
self.root.withdraw()
|
|
68
|
+
self.root.overrideredirect(True) # 无边框
|
|
69
|
+
self.root.attributes("-topmost", True)
|
|
70
|
+
try:
|
|
71
|
+
self.root.attributes("-alpha", 0.0) # 显示瞬间也不透明白闪
|
|
72
|
+
except Exception:
|
|
73
|
+
pass
|
|
74
|
+
self.root.configure(bg=BG)
|
|
75
|
+
_center(self.root)
|
|
76
|
+
self.canvas = tk.Canvas(self.root, width=W, height=H, bg=BG,
|
|
77
|
+
highlightthickness=0, bd=0)
|
|
78
|
+
self.canvas.pack(fill="both", expand=True)
|
|
79
|
+
self._draw_static()
|
|
80
|
+
self._animate()
|
|
81
|
+
# 强制先把这一帧画完,再露出来
|
|
82
|
+
self.root.update_idletasks()
|
|
83
|
+
self.root.update()
|
|
84
|
+
self.root.deiconify()
|
|
85
|
+
try:
|
|
86
|
+
self.root.attributes("-alpha", 0.97)
|
|
87
|
+
except Exception:
|
|
88
|
+
pass
|
|
89
|
+
except Exception:
|
|
90
|
+
# 没有 tkinter / 没有显示环境:静默降级,绝不阻断启动
|
|
91
|
+
self.root = None
|
|
92
|
+
|
|
93
|
+
# ---------------------------------------------------------------- 绘制
|
|
94
|
+
def _draw_static(self) -> None:
|
|
95
|
+
c = self.canvas
|
|
96
|
+
c.create_text(W // 2, 44, text="灵 枢", fill=AMBER,
|
|
97
|
+
font=("Microsoft YaHei UI", 19, "bold"))
|
|
98
|
+
c.create_text(W // 2, 68, text=self._sub, fill=FAINT,
|
|
99
|
+
font=("Microsoft YaHei UI", 9))
|
|
100
|
+
self.txt = c.create_text(W // 2, 152, text=self._text, fill=TEXT,
|
|
101
|
+
font=("Microsoft YaHei UI", 10))
|
|
102
|
+
# 三个环的 id 留着按相位改颜色/宽度
|
|
103
|
+
self.rings = [c.create_oval(0, 0, 0, 0, outline=AMBER_DIM, width=1)
|
|
104
|
+
for _ in range(3)]
|
|
105
|
+
self.core = c.create_oval(0, 0, 0, 0, fill=AMBER, outline="")
|
|
106
|
+
|
|
107
|
+
def _animate(self) -> None:
|
|
108
|
+
if self._closed or self.canvas is None:
|
|
109
|
+
return
|
|
110
|
+
import math
|
|
111
|
+
c = self.canvas
|
|
112
|
+
cx, cy = W // 2, 108
|
|
113
|
+
self._phase += 0.07
|
|
114
|
+
# 星核呼吸:半径在 5~7 之间起伏
|
|
115
|
+
cr = 5.0 + 1.6 * math.sin(self._phase * 1.6)
|
|
116
|
+
c.coords(self.core, cx - cr, cy - cr, cx + cr, cy + cr)
|
|
117
|
+
# 三环:相位错开 2π/3,越靠外的环越淡、扩张越慢
|
|
118
|
+
for i, rid in enumerate(self.rings):
|
|
119
|
+
ph = self._phase * 0.9 - i * (2 * math.pi / 3)
|
|
120
|
+
t = (math.sin(ph) + 1) / 2 # 0..1
|
|
121
|
+
r = 13 + i * 11 + t * 5
|
|
122
|
+
c.coords(rid, cx - r, cy - r, cx + r, cy + r)
|
|
123
|
+
# 亮度和线宽随呼吸变化:外环最淡,形成层次
|
|
124
|
+
base = (0.95, 0.6, 0.35)[i]
|
|
125
|
+
a = base * (0.25 + 0.75 * t)
|
|
126
|
+
c.itemconfigure(rid, outline=self._blend(AMBER, BG, a),
|
|
127
|
+
width=1 if i else 2)
|
|
128
|
+
self.root.after(45, self._animate)
|
|
129
|
+
|
|
130
|
+
@staticmethod
|
|
131
|
+
def _blend(fg: str, bg: str, a: float) -> str:
|
|
132
|
+
"""把 fg 按 alpha 混到 bg 上(tkinter 不支持 rgba,只能算成实色)。"""
|
|
133
|
+
def rgb(h):
|
|
134
|
+
h = h.lstrip("#")
|
|
135
|
+
return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
|
|
136
|
+
f, b = rgb(fg), rgb(bg)
|
|
137
|
+
out = tuple(round(b[i] + (f[i] - b[i]) * max(0.0, min(1.0, a))) for i in range(3))
|
|
138
|
+
return "#%02x%02x%02x" % out
|
|
139
|
+
|
|
140
|
+
# ---------------------------------------------------------------- 外部控制
|
|
141
|
+
def set_text(self, text: str) -> None:
|
|
142
|
+
"""换一句状态说明(例如"面板已就绪,正在打开浏览器…")。"""
|
|
143
|
+
self._text = text
|
|
144
|
+
try:
|
|
145
|
+
if self.canvas is not None:
|
|
146
|
+
self.canvas.itemconfigure(self.txt, text=text)
|
|
147
|
+
except Exception:
|
|
148
|
+
pass
|
|
149
|
+
|
|
150
|
+
def close(self) -> None:
|
|
151
|
+
self._closed = True
|
|
152
|
+
try:
|
|
153
|
+
if self.root is not None:
|
|
154
|
+
self.root.after(0, self._destroy)
|
|
155
|
+
except Exception:
|
|
156
|
+
pass
|
|
157
|
+
|
|
158
|
+
def _destroy(self) -> None:
|
|
159
|
+
try:
|
|
160
|
+
self.root.destroy()
|
|
161
|
+
except Exception:
|
|
162
|
+
pass
|
|
163
|
+
|
|
164
|
+
def run(self) -> None:
|
|
165
|
+
"""跑界面事件循环,直到 close() 把窗口销毁。没有 tk 时立即返回。"""
|
|
166
|
+
if self.root is None:
|
|
167
|
+
return
|
|
168
|
+
try:
|
|
169
|
+
self.root.mainloop()
|
|
170
|
+
except Exception:
|
|
171
|
+
pass
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def available() -> bool:
|
|
175
|
+
"""tkinter 能不能用(拿不到就不装加载窗,静默退化成原来的行为)。"""
|
|
176
|
+
try:
|
|
177
|
+
r = tk.Tk()
|
|
178
|
+
r.destroy()
|
|
179
|
+
return True
|
|
180
|
+
except Exception:
|
|
181
|
+
return False
|
|
@@ -448,7 +448,7 @@ def rollback_persona_snapshot(version: int) -> dict | None:
|
|
|
448
448
|
if not target or not isinstance(target.get("persona"), dict):
|
|
449
449
|
return None
|
|
450
450
|
p = target["persona"]
|
|
451
|
-
# ★ 快照 +
|
|
451
|
+
# ★ 快照 + 覆写必须在**同一把锁内**(审计 persona.py:457):
|
|
452
452
|
# 原来 `load_persona()`(读当前值做"回滚前快照")在锁外,`save_persona(p)`
|
|
453
453
|
# 内部才有锁——两步之间的窗口里若有 update_persona / 面板保存写进来,
|
|
454
454
|
# 紧接着的整份覆写会把那次写入静默抹掉(回滚本身就是全量覆盖,最容易吃掉并发写)。
|
|
@@ -942,12 +942,22 @@ PERSONA_SNAP_KEEP = 40 # 快照保留上限,防止无限增长
|
|
|
942
942
|
|
|
943
943
|
|
|
944
944
|
def _prune_snapshots(keep: int = PERSONA_SNAP_KEEP) -> None:
|
|
945
|
-
"""只保留最近 keep
|
|
945
|
+
"""只保留最近 keep 张快照,多余的**移入 .pruned/**(不会动刚拍的这张)。
|
|
946
|
+
|
|
947
|
+
⚠ 原实现直接 `unlink()`——违反项目自己的"只移不删"规矩
|
|
948
|
+
(safety_net 快照、cmd_backup 修剪都已改成移入 .pruned/)。
|
|
949
|
+
人格快照被硬删意味着回滚链被截断且不可找回:用户想回滚某次人格改动时,
|
|
950
|
+
可能发现那份已经被悄悄删掉了(审计 persona.py:944)。
|
|
951
|
+
"""
|
|
952
|
+
import shutil as _sh
|
|
946
953
|
rows = persona_snapshots(10000)
|
|
954
|
+
pruned_dir = PERSONA_SNAP_DIR / ".pruned"
|
|
947
955
|
for r in rows[keep:]:
|
|
956
|
+
src = PERSONA_SNAP_DIR / f"{r['name']}.json"
|
|
948
957
|
try:
|
|
949
|
-
(
|
|
950
|
-
|
|
958
|
+
pruned_dir.mkdir(parents=True, exist_ok=True)
|
|
959
|
+
_sh.move(str(src), str(pruned_dir / src.name))
|
|
960
|
+
except (OSError, _sh.Error):
|
|
951
961
|
pass
|
|
952
962
|
|
|
953
963
|
|
|
@@ -2264,7 +2274,11 @@ def self_model_autosink() -> dict:
|
|
|
2264
2274
|
for r in _mem.load_all():
|
|
2265
2275
|
if not isinstance(r, dict) or not r.get("correction"):
|
|
2266
2276
|
continue
|
|
2267
|
-
|
|
2277
|
+
# 记忆记录没有 confidence 字段(只有教训库有)。默认值写成 1.0
|
|
2278
|
+
# 会让每条都被 continue 掉 → self_model.limitations 永不积累,
|
|
2279
|
+
# 这条来源等于死代码(审计 persona.py:2264)。
|
|
2280
|
+
# 改成默认 0.0:没标置信度就当"低置信",照常纳入短板。
|
|
2281
|
+
if _num(r.get("confidence"), 0.0) >= 0.5:
|
|
2268
2282
|
continue
|
|
2269
2283
|
t = str(r.get("text") or r.get("summary") or "").strip()
|
|
2270
2284
|
if t:
|
|
@@ -174,12 +174,17 @@ def _counts_of(targets) -> dict:
|
|
|
174
174
|
return out
|
|
175
175
|
|
|
176
176
|
|
|
177
|
-
def verify(names=None, allow_shrink=()) -> dict:
|
|
177
|
+
def verify(names=None, allow_shrink=(), baseline=None) -> dict:
|
|
178
178
|
"""写后校验:文件在、每行可解析、没被截断、哈希链字段齐。
|
|
179
179
|
|
|
180
180
|
返回 {"ok": bool, "issues": [...], "counts": {...}}。
|
|
181
|
-
|
|
181
|
+
|
|
182
|
+
`baseline`:写入**前**的行数 {文件名: 行数}。给了它才做"行数减少"检查;
|
|
183
|
+
`allow_shrink` 里列出的文件名允许减少(删除类操作显式声明)。
|
|
184
|
+
**注意**:`allow_shrink` 原来是死参数——docstring 承诺了这个能力,函数体
|
|
185
|
+
从未引用它(审计 safety_net.py:177)。现在由 guarded_write 传 baseline 生效。
|
|
182
186
|
"""
|
|
187
|
+
allow_shrink = set(allow_shrink or ())
|
|
183
188
|
targets = _resolve(names or PROTECTED)
|
|
184
189
|
issues = []
|
|
185
190
|
counts = {}
|
|
@@ -191,6 +196,14 @@ def verify(names=None, allow_shrink=()) -> dict:
|
|
|
191
196
|
continue
|
|
192
197
|
lines = [ln for ln in raw.splitlines() if ln.strip()]
|
|
193
198
|
counts[p.name] = len(lines)
|
|
199
|
+
# 行数减少检查(只在给了 baseline 时做):
|
|
200
|
+
# 没声明 allow_shrink 的文件少行 = 大概率丢数据,必须报出来。
|
|
201
|
+
if baseline and p.name in baseline and p.name not in allow_shrink:
|
|
202
|
+
_before = int(baseline.get(p.name) or 0)
|
|
203
|
+
if _before > 0 and len(lines) < _before:
|
|
204
|
+
issues.append(
|
|
205
|
+
f"{p.name} 行数从 {_before} 减到 {len(lines)}"
|
|
206
|
+
"——疑似丢记录(删除类写入请显式声明 allow_shrink)")
|
|
194
207
|
if raw and not raw.endswith("\n"):
|
|
195
208
|
issues.append(f"{p.name} 末行没有换行——可能被截断")
|
|
196
209
|
if p.name.endswith(".jsonl"):
|
|
@@ -331,6 +344,19 @@ def guarded_write(reason: str, writer, names=None, allow_shrink=()) -> dict:
|
|
|
331
344
|
但调用方应当把 ok 当回事(记日志/提示用户)。
|
|
332
345
|
"""
|
|
333
346
|
names = names or PROTECTED
|
|
347
|
+
# 写入前记录行数,供 verify 做"行数减少"检查(#28 的实现前提)
|
|
348
|
+
_baseline = {}
|
|
349
|
+
try:
|
|
350
|
+
for _p in _resolve(names):
|
|
351
|
+
try:
|
|
352
|
+
_baseline[_p.name] = len([
|
|
353
|
+
ln for ln in _p.read_text(encoding="utf-8",
|
|
354
|
+
errors="replace").splitlines()
|
|
355
|
+
if ln.strip()])
|
|
356
|
+
except OSError:
|
|
357
|
+
pass
|
|
358
|
+
except Exception: # noqa: BLE001
|
|
359
|
+
_baseline = {}
|
|
334
360
|
snap = snapshot(reason, names)
|
|
335
361
|
err = None
|
|
336
362
|
try:
|
|
@@ -358,7 +384,7 @@ def guarded_write(reason: str, writer, names=None, allow_shrink=()) -> dict:
|
|
|
358
384
|
pass
|
|
359
385
|
return report
|
|
360
386
|
if _verify_enabled():
|
|
361
|
-
v = verify(names, allow_shrink=allow_shrink)
|
|
387
|
+
v = verify(names, allow_shrink=allow_shrink, baseline=_baseline)
|
|
362
388
|
report["verified"] = v["counts"]
|
|
363
389
|
if not v["ok"]:
|
|
364
390
|
report["ok"] = False
|