lingshu-skill 3.98.0 → 4.1.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 +34 -0
- package/README.md +1 -1
- package/SKILL.md +1 -1
- package/assets/panel.html +122 -0
- package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +18 -0
- package/package.json +1 -1
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +8 -7
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +34 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +122 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +47 -8
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +11 -2
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_data.py +113 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +37 -0
- package/scripts/checkpoint.py +47 -8
- package/scripts/cli.py +11 -2
- package/scripts/panel_data.py +113 -0
- package/scripts/panel_server.py +37 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,39 @@
|
|
|
1
1
|
# 更新日志
|
|
2
2
|
|
|
3
|
+
## v4.01(2026-11-24)
|
|
4
|
+
|
|
5
|
+
> 主题:**checkpoint 把瞬时故障说成了业务结论**——顺手修掉那个"偶发 flake"。
|
|
6
|
+
|
|
7
|
+
- **根因(不是测试的错)**:`checkpoint._git()` 用 `except Exception: return ""` 把**瞬时占用**(杀软/索引器 WinError 5/32/33/145)与 **20s 超时**跟"这不是 git 仓库"混成一个空串;`collect()` 见空 root 就 `return None`,于是 `checkpoint()` 返回 `{"ok": False, "reason": "不是 git 仓库"}`——**用户会以为路径给错了**。测试里 `assert data["ok"]` 没带消息,所以表现为"偶发失败 + 空错误信息"(`io_retry_util` 按设计不重试 AssertionError,重试救不了)。
|
|
8
|
+
- **修**:
|
|
9
|
+
- `_git()`:瞬时错误重试 3 次(退避 0.3/0.6s),仍失败抛 `GitUnavailable`;**非零退出码**(真不是仓库/路径不对)仍返回空串、不重试,语义不变。
|
|
10
|
+
- `collect()`:空 root 且 `.git` 存在 → 抛 `GitUnavailable`("仓库存在但取证失败,请稍后重试"),不再谎报"不是仓库"。
|
|
11
|
+
- `checkpoint()`:捕获后返回 `transient: True` + 可重试理由,与"不是 git 仓库"明确区分。
|
|
12
|
+
- 测试:断言补上 `returncode / stdout / stderr / home / repo` 上下文,以后再 flake 能直接定位。
|
|
13
|
+
- 瞬时判定同时看 `winerror` 与 `errno`(纯 `OSError(32)` 没有 `winerror`)——首版漏了,靠回归测试抓出。
|
|
14
|
+
- **验证**:新增 5 项回归(重试次数=3 / 非零退出不重试 / `.git` 存在但 git 失败要抛 / `transient` 标记且理由不含"不是仓库" / 正常仓库仍能写);`test_checkpoint.py` 6/6;全量 65/65。
|
|
15
|
+
|
|
16
|
+
## v3.99(2026-11-23)
|
|
17
|
+
|
|
18
|
+
> 主题:**面板「数据」页(备份/恢复)** + **一个备份修剪 bug 的修复(含一次数据损失事故,如实记录)**。
|
|
19
|
+
|
|
20
|
+
### ⚠️ 事故说明(先读)
|
|
21
|
+
|
|
22
|
+
本版修复了 `cmd_backup` 的一个修剪 bug,而我在自测这个功能时**误删了你的真实备份**:
|
|
23
|
+
|
|
24
|
+
- **bug**:修剪用 `glob("brain-memory_*.zip*")`,同时命中 `.zip` 和 `.zip.sha256`,于是 `keep=N` 实际只保留约 N/2 份真备份。
|
|
25
|
+
- **事故**:我测面板备份时用了 `keep=5` 且**没隔离备份目录**(`safety.pick_backup_dir()` 是跨卷选址,与 `BRAIN_MEMORY_HOME` 无关),于是写进真实的 `D:\brain-memory-backups` 并触发修剪,**删掉 2~3 份真实备份**;`unlink()` 不进回收站,**不可恢复**。现存 3 份(含我测试留下的 1 份 3 KB 空库备份,可自行删)。
|
|
26
|
+
- **防复发**:修剪只数真备份并连带清 `.sha256`;面板备份默认 `keep=0`(不修剪);所有备份相关测试强制先设 `BRAIN_MEMORY_BACKUP_DIR` 到临时目录。
|
|
27
|
+
|
|
28
|
+
### 新功能:面板「数据」页
|
|
29
|
+
|
|
30
|
+
- 面板此前**没有备份/恢复入口**(只有 CLI)。新增 `scripts/panel_data.py`:备份列表(大小/时间/sha/"疑似空壳"标记)、立即备份、从备份恢复、数据规模概览。
|
|
31
|
+
- 复用 CLI 的 `cmd_backup`/`cmd_restore`(完整性校验、恢复前自动备份、坏包回退都在),不另写打包逻辑。
|
|
32
|
+
- `GET /api/data`、`POST /api/data/backup`、`POST /api/data/restore`(只取文件名防穿越,空壳备份禁用恢复)。
|
|
33
|
+
- 前端:规模卡片 + 备份历史 + 立即备份 / 恢复(二次确认,提示会先备份现状)。
|
|
34
|
+
|
|
35
|
+
验证:`tests/test_panel_data.py` 6/6(目录隔离/不修剪/keep 只数真备份/路径穿越拒绝/恢复成功且保留现状备份/空壳标记);实跑面板 GET+POST 全通;无头 Edge 截图。
|
|
36
|
+
|
|
3
37
|
## v3.98(2026-11-23)
|
|
4
38
|
|
|
5
39
|
> 主题:**设置页上线后的自审修复**——三处真缺陷,其中一处是安全问题。
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> 名字取自《黄帝内经》:**算力给思考,人格给灵魂,记忆给生命。**
|
|
4
4
|
|
|
5
|
-
> 当前版本 **
|
|
5
|
+
> 当前版本 **v4.01**(变更见 [CHANGELOG.md](CHANGELOG.md))
|
|
6
6
|
|
|
7
7
|
> 🔁 **双仓库镜像**:GitHub(主)与 Gitee(镜像)保持同步——[gitee.com/htmcwy_0/lingshu-skill](https://gitee.com/htmcwy_0/lingshu-skill)。灵枢的更新检查会探测两边最新提交,**谁更新就自动从谁拉取**;任一边不可达(Gitee 匿名风控 / GitHub 限额)时走另一边兜底。
|
|
8
8
|
|
package/SKILL.md
CHANGED
package/assets/panel.html
CHANGED
|
@@ -353,6 +353,7 @@
|
|
|
353
353
|
<div class="nav-label">系统</div>
|
|
354
354
|
<button data-tab="logs" aria-label="日志"><span class="ic">☰</span><span>日志</span></button>
|
|
355
355
|
<button data-tab="diag" aria-label="自诊断"><span class="ic">✚</span><span>诊断</span></button>
|
|
356
|
+
<button data-tab="data" aria-label="数据"><span class="ic">⛁</span><span>数据</span></button>
|
|
356
357
|
<button data-tab="settings" aria-label="设置"><span class="ic">⚒</span><span>设置</span></button>
|
|
357
358
|
</div>
|
|
358
359
|
</nav>
|
|
@@ -1018,6 +1019,27 @@
|
|
|
1018
1019
|
</div>
|
|
1019
1020
|
</section>
|
|
1020
1021
|
|
|
1022
|
+
<section class="view" id="view-data">
|
|
1023
|
+
<div class="card" style="margin-bottom:14px">
|
|
1024
|
+
<div class="row" style="flex-wrap:wrap">
|
|
1025
|
+
<div>
|
|
1026
|
+
<h2 style="margin-bottom:4px">数据</h2>
|
|
1027
|
+
<div class="sub">备份与恢复。备份是整个记忆库的 zip,恢复前会自动把现状再备份一份。</div>
|
|
1028
|
+
</div>
|
|
1029
|
+
<div class="row" style="margin-left:auto">
|
|
1030
|
+
<button class="ghost" id="btn-data-refresh">刷新</button>
|
|
1031
|
+
<button id="btn-data-backup">立即备份</button>
|
|
1032
|
+
</div>
|
|
1033
|
+
</div>
|
|
1034
|
+
<div id="data-stats" style="margin-top:12px"><div class="empty">加载中…</div></div>
|
|
1035
|
+
</div>
|
|
1036
|
+
<div class="card">
|
|
1037
|
+
<h2 style="margin-bottom:2px">备份历史</h2>
|
|
1038
|
+
<div class="sub" id="data-dir" style="margin-bottom:10px"></div>
|
|
1039
|
+
<div id="data-backups"><div class="empty">加载中…</div></div>
|
|
1040
|
+
</div>
|
|
1041
|
+
</section>
|
|
1042
|
+
|
|
1021
1043
|
<section class="view" id="view-settings">
|
|
1022
1044
|
<div class="card" style="margin-bottom:14px">
|
|
1023
1045
|
<div class="row" style="flex-wrap:wrap">
|
|
@@ -2908,6 +2930,83 @@ async function runInject(){
|
|
|
2908
2930
|
}
|
|
2909
2931
|
}
|
|
2910
2932
|
|
|
2933
|
+
// ---------------------------------------------------------------- 数据页(备份/恢复)
|
|
2934
|
+
// 恢复是不可逆操作:二次确认 + 明确提示"会先自动备份现状"。
|
|
2935
|
+
// 备份默认**不修剪**历史(keep=0),手动点一下不该静默删旧备份。
|
|
2936
|
+
let _dataLoaded = false;
|
|
2937
|
+
|
|
2938
|
+
function _fmtSize(n){
|
|
2939
|
+
const v = Number(n) || 0;
|
|
2940
|
+
if (v >= 1048576) return (v / 1048576).toFixed(1) + " MB";
|
|
2941
|
+
if (v >= 1024) return (v / 1024).toFixed(0) + " KB";
|
|
2942
|
+
return v + " B";
|
|
2943
|
+
}
|
|
2944
|
+
|
|
2945
|
+
async function renderData(force){
|
|
2946
|
+
const statsBox = $("data-stats"), listBox = $("data-backups"), dirBox = $("data-dir");
|
|
2947
|
+
if (!statsBox || !listBox) return;
|
|
2948
|
+
if (_dataLoaded && !force) return;
|
|
2949
|
+
listBox.innerHTML = '<div class="empty">加载中…</div>';
|
|
2950
|
+
let d;
|
|
2951
|
+
try {
|
|
2952
|
+
d = await api("/api/data");
|
|
2953
|
+
} catch (e) {
|
|
2954
|
+
listBox.innerHTML = `<div class="empty">读取失败:${esc(e.message || String(e))}</div>`;
|
|
2955
|
+
return;
|
|
2956
|
+
}
|
|
2957
|
+
const st = (d && d.stats) || {};
|
|
2958
|
+
const layers = st.layers || {};
|
|
2959
|
+
const rows = Object.entries(layers).filter(([, v]) => v && (v.count || v.bytes));
|
|
2960
|
+
statsBox.innerHTML = rows.length
|
|
2961
|
+
? `<div class="metrics">${rows.map(([k, v]) =>
|
|
2962
|
+
`<div class="metric"><div class="k">${esc(k)}</div><div class="v">${v.count}</div>`
|
|
2963
|
+
+ `<div class="sub">${_fmtSize(v.bytes)}</div></div>`).join("")}`
|
|
2964
|
+
+ `<div class="metric"><div class="k">合计</div><div class="v">${_fmtSize(st.total_bytes)}</div></div></div>`
|
|
2965
|
+
: '<div class="empty">记忆库还是空的。</div>';
|
|
2966
|
+
|
|
2967
|
+
const b = (d && d.backups) || {};
|
|
2968
|
+
if (dirBox) dirBox.textContent = b.dir ? `目录:${b.dir}` : "";
|
|
2969
|
+
const items = b.items || [];
|
|
2970
|
+
if (!items.length){
|
|
2971
|
+
listBox.innerHTML = '<div class="empty">还没有备份。点右上「立即备份」生成第一份。</div>';
|
|
2972
|
+
_dataLoaded = true;
|
|
2973
|
+
return;
|
|
2974
|
+
}
|
|
2975
|
+
listBox.innerHTML = `<div class="list">${items.map((it, i) => `
|
|
2976
|
+
<div class="row" style="align-items:center;gap:10px;padding:8px 0;border-bottom:1px solid rgba(255,255,255,.05)">
|
|
2977
|
+
<div style="flex:1;min-width:0">
|
|
2978
|
+
<div style="font-size:13px">${esc(it.name)}
|
|
2979
|
+
${it.suspicious ? '<span class="set-badge">疑似空壳</span>' : ""}
|
|
2980
|
+
${it.has_sha ? "" : '<span class="set-badge">无校验</span>'}
|
|
2981
|
+
</div>
|
|
2982
|
+
<div class="sub">${esc(it.mtime_text)} · ${_fmtSize(it.size)}</div>
|
|
2983
|
+
</div>
|
|
2984
|
+
<button class="ghost" data-restore="${esc(it.name)}" ${it.suspicious ? "disabled" : ""}>恢复</button>
|
|
2985
|
+
</div>`).join("")}</div>`;
|
|
2986
|
+
listBox.onclick = async (ev) => {
|
|
2987
|
+
const btn = ev.target.closest("[data-restore]");
|
|
2988
|
+
if (!btn) return;
|
|
2989
|
+
const name = btn.dataset.restore;
|
|
2990
|
+
if (!confirm(`从「${name}」恢复记忆库?\n\n恢复前会自动把当前状态再备份一份。\n恢复后建议重启面板与新会话。`)) return;
|
|
2991
|
+
btn.disabled = true;
|
|
2992
|
+
try {
|
|
2993
|
+
const r = await api("/api/data/restore", {
|
|
2994
|
+
method: "POST",
|
|
2995
|
+
headers: {"Content-Type": "application/json"},
|
|
2996
|
+
body: JSON.stringify({name}),
|
|
2997
|
+
});
|
|
2998
|
+
if (r && r.ok) toast(`已从 ${name} 恢复`);
|
|
2999
|
+
else toast("恢复失败", true);
|
|
3000
|
+
} catch (e) {
|
|
3001
|
+
toast(e.message || "恢复失败", true);
|
|
3002
|
+
} finally {
|
|
3003
|
+
btn.disabled = false;
|
|
3004
|
+
renderData(true);
|
|
3005
|
+
}
|
|
3006
|
+
};
|
|
3007
|
+
_dataLoaded = true;
|
|
3008
|
+
}
|
|
3009
|
+
|
|
2911
3010
|
// ---------------------------------------------------------------- 设置页
|
|
2912
3011
|
// 后端只允许改 panel_settings.py 白名单里的键(带类型/范围/枚举校验);
|
|
2913
3012
|
// 面板这边只负责渲染 + 保存,不在前端重复一套校验(两边不一致才是灾难)。
|
|
@@ -3018,6 +3117,7 @@ function switchTab(tab){
|
|
|
3018
3117
|
diag: ["自诊断", "归因异常:死链 / 冲突未裁决 / 数据膨胀 / 来源归属"],
|
|
3019
3118
|
store: ["插件商店", "AstrBot / cordis 等宿主适配插件,点安装导出后接入宿主"],
|
|
3020
3119
|
ext: ["本地能力", "本地能力一键安装:Ollama 语义召回等"],
|
|
3120
|
+
data: ["数据", "备份与恢复:整个记忆库打包成 zip,恢复前自动备份现状"],
|
|
3021
3121
|
settings: ["设置", "开关与数值:直接写进 config.json,改完即刻生效"]
|
|
3022
3122
|
};
|
|
3023
3123
|
const t = titles[tab] || titles.overview; // 未知 tab(旧缓存/坏链接)兜底,别在标题上抛 TypeError
|
|
@@ -3027,6 +3127,7 @@ function switchTab(tab){
|
|
|
3027
3127
|
if (tab === "store") renderStore();
|
|
3028
3128
|
if (tab === "ext") loadExtensionOllama();
|
|
3029
3129
|
if (tab === "settings") renderSettings();
|
|
3130
|
+
if (tab === "data") renderData();
|
|
3030
3131
|
if (tab === "graph") loadGraph(Number($("graph-limit").value || 300));
|
|
3031
3132
|
else { stopPhysics(); stopGraphAnim(); } // 离开联想页即停模拟,不空耗 CPU
|
|
3032
3133
|
if (tab === "logs") loadLogs();
|
|
@@ -3133,6 +3234,27 @@ async function loadExtensionOllama(){
|
|
|
3133
3234
|
|
|
3134
3235
|
$("btn-ext-refresh").addEventListener("click", loadExtensionOllama);
|
|
3135
3236
|
$("btn-cfg-reload").addEventListener("click", () => renderSettings(true));
|
|
3237
|
+
$("btn-data-refresh").addEventListener("click", () => renderData(true));
|
|
3238
|
+
$("btn-data-backup").addEventListener("click", async (ev) => {
|
|
3239
|
+
const btn = ev.currentTarget;
|
|
3240
|
+
btn.disabled = true;
|
|
3241
|
+
try {
|
|
3242
|
+
const r = await api("/api/data/backup", {
|
|
3243
|
+
method: "POST",
|
|
3244
|
+
headers: {"Content-Type": "application/json"},
|
|
3245
|
+
body: JSON.stringify({}),
|
|
3246
|
+
});
|
|
3247
|
+
if (r && r.ok) {
|
|
3248
|
+
const n = (r.created && r.created.name) || "新备份";
|
|
3249
|
+
toast(`已备份:${n}`);
|
|
3250
|
+
} else toast("备份失败", true);
|
|
3251
|
+
} catch (e) {
|
|
3252
|
+
toast(e.message || "备份失败", true);
|
|
3253
|
+
} finally {
|
|
3254
|
+
btn.disabled = false;
|
|
3255
|
+
renderData(true);
|
|
3256
|
+
}
|
|
3257
|
+
});
|
|
3136
3258
|
|
|
3137
3259
|
// 告警卡「去处理 →」链接:切到对应页签(事件委托,卡片内容每次重渲染)
|
|
3138
3260
|
document.addEventListener("click", (e) => {
|
|
@@ -402,6 +402,24 @@ startup 注入的记忆块与 cron 的瞬态提醒**同名**,于是 cron 的 p
|
|
|
402
402
|
- **② `panel_port` 是假开关**:`panel_server.py --port` 的 default 硬编码 `8765`,**不读 config**,设置页改端口完全无效。**修**:`--port` 缺省时读 `config.json` 的 `panel_port`(含 1~65535 校验),实测设 18799 后服务确实起在 18799。
|
|
403
403
|
- **③ `extensions_enabled` 不在 DEFAULT_CONFIG**:只有读取方 `.get(key, False)` 兜底,设置页拿不到默认值(显示 undefined)、`unset` 后 UI 语义也不明确。**修**:补进 `DEFAULT_CONFIG`(默认 False)。
|
|
404
404
|
|
|
405
|
+
69. **【已修 v3.99,含一次数据损失事故】备份修剪 bug 把 .sha256 也算进 keep**:
|
|
406
|
+
- **bug**:`cli.cmd_backup` 修剪用 `out_dir.glob("brain-memory_*.zip*")`,这个 glob **同时命中 `.zip` 和 `.zip.sha256`**,于是 `keep=N` 实际只保留约 N/2 份真备份,还会留下"有 sha 无 zip"的孤儿。
|
|
407
|
+
- **事故**:我在测面板备份时用了 `keep=5`,且**没有隔离备份目录**——`safety.pick_backup_dir()` 是跨卷选址、与 HOME 无关,结果写到了真实的 `D:\brain-memory-backups` 并触发修剪,**删掉了 2~3 份真实备份**(`20261121_141450`、`20261120_204615` 等)。`p.unlink()` 不进回收站,**不可恢复**。目录现在只剩 3 份(含我测试留下的 1 份 3 KB 空库备份)。
|
|
408
|
+
- **修**:① 修剪只数真备份(`.zip` / `.zip.enc`),并连带清掉对应的 `.sha256`,不留孤儿;② 面板 `make_backup` 默认 `keep=0`(**不修剪**)——手动点一下备份不该静默删历史;③ 所有涉及备份的测试/验证**必须先设 `BRAIN_MEMORY_BACKUP_DIR` 到临时目录**,这条写进测试文件头注释。
|
|
409
|
+
- **教训**:写盘类功能的自测,**先隔离目标目录再动手**;`pick_backup_dir` 这种"跨卷选址"的默认值不能假设它跟着 HOME 走。
|
|
410
|
+
|
|
411
|
+
70. **【新功能 v3.99】面板「数据」页**:面板此前**完全没有备份/恢复入口**(75 个 CLI 子命令里 backup/restore 只有命令行能做),对记忆系统是最大的可用性缺口。
|
|
412
|
+
- `scripts/panel_data.py`(新):备份列表(大小/时间/是否有 sha/"疑似空壳"标记)、立即备份、从备份恢复、数据规模概览。**复用 CLI 的 `cmd_backup`/`cmd_restore`**(它们已做完整性校验、恢复前自动备份现状、坏包回退),不另写一套打包逻辑。
|
|
413
|
+
- `GET /api/data`(概览+列表)、`POST /api/data/backup`、`POST /api/data/restore`(**只取文件名,杜绝 `../` 穿越**;空壳备份前端禁用恢复按钮)。
|
|
414
|
+
- 前端「数据」页:规模卡片 + 备份历史列表 + 立即备份/恢复(恢复二次确认并提示"会先自动备份现状")。
|
|
415
|
+
|
|
416
|
+
71. **【已修 v4.01】`test_checkpoint.py::test_cli_json_roundtrip` 全套里偶发失败**:单跑稳定(压测 10/10),按全套顺序连跑也难复现——**根因不是测试,是生产代码把瞬时故障说成了业务结论**:
|
|
417
|
+
- `checkpoint._git()` 原来是 `except Exception: return ""`,把**瞬时占用(杀软/索引器 WinError 5/32/33/145)、20s 超时**和"这不是 git 仓库"混成一个空串;
|
|
418
|
+
- `collect()` 见空 root 一律 `return None`,`checkpoint()` 于是返回 `{"ok": False, "reason": "不是 git 仓库"}`;
|
|
419
|
+
- 测试断言 `assert data["ok"]` 没带消息 → flake 时只有空 AssertionError,排查无门(`io_retry_util` 按设计**不重试 AssertionError**,所以重试也救不了)。
|
|
420
|
+
**修**:① `_git()` 对瞬时错误重试 3 次(退避 0.3/0.6s),仍失败抛 `GitUnavailable`;非零退出码(真不是仓库)仍返回空串、不重试;② `collect()` 见空 root 且 `.git` 存在 → 抛 `GitUnavailable`("仓库存在但取证失败,请稍后重试"),不再谎报"不是仓库";③ `checkpoint()` 捕获后返回 `transient: True` + 可重试理由;④ 测试断言补上 returncode/stdout/stderr/home/repo 上下文。
|
|
421
|
+
**副产品**:`OSError(32)` 的 `errno` 也纳入瞬时判定(Windows 原生错误才带 `winerror`,纯 OSError 没有)——首版修复漏了这点,靠回归测试抓出来。
|
|
422
|
+
|
|
405
423
|
## 三、已知问题与风险
|
|
406
424
|
|
|
407
425
|
| # | 现象 | 影响 | 处置 |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lingshu-skill",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.01.0",
|
|
4
4
|
"description": "Brain-inspired persistent memory, persona and growth system for AI coding agents. Local-only, zero-dependency Python. Requires Python 3.10+.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"PATCH_NOTES.md": "9296e524f743f358fd11115598398a754cfd69534526dde9c8ad85f14a418f89",
|
|
3
3
|
"README.md": "3d634d743b085eebd2cbb5dd3a00edfa728ed23947e20cc29e7c3b29087ec043",
|
|
4
|
-
"engine/CHANGELOG.md": "
|
|
5
|
-
"engine/README.md": "
|
|
4
|
+
"engine/CHANGELOG.md": "aa01f6ecce5ac22052b70e8d077c755057009079df2d6d185b7a60c51f3df779",
|
|
5
|
+
"engine/README.md": "ac0092153301be772e994998cadce599a1770ca4e4bfc174571234553062303a",
|
|
6
6
|
"engine/SKILL-lite.md": "04b87789232a0f7537c861c857888b4a0e947bcf92a461cbad5328af05361c58",
|
|
7
7
|
"engine/SKILL-tiny.md": "74e1955cc5bf4ec0ca28d52030f799f039283de27a52345a33ce783d6ee0c608",
|
|
8
|
-
"engine/SKILL.md": "
|
|
9
|
-
"engine/assets/panel.html": "
|
|
8
|
+
"engine/SKILL.md": "e70a1d9320f3a2f7365252853ae18ef791928c988a187c25049ece4f85c3de4c",
|
|
9
|
+
"engine/assets/panel.html": "37720c8277faa1a8b31e63765527cea357bf249bb038d97cb21445d032b3fc5d",
|
|
10
10
|
"engine/docs/commands.md": "63f43d24e64d6eab5b1f901756dff15f53b12a0c1a05fc029bfe82c9b01191e5",
|
|
11
11
|
"engine/docs/mechanics.md": "e8a6602a434ed5b78cac64a98884f65a6888eb48daa7a1c0be1f6c3984041b34",
|
|
12
12
|
"engine/docs/models.md": "596bc1a3414f2de5569dcb41a0c494acae7daa534efd5a91dbcc3c4cb308d695",
|
|
@@ -18,8 +18,8 @@
|
|
|
18
18
|
"engine/scripts/brain.py": "659be7e951fa6d1505ea5a7c1a7aff7fb3cb182633573a68ae135ccaa4b7f05f",
|
|
19
19
|
"engine/scripts/check_pressure_sync.py": "46d53934f17c7b740d0ec9fdbef9d2653850f6e01e883eedd70ff9a1527e869a",
|
|
20
20
|
"engine/scripts/check_tag.py": "6f0b8209dc2deebb1f9ec90d429e1fad60c040a2ec014a6406d9d3498faafd7f",
|
|
21
|
-
"engine/scripts/checkpoint.py": "
|
|
22
|
-
"engine/scripts/cli.py": "
|
|
21
|
+
"engine/scripts/checkpoint.py": "3a9292121042692dc872a865b6ee1c1e5f14c054791887e0791f19ccdb9638fb",
|
|
22
|
+
"engine/scripts/cli.py": "3c1d57da0e3eddfb1b903f80956e5b6eedebed4eddb3cc06275c2ec5f3dc9f90",
|
|
23
23
|
"engine/scripts/context_ab.py": "3d383f1fc16d328612825bbf731866fa427da0746490d027a0ddb719d210f1cb",
|
|
24
24
|
"engine/scripts/core.py": "c2ffdf91f406919e693f424ff31e591ed460dc78facf13aaeebfb66fe136b949",
|
|
25
25
|
"engine/scripts/dream.py": "c1ba3de2958fb045db7b6962a6dd0fcf70f225bfb4d372dd9c3e8584e4f759ce",
|
|
@@ -39,7 +39,8 @@
|
|
|
39
39
|
"engine/scripts/npm_prepack.py": "d62c491a6f9edfcab2dd465a995e72df879a61b4da26ae0fe76121c8adc77e02",
|
|
40
40
|
"engine/scripts/panel_build.py": "6394c1d74d203093e43b2106d7acca6e0ca9db61ca1cd6cd3a1616053653414b",
|
|
41
41
|
"engine/scripts/panel_cloud.py": "fff72888123d45bbf05ab329a06b2126f1c0b972c76283ecff32454bc4155c58",
|
|
42
|
-
"engine/scripts/
|
|
42
|
+
"engine/scripts/panel_data.py": "a26520394d8430364636f5ca0f1ed0a8d6ebc0ee6093f305878f7091df6622e2",
|
|
43
|
+
"engine/scripts/panel_server.py": "ffaebf42f12a51809cbd0dfd73aacf2b5ffd0207ecf6935859ce83ed13cef33d",
|
|
43
44
|
"engine/scripts/panel_settings.py": "327514abf90223dda039150839e6c33808652157c3de111eb8323ea7111dac04",
|
|
44
45
|
"engine/scripts/panels.py": "87dfce47693340af7c9bc6010a593256331e32c2e8504a0ac0745cf2ef992fd6",
|
|
45
46
|
"engine/scripts/persona.py": "fb748d2fb7b176d9dd0d7394de69ba4560da7f4205f62256477d3a69dcbdf0f5",
|
|
@@ -1,5 +1,39 @@
|
|
|
1
1
|
# 更新日志
|
|
2
2
|
|
|
3
|
+
## v4.01(2026-11-24)
|
|
4
|
+
|
|
5
|
+
> 主题:**checkpoint 把瞬时故障说成了业务结论**——顺手修掉那个"偶发 flake"。
|
|
6
|
+
|
|
7
|
+
- **根因(不是测试的错)**:`checkpoint._git()` 用 `except Exception: return ""` 把**瞬时占用**(杀软/索引器 WinError 5/32/33/145)与 **20s 超时**跟"这不是 git 仓库"混成一个空串;`collect()` 见空 root 就 `return None`,于是 `checkpoint()` 返回 `{"ok": False, "reason": "不是 git 仓库"}`——**用户会以为路径给错了**。测试里 `assert data["ok"]` 没带消息,所以表现为"偶发失败 + 空错误信息"(`io_retry_util` 按设计不重试 AssertionError,重试救不了)。
|
|
8
|
+
- **修**:
|
|
9
|
+
- `_git()`:瞬时错误重试 3 次(退避 0.3/0.6s),仍失败抛 `GitUnavailable`;**非零退出码**(真不是仓库/路径不对)仍返回空串、不重试,语义不变。
|
|
10
|
+
- `collect()`:空 root 且 `.git` 存在 → 抛 `GitUnavailable`("仓库存在但取证失败,请稍后重试"),不再谎报"不是仓库"。
|
|
11
|
+
- `checkpoint()`:捕获后返回 `transient: True` + 可重试理由,与"不是 git 仓库"明确区分。
|
|
12
|
+
- 测试:断言补上 `returncode / stdout / stderr / home / repo` 上下文,以后再 flake 能直接定位。
|
|
13
|
+
- 瞬时判定同时看 `winerror` 与 `errno`(纯 `OSError(32)` 没有 `winerror`)——首版漏了,靠回归测试抓出。
|
|
14
|
+
- **验证**:新增 5 项回归(重试次数=3 / 非零退出不重试 / `.git` 存在但 git 失败要抛 / `transient` 标记且理由不含"不是仓库" / 正常仓库仍能写);`test_checkpoint.py` 6/6;全量 65/65。
|
|
15
|
+
|
|
16
|
+
## v3.99(2026-11-23)
|
|
17
|
+
|
|
18
|
+
> 主题:**面板「数据」页(备份/恢复)** + **一个备份修剪 bug 的修复(含一次数据损失事故,如实记录)**。
|
|
19
|
+
|
|
20
|
+
### ⚠️ 事故说明(先读)
|
|
21
|
+
|
|
22
|
+
本版修复了 `cmd_backup` 的一个修剪 bug,而我在自测这个功能时**误删了你的真实备份**:
|
|
23
|
+
|
|
24
|
+
- **bug**:修剪用 `glob("brain-memory_*.zip*")`,同时命中 `.zip` 和 `.zip.sha256`,于是 `keep=N` 实际只保留约 N/2 份真备份。
|
|
25
|
+
- **事故**:我测面板备份时用了 `keep=5` 且**没隔离备份目录**(`safety.pick_backup_dir()` 是跨卷选址,与 `BRAIN_MEMORY_HOME` 无关),于是写进真实的 `D:\brain-memory-backups` 并触发修剪,**删掉 2~3 份真实备份**;`unlink()` 不进回收站,**不可恢复**。现存 3 份(含我测试留下的 1 份 3 KB 空库备份,可自行删)。
|
|
26
|
+
- **防复发**:修剪只数真备份并连带清 `.sha256`;面板备份默认 `keep=0`(不修剪);所有备份相关测试强制先设 `BRAIN_MEMORY_BACKUP_DIR` 到临时目录。
|
|
27
|
+
|
|
28
|
+
### 新功能:面板「数据」页
|
|
29
|
+
|
|
30
|
+
- 面板此前**没有备份/恢复入口**(只有 CLI)。新增 `scripts/panel_data.py`:备份列表(大小/时间/sha/"疑似空壳"标记)、立即备份、从备份恢复、数据规模概览。
|
|
31
|
+
- 复用 CLI 的 `cmd_backup`/`cmd_restore`(完整性校验、恢复前自动备份、坏包回退都在),不另写打包逻辑。
|
|
32
|
+
- `GET /api/data`、`POST /api/data/backup`、`POST /api/data/restore`(只取文件名防穿越,空壳备份禁用恢复)。
|
|
33
|
+
- 前端:规模卡片 + 备份历史 + 立即备份 / 恢复(二次确认,提示会先备份现状)。
|
|
34
|
+
|
|
35
|
+
验证:`tests/test_panel_data.py` 6/6(目录隔离/不修剪/keep 只数真备份/路径穿越拒绝/恢复成功且保留现状备份/空壳标记);实跑面板 GET+POST 全通;无头 Edge 截图。
|
|
36
|
+
|
|
3
37
|
## v3.98(2026-11-23)
|
|
4
38
|
|
|
5
39
|
> 主题:**设置页上线后的自审修复**——三处真缺陷,其中一处是安全问题。
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> 名字取自《黄帝内经》:**算力给思考,人格给灵魂,记忆给生命。**
|
|
4
4
|
|
|
5
|
-
> 当前版本 **
|
|
5
|
+
> 当前版本 **v4.01**(变更见 [CHANGELOG.md](CHANGELOG.md))
|
|
6
6
|
|
|
7
7
|
> 🔁 **双仓库镜像**:GitHub(主)与 Gitee(镜像)保持同步——[gitee.com/htmcwy_0/lingshu-skill](https://gitee.com/htmcwy_0/lingshu-skill)。灵枢的更新检查会探测两边最新提交,**谁更新就自动从谁拉取**;任一边不可达(Gitee 匿名风控 / GitHub 限额)时走另一边兜底。
|
|
8
8
|
|
|
@@ -353,6 +353,7 @@
|
|
|
353
353
|
<div class="nav-label">系统</div>
|
|
354
354
|
<button data-tab="logs" aria-label="日志"><span class="ic">☰</span><span>日志</span></button>
|
|
355
355
|
<button data-tab="diag" aria-label="自诊断"><span class="ic">✚</span><span>诊断</span></button>
|
|
356
|
+
<button data-tab="data" aria-label="数据"><span class="ic">⛁</span><span>数据</span></button>
|
|
356
357
|
<button data-tab="settings" aria-label="设置"><span class="ic">⚒</span><span>设置</span></button>
|
|
357
358
|
</div>
|
|
358
359
|
</nav>
|
|
@@ -1018,6 +1019,27 @@
|
|
|
1018
1019
|
</div>
|
|
1019
1020
|
</section>
|
|
1020
1021
|
|
|
1022
|
+
<section class="view" id="view-data">
|
|
1023
|
+
<div class="card" style="margin-bottom:14px">
|
|
1024
|
+
<div class="row" style="flex-wrap:wrap">
|
|
1025
|
+
<div>
|
|
1026
|
+
<h2 style="margin-bottom:4px">数据</h2>
|
|
1027
|
+
<div class="sub">备份与恢复。备份是整个记忆库的 zip,恢复前会自动把现状再备份一份。</div>
|
|
1028
|
+
</div>
|
|
1029
|
+
<div class="row" style="margin-left:auto">
|
|
1030
|
+
<button class="ghost" id="btn-data-refresh">刷新</button>
|
|
1031
|
+
<button id="btn-data-backup">立即备份</button>
|
|
1032
|
+
</div>
|
|
1033
|
+
</div>
|
|
1034
|
+
<div id="data-stats" style="margin-top:12px"><div class="empty">加载中…</div></div>
|
|
1035
|
+
</div>
|
|
1036
|
+
<div class="card">
|
|
1037
|
+
<h2 style="margin-bottom:2px">备份历史</h2>
|
|
1038
|
+
<div class="sub" id="data-dir" style="margin-bottom:10px"></div>
|
|
1039
|
+
<div id="data-backups"><div class="empty">加载中…</div></div>
|
|
1040
|
+
</div>
|
|
1041
|
+
</section>
|
|
1042
|
+
|
|
1021
1043
|
<section class="view" id="view-settings">
|
|
1022
1044
|
<div class="card" style="margin-bottom:14px">
|
|
1023
1045
|
<div class="row" style="flex-wrap:wrap">
|
|
@@ -2908,6 +2930,83 @@ async function runInject(){
|
|
|
2908
2930
|
}
|
|
2909
2931
|
}
|
|
2910
2932
|
|
|
2933
|
+
// ---------------------------------------------------------------- 数据页(备份/恢复)
|
|
2934
|
+
// 恢复是不可逆操作:二次确认 + 明确提示"会先自动备份现状"。
|
|
2935
|
+
// 备份默认**不修剪**历史(keep=0),手动点一下不该静默删旧备份。
|
|
2936
|
+
let _dataLoaded = false;
|
|
2937
|
+
|
|
2938
|
+
function _fmtSize(n){
|
|
2939
|
+
const v = Number(n) || 0;
|
|
2940
|
+
if (v >= 1048576) return (v / 1048576).toFixed(1) + " MB";
|
|
2941
|
+
if (v >= 1024) return (v / 1024).toFixed(0) + " KB";
|
|
2942
|
+
return v + " B";
|
|
2943
|
+
}
|
|
2944
|
+
|
|
2945
|
+
async function renderData(force){
|
|
2946
|
+
const statsBox = $("data-stats"), listBox = $("data-backups"), dirBox = $("data-dir");
|
|
2947
|
+
if (!statsBox || !listBox) return;
|
|
2948
|
+
if (_dataLoaded && !force) return;
|
|
2949
|
+
listBox.innerHTML = '<div class="empty">加载中…</div>';
|
|
2950
|
+
let d;
|
|
2951
|
+
try {
|
|
2952
|
+
d = await api("/api/data");
|
|
2953
|
+
} catch (e) {
|
|
2954
|
+
listBox.innerHTML = `<div class="empty">读取失败:${esc(e.message || String(e))}</div>`;
|
|
2955
|
+
return;
|
|
2956
|
+
}
|
|
2957
|
+
const st = (d && d.stats) || {};
|
|
2958
|
+
const layers = st.layers || {};
|
|
2959
|
+
const rows = Object.entries(layers).filter(([, v]) => v && (v.count || v.bytes));
|
|
2960
|
+
statsBox.innerHTML = rows.length
|
|
2961
|
+
? `<div class="metrics">${rows.map(([k, v]) =>
|
|
2962
|
+
`<div class="metric"><div class="k">${esc(k)}</div><div class="v">${v.count}</div>`
|
|
2963
|
+
+ `<div class="sub">${_fmtSize(v.bytes)}</div></div>`).join("")}`
|
|
2964
|
+
+ `<div class="metric"><div class="k">合计</div><div class="v">${_fmtSize(st.total_bytes)}</div></div></div>`
|
|
2965
|
+
: '<div class="empty">记忆库还是空的。</div>';
|
|
2966
|
+
|
|
2967
|
+
const b = (d && d.backups) || {};
|
|
2968
|
+
if (dirBox) dirBox.textContent = b.dir ? `目录:${b.dir}` : "";
|
|
2969
|
+
const items = b.items || [];
|
|
2970
|
+
if (!items.length){
|
|
2971
|
+
listBox.innerHTML = '<div class="empty">还没有备份。点右上「立即备份」生成第一份。</div>';
|
|
2972
|
+
_dataLoaded = true;
|
|
2973
|
+
return;
|
|
2974
|
+
}
|
|
2975
|
+
listBox.innerHTML = `<div class="list">${items.map((it, i) => `
|
|
2976
|
+
<div class="row" style="align-items:center;gap:10px;padding:8px 0;border-bottom:1px solid rgba(255,255,255,.05)">
|
|
2977
|
+
<div style="flex:1;min-width:0">
|
|
2978
|
+
<div style="font-size:13px">${esc(it.name)}
|
|
2979
|
+
${it.suspicious ? '<span class="set-badge">疑似空壳</span>' : ""}
|
|
2980
|
+
${it.has_sha ? "" : '<span class="set-badge">无校验</span>'}
|
|
2981
|
+
</div>
|
|
2982
|
+
<div class="sub">${esc(it.mtime_text)} · ${_fmtSize(it.size)}</div>
|
|
2983
|
+
</div>
|
|
2984
|
+
<button class="ghost" data-restore="${esc(it.name)}" ${it.suspicious ? "disabled" : ""}>恢复</button>
|
|
2985
|
+
</div>`).join("")}</div>`;
|
|
2986
|
+
listBox.onclick = async (ev) => {
|
|
2987
|
+
const btn = ev.target.closest("[data-restore]");
|
|
2988
|
+
if (!btn) return;
|
|
2989
|
+
const name = btn.dataset.restore;
|
|
2990
|
+
if (!confirm(`从「${name}」恢复记忆库?\n\n恢复前会自动把当前状态再备份一份。\n恢复后建议重启面板与新会话。`)) return;
|
|
2991
|
+
btn.disabled = true;
|
|
2992
|
+
try {
|
|
2993
|
+
const r = await api("/api/data/restore", {
|
|
2994
|
+
method: "POST",
|
|
2995
|
+
headers: {"Content-Type": "application/json"},
|
|
2996
|
+
body: JSON.stringify({name}),
|
|
2997
|
+
});
|
|
2998
|
+
if (r && r.ok) toast(`已从 ${name} 恢复`);
|
|
2999
|
+
else toast("恢复失败", true);
|
|
3000
|
+
} catch (e) {
|
|
3001
|
+
toast(e.message || "恢复失败", true);
|
|
3002
|
+
} finally {
|
|
3003
|
+
btn.disabled = false;
|
|
3004
|
+
renderData(true);
|
|
3005
|
+
}
|
|
3006
|
+
};
|
|
3007
|
+
_dataLoaded = true;
|
|
3008
|
+
}
|
|
3009
|
+
|
|
2911
3010
|
// ---------------------------------------------------------------- 设置页
|
|
2912
3011
|
// 后端只允许改 panel_settings.py 白名单里的键(带类型/范围/枚举校验);
|
|
2913
3012
|
// 面板这边只负责渲染 + 保存,不在前端重复一套校验(两边不一致才是灾难)。
|
|
@@ -3018,6 +3117,7 @@ function switchTab(tab){
|
|
|
3018
3117
|
diag: ["自诊断", "归因异常:死链 / 冲突未裁决 / 数据膨胀 / 来源归属"],
|
|
3019
3118
|
store: ["插件商店", "AstrBot / cordis 等宿主适配插件,点安装导出后接入宿主"],
|
|
3020
3119
|
ext: ["本地能力", "本地能力一键安装:Ollama 语义召回等"],
|
|
3120
|
+
data: ["数据", "备份与恢复:整个记忆库打包成 zip,恢复前自动备份现状"],
|
|
3021
3121
|
settings: ["设置", "开关与数值:直接写进 config.json,改完即刻生效"]
|
|
3022
3122
|
};
|
|
3023
3123
|
const t = titles[tab] || titles.overview; // 未知 tab(旧缓存/坏链接)兜底,别在标题上抛 TypeError
|
|
@@ -3027,6 +3127,7 @@ function switchTab(tab){
|
|
|
3027
3127
|
if (tab === "store") renderStore();
|
|
3028
3128
|
if (tab === "ext") loadExtensionOllama();
|
|
3029
3129
|
if (tab === "settings") renderSettings();
|
|
3130
|
+
if (tab === "data") renderData();
|
|
3030
3131
|
if (tab === "graph") loadGraph(Number($("graph-limit").value || 300));
|
|
3031
3132
|
else { stopPhysics(); stopGraphAnim(); } // 离开联想页即停模拟,不空耗 CPU
|
|
3032
3133
|
if (tab === "logs") loadLogs();
|
|
@@ -3133,6 +3234,27 @@ async function loadExtensionOllama(){
|
|
|
3133
3234
|
|
|
3134
3235
|
$("btn-ext-refresh").addEventListener("click", loadExtensionOllama);
|
|
3135
3236
|
$("btn-cfg-reload").addEventListener("click", () => renderSettings(true));
|
|
3237
|
+
$("btn-data-refresh").addEventListener("click", () => renderData(true));
|
|
3238
|
+
$("btn-data-backup").addEventListener("click", async (ev) => {
|
|
3239
|
+
const btn = ev.currentTarget;
|
|
3240
|
+
btn.disabled = true;
|
|
3241
|
+
try {
|
|
3242
|
+
const r = await api("/api/data/backup", {
|
|
3243
|
+
method: "POST",
|
|
3244
|
+
headers: {"Content-Type": "application/json"},
|
|
3245
|
+
body: JSON.stringify({}),
|
|
3246
|
+
});
|
|
3247
|
+
if (r && r.ok) {
|
|
3248
|
+
const n = (r.created && r.created.name) || "新备份";
|
|
3249
|
+
toast(`已备份:${n}`);
|
|
3250
|
+
} else toast("备份失败", true);
|
|
3251
|
+
} catch (e) {
|
|
3252
|
+
toast(e.message || "备份失败", true);
|
|
3253
|
+
} finally {
|
|
3254
|
+
btn.disabled = false;
|
|
3255
|
+
renderData(true);
|
|
3256
|
+
}
|
|
3257
|
+
});
|
|
3136
3258
|
|
|
3137
3259
|
// 告警卡「去处理 →」链接:切到对应页签(事件委托,卡片内容每次重渲染)
|
|
3138
3260
|
document.addEventListener("click", (e) => {
|
|
@@ -62,13 +62,44 @@ def _save_state(state: dict, home: Path | None = None) -> None:
|
|
|
62
62
|
core.atomic_json(p, disk)
|
|
63
63
|
|
|
64
64
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
65
|
+
_GIT_TRANSIENT_WINERRORS = {5, 32, 33, 145} # 拒绝访问 / 共享冲突 / 锁冲突 / 目录非空
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class GitUnavailable(RuntimeError):
|
|
69
|
+
"""git 命令反复失败(瞬时占用/超时),不是"这不是仓库"——两者必须分开报。"""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _git(repo: str, *args: str, attempts: int = 3) -> str:
|
|
73
|
+
"""跑 git 返回 stdout;**瞬时**失败重试,仍失败抛 GitUnavailable。
|
|
74
|
+
|
|
75
|
+
原来这里 `except Exception: return ""` 把瞬时占用/超时和"不是仓库"混为一谈,
|
|
76
|
+
一次杀软扫过就能让 checkpoint 误报"不是 git 仓库"(台账 #71)。
|
|
77
|
+
非零退出码(真的不是仓库、路径不对)仍返回 "",由调用方按业务判断。
|
|
78
|
+
"""
|
|
79
|
+
last = ""
|
|
80
|
+
for i in range(max(1, attempts)):
|
|
81
|
+
try:
|
|
82
|
+
r = subprocess.run(["git", "-C", repo, *args], capture_output=True,
|
|
83
|
+
text=True, encoding="utf-8", errors="replace", timeout=20)
|
|
84
|
+
if r.returncode == 0:
|
|
85
|
+
return r.stdout.strip()
|
|
86
|
+
return "" # 非零退出:业务层面的"没有/不是",不重试
|
|
87
|
+
except subprocess.TimeoutExpired:
|
|
88
|
+
last = f"git {args[0] if args else ''} 超时"
|
|
89
|
+
except OSError as exc:
|
|
90
|
+
# Windows 原生错误看 winerror;纯 OSError(errno=32) 没有 winerror,也要认
|
|
91
|
+
winerr = getattr(exc, "winerror", None)
|
|
92
|
+
errno_ = getattr(exc, "errno", None)
|
|
93
|
+
if (winerr not in _GIT_TRANSIENT_WINERRORS
|
|
94
|
+
and errno_ not in _GIT_TRANSIENT_WINERRORS
|
|
95
|
+
and not isinstance(exc, PermissionError)):
|
|
96
|
+
raise GitUnavailable(f"git 不可用:{exc}") from exc
|
|
97
|
+
last = f"git 被占用(winerror={winerr} errno={errno_}):{exc}"
|
|
98
|
+
except Exception as exc: # noqa: BLE001
|
|
99
|
+
raise GitUnavailable(f"git 调用失败:{exc}") from exc
|
|
100
|
+
if i + 1 < attempts:
|
|
101
|
+
time.sleep(0.3 * (i + 1)) # 退避:0.3s / 0.6s
|
|
102
|
+
raise GitUnavailable(last or "git 多次失败")
|
|
72
103
|
|
|
73
104
|
|
|
74
105
|
def collect(repo: str | None = None) -> dict | None:
|
|
@@ -76,6 +107,10 @@ def collect(repo: str | None = None) -> dict | None:
|
|
|
76
107
|
base = str(repo or ".")
|
|
77
108
|
root = _git(base, "rev-parse", "--show-toplevel")
|
|
78
109
|
if not root:
|
|
110
|
+
# 空 root 有两种可能:真的不是仓库,或 git 反复失败。
|
|
111
|
+
# .git 存在说明"是仓库、只是这次取证没成功"——这时不能谎报"不是仓库"。
|
|
112
|
+
if (Path(base) / ".git").exists():
|
|
113
|
+
raise GitUnavailable("git 仓库存在,但取证失败(可能被杀软/索引器短暂占用),请稍后重试")
|
|
79
114
|
return None
|
|
80
115
|
head = _git(root, "rev-parse", "--short", "HEAD")
|
|
81
116
|
branch = _git(root, "rev-parse", "--abbrev-ref", "HEAD")
|
|
@@ -139,7 +174,11 @@ def build_text(ev: dict, note: str = "", extra: str = "") -> str:
|
|
|
139
174
|
def checkpoint(repo: str | None = None, note: str = "", *, dry_run: bool = False,
|
|
140
175
|
force: bool = False, home: Path | None = None) -> dict:
|
|
141
176
|
"""一步到位:收集 → 判断 → 写记忆 + 记状态。"""
|
|
142
|
-
|
|
177
|
+
try:
|
|
178
|
+
ev = collect(repo)
|
|
179
|
+
except GitUnavailable as exc:
|
|
180
|
+
# 取证失败 ≠ 不是仓库:给可重试的明确理由,别让用户以为路径给错了
|
|
181
|
+
return {"ok": False, "skipped": True, "transient": True, "reason": str(exc)}
|
|
143
182
|
if ev is None:
|
|
144
183
|
return {"ok": False, "skipped": True, "reason": "不是 git 仓库,没法取证(可显式传 --repo)"}
|
|
145
184
|
state = _load_state(home)
|
|
@@ -300,11 +300,20 @@ def cmd_backup(target: str | None = None, keep: int = 20, password: str | None =
|
|
|
300
300
|
removed = 0
|
|
301
301
|
if keep and keep > 0:
|
|
302
302
|
# 按修改时间排序而不是文件名:跨日期时文件名字典序可能乱掉新旧关系
|
|
303
|
-
|
|
304
|
-
|
|
303
|
+
# 只按**真备份文件**计数:原来 glob 是 brain-memory_*.zip* ,把同名
|
|
304
|
+
# .zip.sha256 校验文件也算进去,于是 keep=5 实际只留 2~3 份备份,
|
|
305
|
+
# 还会留下没有 zip 的孤儿 sha256(P10 #69)。
|
|
306
|
+
existing = sorted(
|
|
307
|
+
[p for p in out_dir.glob("brain-memory_*.zip*")
|
|
308
|
+
if p.name.endswith(".zip") or p.name.endswith(".zip.enc")],
|
|
309
|
+
key=lambda p: p.stat().st_mtime, reverse=True)
|
|
305
310
|
for p in existing[keep:]:
|
|
306
311
|
try:
|
|
307
312
|
p.unlink()
|
|
313
|
+
# 连带清掉它的 sha256 边车,别留孤儿
|
|
314
|
+
side = p.with_name(p.name + ".sha256")
|
|
315
|
+
if side.is_file():
|
|
316
|
+
side.unlink()
|
|
308
317
|
removed += 1
|
|
309
318
|
except Exception:
|
|
310
319
|
pass
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""面板「数据」页后端:备份列表 / 立即备份 / 从备份恢复。
|
|
3
|
+
|
|
4
|
+
复用 CLI 已有的 cmd_backup / cmd_restore——它们已经做了:完整性校验、
|
|
5
|
+
恢复前自动备份、坏包回退、保留份数修剪。面板只负责触发与展示,
|
|
6
|
+
不另写一套打包逻辑(两套实现必然分叉)。
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import core
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _backup_dir() -> Path:
|
|
19
|
+
"""与 CLI 同源的备份目录选址(跨卷优先)。"""
|
|
20
|
+
env = os.environ.get("BRAIN_MEMORY_BACKUP_DIR", "").strip()
|
|
21
|
+
if env:
|
|
22
|
+
return Path(env).expanduser()
|
|
23
|
+
try:
|
|
24
|
+
import safety
|
|
25
|
+
return safety.pick_backup_dir(core.HOME)
|
|
26
|
+
except Exception:
|
|
27
|
+
return Path(core.HOME) / "backups"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def list_backups(limit: int = 30) -> dict:
|
|
31
|
+
"""列出备份目录里的 zip(含大小/时间/是否有 sha 记录)。"""
|
|
32
|
+
d = _backup_dir()
|
|
33
|
+
items = []
|
|
34
|
+
try:
|
|
35
|
+
files = sorted(d.glob("*.zip"), key=lambda p: p.stat().st_mtime, reverse=True)
|
|
36
|
+
except OSError:
|
|
37
|
+
files = []
|
|
38
|
+
for p in files[:limit]:
|
|
39
|
+
try:
|
|
40
|
+
st = p.stat()
|
|
41
|
+
except OSError:
|
|
42
|
+
continue
|
|
43
|
+
sha_file = p.with_name(p.name + ".sha256")
|
|
44
|
+
items.append({
|
|
45
|
+
"name": p.name,
|
|
46
|
+
"path": str(p),
|
|
47
|
+
"size": st.st_size,
|
|
48
|
+
"mtime": int(st.st_mtime),
|
|
49
|
+
"mtime_text": time.strftime("%Y-%m-%d %H:%M", time.localtime(st.st_mtime)),
|
|
50
|
+
# 22 字节的空 zip(PK\x05\x06)是失败残壳,标出来别当备份用
|
|
51
|
+
"suspicious": st.st_size < 1024,
|
|
52
|
+
"has_sha": sha_file.is_file(),
|
|
53
|
+
})
|
|
54
|
+
return {"dir": str(d), "dir_exists": d.is_dir(), "items": items,
|
|
55
|
+
"count": len(items)}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def make_backup(keep: int = 0) -> dict:
|
|
59
|
+
"""立即备份。复用 CLI 的 cmd_backup(assume_yes=True:面板是显式点击)。
|
|
60
|
+
|
|
61
|
+
**keep 默认 0 = 不修剪**:手动点一下备份不该静默删掉历史备份——这是
|
|
62
|
+
不可逆操作(cmd_backup 用 unlink,不进回收站)。要清理请显式传 keep。
|
|
63
|
+
"""
|
|
64
|
+
if core.READONLY:
|
|
65
|
+
raise PermissionError("记忆库当前只读,无法备份。")
|
|
66
|
+
import cli
|
|
67
|
+
before = {x["name"] for x in list_backups(limit=500)["items"]}
|
|
68
|
+
code = cli.cmd_backup(target=None, keep=int(keep or 0), password=None,
|
|
69
|
+
assume_yes=True)
|
|
70
|
+
after = list_backups(limit=200)["items"]
|
|
71
|
+
new = [x for x in after if x["name"] not in before]
|
|
72
|
+
return {"ok": code == 0, "code": code,
|
|
73
|
+
"created": new[0] if new else None,
|
|
74
|
+
"total": len(after), "dir": str(_backup_dir())}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def restore_backup(name: str, exact: bool = False) -> dict:
|
|
78
|
+
"""从指定备份恢复。只接受备份目录内的 .zip 文件名(防路径穿越)。
|
|
79
|
+
|
|
80
|
+
cmd_restore 内部会:校验 zip 完整性 → 恢复前自动给现状打一份备份 →
|
|
81
|
+
坏包回退提示。这里不重复实现,只做入参收敛。
|
|
82
|
+
"""
|
|
83
|
+
if core.READONLY:
|
|
84
|
+
raise PermissionError("记忆库当前只读,无法恢复。")
|
|
85
|
+
safe = Path(str(name or "")).name # 只取文件名,杜绝 ../ 穿越
|
|
86
|
+
if not safe.lower().endswith(".zip"):
|
|
87
|
+
raise ValueError("只支持 .zip 备份文件")
|
|
88
|
+
d = _backup_dir()
|
|
89
|
+
target = d / safe
|
|
90
|
+
if not target.is_file():
|
|
91
|
+
raise FileNotFoundError(f"备份目录里没有这个文件:{safe}")
|
|
92
|
+
import cli
|
|
93
|
+
code = cli.cmd_restore(str(target), yes=True, password=None, exact=bool(exact))
|
|
94
|
+
return {"ok": code == 0, "code": code, "restored": safe, "exact": bool(exact)}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def data_stats() -> dict:
|
|
98
|
+
"""数据规模概览(给「数据」页顶部卡片)。"""
|
|
99
|
+
home = core.HOME
|
|
100
|
+
out = {"home": str(home), "layers": {}, "total_bytes": 0}
|
|
101
|
+
for name in ("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl",
|
|
102
|
+
"archive.jsonl", "knowledge.jsonl", "notes.jsonl"):
|
|
103
|
+
p = home / name
|
|
104
|
+
try:
|
|
105
|
+
size = p.stat().st_size if p.is_file() else 0
|
|
106
|
+
n = 0
|
|
107
|
+
if p.is_file():
|
|
108
|
+
n = sum(1 for ln in p.open(encoding="utf-8", errors="replace") if ln.strip())
|
|
109
|
+
except OSError:
|
|
110
|
+
size, n = 0, 0
|
|
111
|
+
out["layers"][name.replace(".jsonl", "")] = {"count": n, "bytes": size}
|
|
112
|
+
out["total_bytes"] += size
|
|
113
|
+
return out
|
|
@@ -56,6 +56,8 @@ _WRITE_ENDPOINTS = {
|
|
|
56
56
|
"/api/extensions",
|
|
57
57
|
# 设置页:改 config.json(只允许 panel_settings 白名单里的键)
|
|
58
58
|
"/api/config",
|
|
59
|
+
# 数据页:备份 / 恢复(都写盘;恢复前 cmd_restore 会先自动备份现状)
|
|
60
|
+
"/api/data/backup", "/api/data/restore",
|
|
59
61
|
# 云端面板市场:发布/下载/配置(token 写 config.json)
|
|
60
62
|
"/api/panels/cloud",
|
|
61
63
|
# Ollama 扩展:下载写 zip / 安装写程序目录与 config.json / setup 一键全流程
|
|
@@ -779,6 +781,12 @@ class Handler(BaseHTTPRequestHandler):
|
|
|
779
781
|
# 拓展商店清单:内置宿主适配插件 + 自定义已装拓展
|
|
780
782
|
self._json(panels.list_extensions())
|
|
781
783
|
return
|
|
784
|
+
if path == "/api/data":
|
|
785
|
+
# 数据页:规模概览 + 备份列表(只读)
|
|
786
|
+
import panel_data
|
|
787
|
+
self._json({"stats": panel_data.data_stats(),
|
|
788
|
+
"backups": panel_data.list_backups()})
|
|
789
|
+
return
|
|
782
790
|
if path == "/api/config":
|
|
783
791
|
# 设置页清单:白名单键的元数据 + 当前值 + 默认值(不返回任何密钥)
|
|
784
792
|
import panel_settings
|
|
@@ -981,6 +989,32 @@ def _api_persona_update(self, path, data):
|
|
|
981
989
|
|
|
982
990
|
|
|
983
991
|
|
|
992
|
+
def _api_data_backup(self, path, data):
|
|
993
|
+
"""立即备份。keep 可调(默认 20,与 CLI 一致)。"""
|
|
994
|
+
import panel_data
|
|
995
|
+
try:
|
|
996
|
+
r = panel_data.make_backup(keep=_to_int(data.get("keep"), 20) or 20)
|
|
997
|
+
except PermissionError as exc:
|
|
998
|
+
self._json({"error": str(exc)}, 403)
|
|
999
|
+
return
|
|
1000
|
+
self._json(r)
|
|
1001
|
+
|
|
1002
|
+
|
|
1003
|
+
def _api_data_restore(self, path, data):
|
|
1004
|
+
"""从备份恢复。name 只取文件名(防穿越);cmd_restore 会先自动备份现状。"""
|
|
1005
|
+
import panel_data
|
|
1006
|
+
name = str(data.get("name") or "").strip()
|
|
1007
|
+
try:
|
|
1008
|
+
r = panel_data.restore_backup(name, exact=bool(data.get("exact")))
|
|
1009
|
+
except PermissionError as exc:
|
|
1010
|
+
self._json({"error": str(exc)}, 403)
|
|
1011
|
+
return
|
|
1012
|
+
except (FileNotFoundError, ValueError) as exc:
|
|
1013
|
+
self._json({"error": str(exc)}, 400)
|
|
1014
|
+
return
|
|
1015
|
+
self._json(r)
|
|
1016
|
+
|
|
1017
|
+
|
|
984
1018
|
def _api_config(self, path, data):
|
|
985
1019
|
"""改一项配置:{key, value}。只允许 panel_settings 白名单里的键,
|
|
986
1020
|
并按 schema 校验类型/范围(配错一个键就能让注入崩掉,不能任写)。"""
|
|
@@ -2610,6 +2644,9 @@ _POST_ROUTES = {
|
|
|
2610
2644
|
# 首页与记忆写入
|
|
2611
2645
|
"/api/home/migrate": _api_home_migrate,
|
|
2612
2646
|
"/api/remember": _api_remember,
|
|
2647
|
+
# 数据页
|
|
2648
|
+
"/api/data/backup": _api_data_backup,
|
|
2649
|
+
"/api/data/restore": _api_data_restore,
|
|
2613
2650
|
# 设置页
|
|
2614
2651
|
"/api/config": _api_config,
|
|
2615
2652
|
# 人格 / 心智 / 情绪
|
package/scripts/checkpoint.py
CHANGED
|
@@ -62,13 +62,44 @@ def _save_state(state: dict, home: Path | None = None) -> None:
|
|
|
62
62
|
core.atomic_json(p, disk)
|
|
63
63
|
|
|
64
64
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
65
|
+
_GIT_TRANSIENT_WINERRORS = {5, 32, 33, 145} # 拒绝访问 / 共享冲突 / 锁冲突 / 目录非空
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class GitUnavailable(RuntimeError):
|
|
69
|
+
"""git 命令反复失败(瞬时占用/超时),不是"这不是仓库"——两者必须分开报。"""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _git(repo: str, *args: str, attempts: int = 3) -> str:
|
|
73
|
+
"""跑 git 返回 stdout;**瞬时**失败重试,仍失败抛 GitUnavailable。
|
|
74
|
+
|
|
75
|
+
原来这里 `except Exception: return ""` 把瞬时占用/超时和"不是仓库"混为一谈,
|
|
76
|
+
一次杀软扫过就能让 checkpoint 误报"不是 git 仓库"(台账 #71)。
|
|
77
|
+
非零退出码(真的不是仓库、路径不对)仍返回 "",由调用方按业务判断。
|
|
78
|
+
"""
|
|
79
|
+
last = ""
|
|
80
|
+
for i in range(max(1, attempts)):
|
|
81
|
+
try:
|
|
82
|
+
r = subprocess.run(["git", "-C", repo, *args], capture_output=True,
|
|
83
|
+
text=True, encoding="utf-8", errors="replace", timeout=20)
|
|
84
|
+
if r.returncode == 0:
|
|
85
|
+
return r.stdout.strip()
|
|
86
|
+
return "" # 非零退出:业务层面的"没有/不是",不重试
|
|
87
|
+
except subprocess.TimeoutExpired:
|
|
88
|
+
last = f"git {args[0] if args else ''} 超时"
|
|
89
|
+
except OSError as exc:
|
|
90
|
+
# Windows 原生错误看 winerror;纯 OSError(errno=32) 没有 winerror,也要认
|
|
91
|
+
winerr = getattr(exc, "winerror", None)
|
|
92
|
+
errno_ = getattr(exc, "errno", None)
|
|
93
|
+
if (winerr not in _GIT_TRANSIENT_WINERRORS
|
|
94
|
+
and errno_ not in _GIT_TRANSIENT_WINERRORS
|
|
95
|
+
and not isinstance(exc, PermissionError)):
|
|
96
|
+
raise GitUnavailable(f"git 不可用:{exc}") from exc
|
|
97
|
+
last = f"git 被占用(winerror={winerr} errno={errno_}):{exc}"
|
|
98
|
+
except Exception as exc: # noqa: BLE001
|
|
99
|
+
raise GitUnavailable(f"git 调用失败:{exc}") from exc
|
|
100
|
+
if i + 1 < attempts:
|
|
101
|
+
time.sleep(0.3 * (i + 1)) # 退避:0.3s / 0.6s
|
|
102
|
+
raise GitUnavailable(last or "git 多次失败")
|
|
72
103
|
|
|
73
104
|
|
|
74
105
|
def collect(repo: str | None = None) -> dict | None:
|
|
@@ -76,6 +107,10 @@ def collect(repo: str | None = None) -> dict | None:
|
|
|
76
107
|
base = str(repo or ".")
|
|
77
108
|
root = _git(base, "rev-parse", "--show-toplevel")
|
|
78
109
|
if not root:
|
|
110
|
+
# 空 root 有两种可能:真的不是仓库,或 git 反复失败。
|
|
111
|
+
# .git 存在说明"是仓库、只是这次取证没成功"——这时不能谎报"不是仓库"。
|
|
112
|
+
if (Path(base) / ".git").exists():
|
|
113
|
+
raise GitUnavailable("git 仓库存在,但取证失败(可能被杀软/索引器短暂占用),请稍后重试")
|
|
79
114
|
return None
|
|
80
115
|
head = _git(root, "rev-parse", "--short", "HEAD")
|
|
81
116
|
branch = _git(root, "rev-parse", "--abbrev-ref", "HEAD")
|
|
@@ -139,7 +174,11 @@ def build_text(ev: dict, note: str = "", extra: str = "") -> str:
|
|
|
139
174
|
def checkpoint(repo: str | None = None, note: str = "", *, dry_run: bool = False,
|
|
140
175
|
force: bool = False, home: Path | None = None) -> dict:
|
|
141
176
|
"""一步到位:收集 → 判断 → 写记忆 + 记状态。"""
|
|
142
|
-
|
|
177
|
+
try:
|
|
178
|
+
ev = collect(repo)
|
|
179
|
+
except GitUnavailable as exc:
|
|
180
|
+
# 取证失败 ≠ 不是仓库:给可重试的明确理由,别让用户以为路径给错了
|
|
181
|
+
return {"ok": False, "skipped": True, "transient": True, "reason": str(exc)}
|
|
143
182
|
if ev is None:
|
|
144
183
|
return {"ok": False, "skipped": True, "reason": "不是 git 仓库,没法取证(可显式传 --repo)"}
|
|
145
184
|
state = _load_state(home)
|
package/scripts/cli.py
CHANGED
|
@@ -300,11 +300,20 @@ def cmd_backup(target: str | None = None, keep: int = 20, password: str | None =
|
|
|
300
300
|
removed = 0
|
|
301
301
|
if keep and keep > 0:
|
|
302
302
|
# 按修改时间排序而不是文件名:跨日期时文件名字典序可能乱掉新旧关系
|
|
303
|
-
|
|
304
|
-
|
|
303
|
+
# 只按**真备份文件**计数:原来 glob 是 brain-memory_*.zip* ,把同名
|
|
304
|
+
# .zip.sha256 校验文件也算进去,于是 keep=5 实际只留 2~3 份备份,
|
|
305
|
+
# 还会留下没有 zip 的孤儿 sha256(P10 #69)。
|
|
306
|
+
existing = sorted(
|
|
307
|
+
[p for p in out_dir.glob("brain-memory_*.zip*")
|
|
308
|
+
if p.name.endswith(".zip") or p.name.endswith(".zip.enc")],
|
|
309
|
+
key=lambda p: p.stat().st_mtime, reverse=True)
|
|
305
310
|
for p in existing[keep:]:
|
|
306
311
|
try:
|
|
307
312
|
p.unlink()
|
|
313
|
+
# 连带清掉它的 sha256 边车,别留孤儿
|
|
314
|
+
side = p.with_name(p.name + ".sha256")
|
|
315
|
+
if side.is_file():
|
|
316
|
+
side.unlink()
|
|
308
317
|
removed += 1
|
|
309
318
|
except Exception:
|
|
310
319
|
pass
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""面板「数据」页后端:备份列表 / 立即备份 / 从备份恢复。
|
|
3
|
+
|
|
4
|
+
复用 CLI 已有的 cmd_backup / cmd_restore——它们已经做了:完整性校验、
|
|
5
|
+
恢复前自动备份、坏包回退、保留份数修剪。面板只负责触发与展示,
|
|
6
|
+
不另写一套打包逻辑(两套实现必然分叉)。
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import core
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _backup_dir() -> Path:
|
|
19
|
+
"""与 CLI 同源的备份目录选址(跨卷优先)。"""
|
|
20
|
+
env = os.environ.get("BRAIN_MEMORY_BACKUP_DIR", "").strip()
|
|
21
|
+
if env:
|
|
22
|
+
return Path(env).expanduser()
|
|
23
|
+
try:
|
|
24
|
+
import safety
|
|
25
|
+
return safety.pick_backup_dir(core.HOME)
|
|
26
|
+
except Exception:
|
|
27
|
+
return Path(core.HOME) / "backups"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def list_backups(limit: int = 30) -> dict:
|
|
31
|
+
"""列出备份目录里的 zip(含大小/时间/是否有 sha 记录)。"""
|
|
32
|
+
d = _backup_dir()
|
|
33
|
+
items = []
|
|
34
|
+
try:
|
|
35
|
+
files = sorted(d.glob("*.zip"), key=lambda p: p.stat().st_mtime, reverse=True)
|
|
36
|
+
except OSError:
|
|
37
|
+
files = []
|
|
38
|
+
for p in files[:limit]:
|
|
39
|
+
try:
|
|
40
|
+
st = p.stat()
|
|
41
|
+
except OSError:
|
|
42
|
+
continue
|
|
43
|
+
sha_file = p.with_name(p.name + ".sha256")
|
|
44
|
+
items.append({
|
|
45
|
+
"name": p.name,
|
|
46
|
+
"path": str(p),
|
|
47
|
+
"size": st.st_size,
|
|
48
|
+
"mtime": int(st.st_mtime),
|
|
49
|
+
"mtime_text": time.strftime("%Y-%m-%d %H:%M", time.localtime(st.st_mtime)),
|
|
50
|
+
# 22 字节的空 zip(PK\x05\x06)是失败残壳,标出来别当备份用
|
|
51
|
+
"suspicious": st.st_size < 1024,
|
|
52
|
+
"has_sha": sha_file.is_file(),
|
|
53
|
+
})
|
|
54
|
+
return {"dir": str(d), "dir_exists": d.is_dir(), "items": items,
|
|
55
|
+
"count": len(items)}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def make_backup(keep: int = 0) -> dict:
|
|
59
|
+
"""立即备份。复用 CLI 的 cmd_backup(assume_yes=True:面板是显式点击)。
|
|
60
|
+
|
|
61
|
+
**keep 默认 0 = 不修剪**:手动点一下备份不该静默删掉历史备份——这是
|
|
62
|
+
不可逆操作(cmd_backup 用 unlink,不进回收站)。要清理请显式传 keep。
|
|
63
|
+
"""
|
|
64
|
+
if core.READONLY:
|
|
65
|
+
raise PermissionError("记忆库当前只读,无法备份。")
|
|
66
|
+
import cli
|
|
67
|
+
before = {x["name"] for x in list_backups(limit=500)["items"]}
|
|
68
|
+
code = cli.cmd_backup(target=None, keep=int(keep or 0), password=None,
|
|
69
|
+
assume_yes=True)
|
|
70
|
+
after = list_backups(limit=200)["items"]
|
|
71
|
+
new = [x for x in after if x["name"] not in before]
|
|
72
|
+
return {"ok": code == 0, "code": code,
|
|
73
|
+
"created": new[0] if new else None,
|
|
74
|
+
"total": len(after), "dir": str(_backup_dir())}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def restore_backup(name: str, exact: bool = False) -> dict:
|
|
78
|
+
"""从指定备份恢复。只接受备份目录内的 .zip 文件名(防路径穿越)。
|
|
79
|
+
|
|
80
|
+
cmd_restore 内部会:校验 zip 完整性 → 恢复前自动给现状打一份备份 →
|
|
81
|
+
坏包回退提示。这里不重复实现,只做入参收敛。
|
|
82
|
+
"""
|
|
83
|
+
if core.READONLY:
|
|
84
|
+
raise PermissionError("记忆库当前只读,无法恢复。")
|
|
85
|
+
safe = Path(str(name or "")).name # 只取文件名,杜绝 ../ 穿越
|
|
86
|
+
if not safe.lower().endswith(".zip"):
|
|
87
|
+
raise ValueError("只支持 .zip 备份文件")
|
|
88
|
+
d = _backup_dir()
|
|
89
|
+
target = d / safe
|
|
90
|
+
if not target.is_file():
|
|
91
|
+
raise FileNotFoundError(f"备份目录里没有这个文件:{safe}")
|
|
92
|
+
import cli
|
|
93
|
+
code = cli.cmd_restore(str(target), yes=True, password=None, exact=bool(exact))
|
|
94
|
+
return {"ok": code == 0, "code": code, "restored": safe, "exact": bool(exact)}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def data_stats() -> dict:
|
|
98
|
+
"""数据规模概览(给「数据」页顶部卡片)。"""
|
|
99
|
+
home = core.HOME
|
|
100
|
+
out = {"home": str(home), "layers": {}, "total_bytes": 0}
|
|
101
|
+
for name in ("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl",
|
|
102
|
+
"archive.jsonl", "knowledge.jsonl", "notes.jsonl"):
|
|
103
|
+
p = home / name
|
|
104
|
+
try:
|
|
105
|
+
size = p.stat().st_size if p.is_file() else 0
|
|
106
|
+
n = 0
|
|
107
|
+
if p.is_file():
|
|
108
|
+
n = sum(1 for ln in p.open(encoding="utf-8", errors="replace") if ln.strip())
|
|
109
|
+
except OSError:
|
|
110
|
+
size, n = 0, 0
|
|
111
|
+
out["layers"][name.replace(".jsonl", "")] = {"count": n, "bytes": size}
|
|
112
|
+
out["total_bytes"] += size
|
|
113
|
+
return out
|
package/scripts/panel_server.py
CHANGED
|
@@ -56,6 +56,8 @@ _WRITE_ENDPOINTS = {
|
|
|
56
56
|
"/api/extensions",
|
|
57
57
|
# 设置页:改 config.json(只允许 panel_settings 白名单里的键)
|
|
58
58
|
"/api/config",
|
|
59
|
+
# 数据页:备份 / 恢复(都写盘;恢复前 cmd_restore 会先自动备份现状)
|
|
60
|
+
"/api/data/backup", "/api/data/restore",
|
|
59
61
|
# 云端面板市场:发布/下载/配置(token 写 config.json)
|
|
60
62
|
"/api/panels/cloud",
|
|
61
63
|
# Ollama 扩展:下载写 zip / 安装写程序目录与 config.json / setup 一键全流程
|
|
@@ -779,6 +781,12 @@ class Handler(BaseHTTPRequestHandler):
|
|
|
779
781
|
# 拓展商店清单:内置宿主适配插件 + 自定义已装拓展
|
|
780
782
|
self._json(panels.list_extensions())
|
|
781
783
|
return
|
|
784
|
+
if path == "/api/data":
|
|
785
|
+
# 数据页:规模概览 + 备份列表(只读)
|
|
786
|
+
import panel_data
|
|
787
|
+
self._json({"stats": panel_data.data_stats(),
|
|
788
|
+
"backups": panel_data.list_backups()})
|
|
789
|
+
return
|
|
782
790
|
if path == "/api/config":
|
|
783
791
|
# 设置页清单:白名单键的元数据 + 当前值 + 默认值(不返回任何密钥)
|
|
784
792
|
import panel_settings
|
|
@@ -981,6 +989,32 @@ def _api_persona_update(self, path, data):
|
|
|
981
989
|
|
|
982
990
|
|
|
983
991
|
|
|
992
|
+
def _api_data_backup(self, path, data):
|
|
993
|
+
"""立即备份。keep 可调(默认 20,与 CLI 一致)。"""
|
|
994
|
+
import panel_data
|
|
995
|
+
try:
|
|
996
|
+
r = panel_data.make_backup(keep=_to_int(data.get("keep"), 20) or 20)
|
|
997
|
+
except PermissionError as exc:
|
|
998
|
+
self._json({"error": str(exc)}, 403)
|
|
999
|
+
return
|
|
1000
|
+
self._json(r)
|
|
1001
|
+
|
|
1002
|
+
|
|
1003
|
+
def _api_data_restore(self, path, data):
|
|
1004
|
+
"""从备份恢复。name 只取文件名(防穿越);cmd_restore 会先自动备份现状。"""
|
|
1005
|
+
import panel_data
|
|
1006
|
+
name = str(data.get("name") or "").strip()
|
|
1007
|
+
try:
|
|
1008
|
+
r = panel_data.restore_backup(name, exact=bool(data.get("exact")))
|
|
1009
|
+
except PermissionError as exc:
|
|
1010
|
+
self._json({"error": str(exc)}, 403)
|
|
1011
|
+
return
|
|
1012
|
+
except (FileNotFoundError, ValueError) as exc:
|
|
1013
|
+
self._json({"error": str(exc)}, 400)
|
|
1014
|
+
return
|
|
1015
|
+
self._json(r)
|
|
1016
|
+
|
|
1017
|
+
|
|
984
1018
|
def _api_config(self, path, data):
|
|
985
1019
|
"""改一项配置:{key, value}。只允许 panel_settings 白名单里的键,
|
|
986
1020
|
并按 schema 校验类型/范围(配错一个键就能让注入崩掉,不能任写)。"""
|
|
@@ -2610,6 +2644,9 @@ _POST_ROUTES = {
|
|
|
2610
2644
|
# 首页与记忆写入
|
|
2611
2645
|
"/api/home/migrate": _api_home_migrate,
|
|
2612
2646
|
"/api/remember": _api_remember,
|
|
2647
|
+
# 数据页
|
|
2648
|
+
"/api/data/backup": _api_data_backup,
|
|
2649
|
+
"/api/data/restore": _api_data_restore,
|
|
2613
2650
|
# 设置页
|
|
2614
2651
|
"/api/config": _api_config,
|
|
2615
2652
|
# 人格 / 心智 / 情绪
|