lingshu-skill 5.58.0 → 5.60.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 +29 -0
- package/README.md +1 -1
- package/SKILL-lite.md +1 -1
- package/SKILL-tiny.md +1 -1
- package/SKILL.md +1 -1
- package/package.json +1 -1
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +8 -8
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +29 -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 +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +81 -28
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +1235 -1214
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +58 -12
- package/scripts/cli.py +81 -28
- package/scripts/dream.py +1235 -1214
- package/scripts/memory.py +58 -12
|
@@ -1102,8 +1102,40 @@ def save_all(records: list) -> None:
|
|
|
1102
1102
|
except OSError:
|
|
1103
1103
|
pass
|
|
1104
1104
|
raise
|
|
1105
|
-
|
|
1106
|
-
|
|
1105
|
+
# LS-009(v5.59):为 save_all 增加多文件替换失败原子回滚!
|
|
1106
|
+
replaced_backups = [] # [(target_path, backup_path)]
|
|
1107
|
+
try:
|
|
1108
|
+
for tmp, p in staged:
|
|
1109
|
+
bak_old = None
|
|
1110
|
+
if p.exists():
|
|
1111
|
+
bak_old = p.with_name(p.name + f".rollback-{os.getpid()}-{int(now_ts() * 1000) % 1000000}")
|
|
1112
|
+
try:
|
|
1113
|
+
shutil.copy2(p, bak_old)
|
|
1114
|
+
except Exception:
|
|
1115
|
+
bak_old = None
|
|
1116
|
+
_replace_retry(tmp, p)
|
|
1117
|
+
if bak_old:
|
|
1118
|
+
replaced_backups.append((p, bak_old))
|
|
1119
|
+
except BaseException as replace_err:
|
|
1120
|
+
for target_p, bak_p in reversed(replaced_backups):
|
|
1121
|
+
try:
|
|
1122
|
+
_replace_retry(bak_p, target_p)
|
|
1123
|
+
except Exception:
|
|
1124
|
+
pass
|
|
1125
|
+
for tmp, _ in staged:
|
|
1126
|
+
try:
|
|
1127
|
+
if tmp.exists():
|
|
1128
|
+
os.unlink(tmp)
|
|
1129
|
+
except OSError:
|
|
1130
|
+
pass
|
|
1131
|
+
raise replace_err
|
|
1132
|
+
finally:
|
|
1133
|
+
for _, bak_p in replaced_backups:
|
|
1134
|
+
try:
|
|
1135
|
+
if bak_p.exists():
|
|
1136
|
+
os.unlink(bak_p)
|
|
1137
|
+
except OSError:
|
|
1138
|
+
pass
|
|
1107
1139
|
|
|
1108
1140
|
# 写后校验:JSON 可解析 + 末行完整 + 层级自洽。不通过就回滚并抛错
|
|
1109
1141
|
# (回滚成功时数据是"旧的一致状态",比留着一份写坏的新数据安全)。
|
|
@@ -3075,8 +3107,8 @@ def _ledger_path():
|
|
|
3075
3107
|
return HOME / _LEDGER_FILE
|
|
3076
3108
|
|
|
3077
3109
|
|
|
3078
|
-
def
|
|
3079
|
-
"""
|
|
3110
|
+
def _ledger_add_strict(record: dict, reason: str = "purge") -> bool:
|
|
3111
|
+
"""LS-016: 把一条记录追加进软删除台账,返回是否成功。"""
|
|
3080
3112
|
try:
|
|
3081
3113
|
row = dict(record)
|
|
3082
3114
|
row["deleted_at"] = now_ts()
|
|
@@ -3085,10 +3117,15 @@ def _ledger_add(record: dict, reason: str = "purge") -> None:
|
|
|
3085
3117
|
with _locked(_ledger_path()):
|
|
3086
3118
|
with _ledger_path().open("a", encoding="utf-8") as f:
|
|
3087
3119
|
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
|
3088
|
-
|
|
3089
|
-
|
|
3120
|
+
return True
|
|
3121
|
+
except Exception as exc:
|
|
3122
|
+
log_event("purge", f"软删除台账严格写入失败:{exc}", level="error")
|
|
3123
|
+
return False
|
|
3090
3124
|
|
|
3091
3125
|
|
|
3126
|
+
def _ledger_add(record: dict, reason: str = "purge") -> None:
|
|
3127
|
+
"""把一条记录追加进软删除台账(调用方负责持锁)。失败不阻断删除主流程。"""
|
|
3128
|
+
_ledger_add_strict(record, reason)
|
|
3092
3129
|
def trash_list(limit: int = 50) -> list:
|
|
3093
3130
|
"""看软删除台账里有什么(最近优先)。"""
|
|
3094
3131
|
rows = []
|
|
@@ -3210,7 +3247,9 @@ def purge(memory_id: str, confirm_token: str) -> dict:
|
|
|
3210
3247
|
# 而 _ledger_add 会吞掉所有异常只记 warn —— 于是"删成功 + 台账写失败"
|
|
3211
3248
|
# (磁盘满/权限/文件被占)时,这条归档记忆被物理销毁且哪里都没有副本,
|
|
3212
3249
|
# 用户无法恢复,直接违反"只移不删、删除必须先留底"。
|
|
3213
|
-
|
|
3250
|
+
# LS-016(v5.59):台账写入失败时必须禁止物理删除!
|
|
3251
|
+
if not _ledger_add_strict(target, reason="purge-archive"):
|
|
3252
|
+
raise RuntimeError(f"软删除台账写入失败,为防数据丢失已中止物理删除:{memory_id}")
|
|
3214
3253
|
write_jsonl(HOME / "archive.jsonl", archive)
|
|
3215
3254
|
_cut_assoc_links(memory_id)
|
|
3216
3255
|
audit_log("user", "purge", memory_id, "物理删除(archive 副本)")
|
|
@@ -3224,7 +3263,9 @@ def purge(memory_id: str, confirm_token: str) -> dict:
|
|
|
3224
3263
|
raise ValueError(
|
|
3225
3264
|
f"淡忘记忆需冷静满 {_PURGE_COOLDOWN_DAYS} 天后才能物理删除"
|
|
3226
3265
|
f"(当前淡忘于 {fmt_date(forgotten_at)})")
|
|
3227
|
-
|
|
3266
|
+
# LS-016(v5.59):台账写入失败时必须禁止物理删除!
|
|
3267
|
+
if not _ledger_add_strict(target, reason="purge-dust"):
|
|
3268
|
+
raise RuntimeError(f"软删除台账写入失败,为防数据丢失已中止物理删除:{memory_id}")
|
|
3228
3269
|
records = [m for m in records if m.get("id") != memory_id]
|
|
3229
3270
|
save_all(records)
|
|
3230
3271
|
# archive 里可能也有同名副本(归档过的),一并清掉
|
|
@@ -3716,15 +3757,20 @@ def _sweep_locked(rows: list) -> int:
|
|
|
3716
3757
|
arch.append(r)
|
|
3717
3758
|
continue
|
|
3718
3759
|
keep.append(r)
|
|
3760
|
+
# LS-017(v5.59):归档失败时保留工作记忆原记录!
|
|
3761
|
+
actually_archived = []
|
|
3762
|
+
failed_arch = []
|
|
3719
3763
|
if arch:
|
|
3720
|
-
rows[:] = keep
|
|
3721
3764
|
path = _work_archive_path()
|
|
3722
3765
|
for r in arch:
|
|
3723
3766
|
try:
|
|
3724
3767
|
_append_jsonl(path, r)
|
|
3725
|
-
|
|
3726
|
-
|
|
3727
|
-
|
|
3768
|
+
actually_archived.append(r)
|
|
3769
|
+
except OSError as exc:
|
|
3770
|
+
log_event("working", f"工作记忆归档单条失败,保留在原工作区:{exc}", level="warn")
|
|
3771
|
+
failed_arch.append(r)
|
|
3772
|
+
rows[:] = keep + failed_arch
|
|
3773
|
+
return len(actually_archived)
|
|
3728
3774
|
|
|
3729
3775
|
|
|
3730
3776
|
def work_sweep() -> int:
|
package/scripts/cli.py
CHANGED
|
@@ -139,10 +139,9 @@ def _open_backup_zip(zp: Path, password: str | None):
|
|
|
139
139
|
return zipfile.ZipFile(zp)
|
|
140
140
|
|
|
141
141
|
|
|
142
|
-
def _latest_valid_backup(bad_path: Path) -> Path | None:
|
|
143
|
-
"""v3.02 #6
|
|
144
|
-
|
|
145
|
-
找不到/校验失败返回 None(只有这一个搜索结果,不做任何自动恢复决策)。
|
|
142
|
+
def _latest_valid_backup(bad_path: Path, password: str | None = None) -> Path | None:
|
|
143
|
+
"""v3.02 #6 & LS-025(v5.60):坏包回退——在坏包同目录找最近一份 testzip 通过的备份。
|
|
144
|
+
支持将当前 password 传入,当损坏的新包出现时,能够正确解开并校验历史加密备份包(.zip.enc)。
|
|
146
145
|
"""
|
|
147
146
|
try:
|
|
148
147
|
cands = sorted(bad_path.parent.glob("brain-memory_*.zip*"),
|
|
@@ -155,7 +154,7 @@ def _latest_valid_backup(bad_path: Path) -> Path | None:
|
|
|
155
154
|
if not p.is_file():
|
|
156
155
|
continue
|
|
157
156
|
try:
|
|
158
|
-
with _open_backup_zip(p,
|
|
157
|
+
with _open_backup_zip(p, password) as zf:
|
|
159
158
|
if zf.testzip() is None:
|
|
160
159
|
return p
|
|
161
160
|
except Exception:
|
|
@@ -362,6 +361,13 @@ def cmd_backup(target: str | None = None, keep: int = 20, password: str | None =
|
|
|
362
361
|
无口令备份是明文 zip(含全部记忆原文),交互环境下需显式确认;
|
|
363
362
|
restore 前的自动备份、--yes / 非交互脚本传 assume_yes=True 跳过确认。
|
|
364
363
|
"""
|
|
364
|
+
# LS-002(v5.60):给备份补上 HOME 安全护栏!
|
|
365
|
+
# 严禁将盘符根、用户主目录、桌面/文档等危险目标当作 HOME 进行打包遍历。
|
|
366
|
+
try:
|
|
367
|
+
safety.assert_safe_home(HOME, action="备份")
|
|
368
|
+
except (ValueError, safety.UnsafeHomeError) as exc:
|
|
369
|
+
print(f"[错误] {exc}", file=sys.stderr)
|
|
370
|
+
return 1
|
|
365
371
|
if not HOME.exists():
|
|
366
372
|
print(f"[错误] 记忆库还不存在:{HOME}(先运行 init)", file=sys.stderr)
|
|
367
373
|
return 1
|
|
@@ -425,8 +431,9 @@ def cmd_backup(target: str | None = None, keep: int = 20, password: str | None =
|
|
|
425
431
|
continue
|
|
426
432
|
if f == zip_path:
|
|
427
433
|
continue # 别把正在写的备份包自己打包进去(--out 指向记忆库自身时会踩到)
|
|
428
|
-
|
|
429
|
-
|
|
434
|
+
# LS-013(v5.50):阻止备份递归包含旧 .zip 及加密 .zip.enc 包!
|
|
435
|
+
if "backups" in f.parts and (f.name.endswith(".zip") or f.name.endswith(".zip.enc")):
|
|
436
|
+
continue
|
|
430
437
|
if _is_sensitive_file(f):
|
|
431
438
|
skipped += 1
|
|
432
439
|
continue # 密钥/凭据不进备份包
|
|
@@ -448,10 +455,13 @@ def cmd_backup(target: str | None = None, keep: int = 20, password: str | None =
|
|
|
448
455
|
zf.write(f, rel)
|
|
449
456
|
n += 1
|
|
450
457
|
except OSError as exc:
|
|
458
|
+
# LS-015(v5.60):严谨区分并发临时文件消失(FileNotFoundError)与严重读取故障(Permission/IOError)!
|
|
459
|
+
# 如果是核心关键文件(cortex/hippo/persona/config)读取故障,必须抛出异常导致备份失败,绝不标为成功!
|
|
460
|
+
_is_critical = any(k in rel for k in ("cortex.jsonl", "hippocampus.jsonl", "persona.json", "config.json"))
|
|
461
|
+
if _is_critical:
|
|
462
|
+
raise RuntimeError(f"备份核心记忆文件读取故障(已中止,不生成残缺包):{rel} ({exc})") from exc
|
|
451
463
|
vanished += 1
|
|
452
|
-
if vanished == 1:
|
|
453
|
-
# LOG-NOISE(v5.49):单个 handoff/临时文件消失属正常竞态(面板保存/
|
|
454
|
-
# cron 移动),降为 info——error 级会触发 doctor 的 log-anomalies 假警报。
|
|
464
|
+
if vanished == 1:
|
|
455
465
|
_lv = "info" if ("handoffs" in str(rel) or ".pruned" in str(rel)) else "warn"
|
|
456
466
|
log_event("backup",
|
|
457
467
|
f"跳过 {rel}(并发写入/移动导致读不到):{exc}",
|
|
@@ -533,14 +543,19 @@ def cmd_backup(target: str | None = None, keep: int = 20, password: str | None =
|
|
|
533
543
|
print("[警告] 备份抽样演练未通过:包能打开,但关键文件缺失或解析失败。"
|
|
534
544
|
"建议尽快重做一份备份并人工检查。", file=sys.stderr)
|
|
535
545
|
if password:
|
|
536
|
-
#
|
|
546
|
+
# LS-012(v5.60):清理加密备份失败后的明文 ZIP!
|
|
547
|
+
# 若加密过程抛出异常,明文 zip 绝不能遗留盘上,必须立即清理或隔离。
|
|
537
548
|
try:
|
|
538
549
|
enc_path = zip_path.with_name(zip_path.name + ".enc")
|
|
539
550
|
enc_path.write_bytes(_vault_encrypt(zip_path.read_bytes(), password))
|
|
540
|
-
zip_path.unlink()
|
|
551
|
+
zip_path.unlink(missing_ok=True)
|
|
541
552
|
zip_path = enc_path
|
|
542
553
|
except Exception as exc:
|
|
543
|
-
|
|
554
|
+
try:
|
|
555
|
+
zip_path.unlink(missing_ok=True)
|
|
556
|
+
except Exception:
|
|
557
|
+
pass
|
|
558
|
+
print(f"[错误] 备份加密失败,已清理明文包:{exc}", file=sys.stderr)
|
|
544
559
|
return 2
|
|
545
560
|
removed = 0
|
|
546
561
|
# 分层保留(GFS,P11 #72):小时内留最近 N 个、天内每天留 1 个、周内每周留 1 个,
|
|
@@ -640,17 +655,24 @@ def cmd_backup(target: str | None = None, keep: int = 20, password: str | None =
|
|
|
640
655
|
return 0
|
|
641
656
|
|
|
642
657
|
|
|
643
|
-
MAX_RESTORE_ENTRIES =
|
|
658
|
+
MAX_RESTORE_ENTRIES = 2000 # LS-014 (v5.60): 提高到 2000 项以对齐大库正常备份条目数,防大库恢复被拒
|
|
644
659
|
MAX_RESTORE_BYTES = 512 * 1024 * 1024 # 512 MB,防 zip 炸弹
|
|
645
660
|
|
|
646
661
|
|
|
647
662
|
def cmd_restore(zip_path: str, yes: bool = False, password: str | None = None,
|
|
648
663
|
exact: bool = False) -> int:
|
|
649
|
-
"""
|
|
664
|
+
"""从备份恢复记忆库。恢复前自��给现状打一份备份。
|
|
650
665
|
|
|
651
666
|
默认合并语义:只覆盖 zip 内同名文件,备份之后新增的文件保留。
|
|
652
667
|
exact=True 时先清空受管目录(backups/ 除外)再解包,真正回到备份时点。
|
|
653
668
|
"""
|
|
669
|
+
# LS-002(v5.60):给恢复补上 HOME 安全护栏!
|
|
670
|
+
# 严防 restore 向用户根目录、系统目录解压覆盖甚至在 exact 下清空整个盘符。
|
|
671
|
+
try:
|
|
672
|
+
safety.assert_safe_home(HOME, action="恢复")
|
|
673
|
+
except (ValueError, safety.UnsafeHomeError) as exc:
|
|
674
|
+
print(f"[错误] {exc}", file=sys.stderr)
|
|
675
|
+
return 1
|
|
654
676
|
zp = Path(zip_path).expanduser()
|
|
655
677
|
if not zp.exists():
|
|
656
678
|
print(f"[错误] 找不到备份文件:{zp}", file=sys.stderr)
|
|
@@ -669,7 +691,7 @@ def cmd_restore(zip_path: str, yes: bool = False, password: str | None = None,
|
|
|
669
691
|
print(f"[错误] {exc}", file=sys.stderr)
|
|
670
692
|
if bad:
|
|
671
693
|
# v3.02 #6:坏包自动回退——尝试列表里最近一份通过校验的旧备份
|
|
672
|
-
prev = _latest_valid_backup(zp)
|
|
694
|
+
prev = _latest_valid_backup(zp, password)
|
|
673
695
|
if prev:
|
|
674
696
|
print(f"[错误] {zp.name} 是坏包,且发现上一份完好备份:{prev}",
|
|
675
697
|
file=sys.stderr)
|
|
@@ -743,6 +765,9 @@ def cmd_restore(zip_path: str, yes: bool = False, password: str | None = None,
|
|
|
743
765
|
# 只删白名单内的路径:记忆库里用户自己放进去的东西(草稿、导出包、
|
|
744
766
|
# 参考笔记)一律保留并汇报——"清空受管文件"不该变成"清空这个目录"。
|
|
745
767
|
kept: list[str] = []
|
|
768
|
+
# LS-011(v5.59):禁止 exact 恢复忽略受管文件删除失败!
|
|
769
|
+
# 若受管文件删除抛出 OSError/PermissionError,绝不能静默 pass 并输出"已回到备份时点"。
|
|
770
|
+
# 必须明确报错中止恢复流程。
|
|
746
771
|
for f in sorted(HOME.rglob("*"), reverse=True):
|
|
747
772
|
if f.is_dir():
|
|
748
773
|
continue
|
|
@@ -757,21 +782,49 @@ def cmd_restore(zip_path: str, yes: bool = False, password: str | None = None,
|
|
|
757
782
|
with _locked(f):
|
|
758
783
|
try:
|
|
759
784
|
f.unlink()
|
|
760
|
-
except OSError:
|
|
761
|
-
|
|
785
|
+
except OSError as unl_err:
|
|
786
|
+
raise RuntimeError(f"exact 恢复清理受管文件失败({rel} 被占用或拒绝):{unl_err}") from unl_err
|
|
762
787
|
if kept:
|
|
763
788
|
head = "、".join(kept[:5]) + (" …" if len(kept) > 5 else "")
|
|
764
789
|
print(f"保留 {len(kept)} 个非灵枢文件(restore 只清自己的东西):{head}")
|
|
765
|
-
|
|
766
|
-
#
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
790
|
+
|
|
791
|
+
# LS-010(v5.59):让恢复过程具备事务回滚能力!
|
|
792
|
+
# 记录所有已替换文件的旧版本备份副本,一旦任意文件 os.replace 失败,
|
|
793
|
+
# 立即逆序原子回滚所有已替换文件,绝不在磁盘留下新旧混合的脏库!
|
|
794
|
+
restored_backups = []
|
|
795
|
+
try:
|
|
796
|
+
for extracted in tmp_dir.rglob("*"):
|
|
797
|
+
if extracted.is_dir():
|
|
798
|
+
continue
|
|
799
|
+
rel = extracted.relative_to(tmp_dir)
|
|
800
|
+
final = (HOME / rel).resolve()
|
|
801
|
+
final.parent.mkdir(parents=True, exist_ok=True)
|
|
802
|
+
bak_curr = None
|
|
803
|
+
if final.exists():
|
|
804
|
+
bak_curr = final.with_name(final.name + f".restore-bak-{os.getpid()}-{int(now_ts() * 1000) % 1000000}")
|
|
805
|
+
try:
|
|
806
|
+
shutil.copy2(final, bak_curr)
|
|
807
|
+
except Exception:
|
|
808
|
+
bak_curr = None
|
|
809
|
+
with _locked(final):
|
|
810
|
+
os.replace(str(extracted), str(final))
|
|
811
|
+
if bak_curr:
|
|
812
|
+
restored_backups.append((final, bak_curr))
|
|
813
|
+
except BaseException as restore_err:
|
|
814
|
+
for target_f, bak_f in reversed(restored_backups):
|
|
815
|
+
try:
|
|
816
|
+
with _locked(target_f):
|
|
817
|
+
os.replace(str(bak_f), str(target_f))
|
|
818
|
+
except Exception:
|
|
819
|
+
pass
|
|
820
|
+
raise restore_err
|
|
821
|
+
finally:
|
|
822
|
+
for _, bak_f in restored_backups:
|
|
823
|
+
try:
|
|
824
|
+
if bak_f.exists():
|
|
825
|
+
os.unlink(bak_f)
|
|
826
|
+
except OSError:
|
|
827
|
+
pass
|
|
775
828
|
except ValueError as exc:
|
|
776
829
|
print(f"[错误] {exc}", file=sys.stderr)
|
|
777
830
|
return 1
|