lingshu-skill 5.70.0 → 5.72.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 +56 -0
- package/SKILL-lite.md +1 -1
- package/SKILL-tiny.md +1 -1
- package/SKILL.md +1 -1
- package/cordis-plugin/lingshu-cron/plugin.js +36 -14
- package/cordis-plugin/lingshu-im/plugin.js +67 -15
- package/manifest.json +36 -36
- package/package.json +3 -2
- package/scripts/assembler.py +8 -2
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +89 -16
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +56 -0
- 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/assembler.py +8 -2
- package/scripts/astrbot_plugin_lingshu/engine/scripts/autotag.py +82 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +13 -2
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +51 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +13 -2
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth_parts.py +5 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +75 -10
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +47 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +12 -2
- package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +47 -27
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +6 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +6 -2
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +68 -21
- package/scripts/astrbot_plugin_lingshu/make_checksums.py +8 -4
- package/scripts/autotag.py +82 -0
- package/scripts/checkpoint.py +13 -2
- package/scripts/dream.py +51 -1
- package/scripts/emotion.py +13 -2
- package/scripts/growth_parts.py +5 -1
- package/scripts/memory.py +75 -10
- package/scripts/panel_cloud.py +47 -1
- package/scripts/panel_server.py +12 -2
- package/scripts/persona.py +47 -27
- package/scripts/safety.py +6 -1
- package/scripts/session_import.py +6 -2
- package/scripts/session_rag.py +68 -21
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""npm postpublish 自动打 tag 并推送(插件市场依赖 GitHub Release 更新版本说明)。
|
|
4
|
+
|
|
5
|
+
背景(2026-12-05 事故):插件市场的「版本说明」读的是 GitHub Release,而 Release
|
|
6
|
+
只由 .github/workflows/release.yml 在**推送 tag** 时触发创建。v5.34-v5.71 从没
|
|
7
|
+
打过 tag,导致 npm 一直发新版、市场却永远停在旧版。
|
|
8
|
+
|
|
9
|
+
用法:package.json 里配
|
|
10
|
+
"scripts": { "postpublish": "python scripts/autotag.py" }
|
|
11
|
+
npm publish 成功后自动执行:本地缺 tag 则补打,并推送 origin(GitHub)与 gitee。
|
|
12
|
+
GitHub 网络不稳时按退避重试;全程失败不阻断(tag 已在本地,下次可手推)。
|
|
13
|
+
"""
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
import re
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
ROOT = Path(__file__).resolve().parent.parent
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def cur_version() -> str:
|
|
24
|
+
t = (ROOT / "SKILL.md").read_text(encoding="utf-8-sig")
|
|
25
|
+
m = re.search(r"^version:\s*([\d.]+)", t, re.M)
|
|
26
|
+
return m.group(1) if m else ""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def run(cmd: list, timeout: int = 60) -> tuple[int, str]:
|
|
30
|
+
try:
|
|
31
|
+
r = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True,
|
|
32
|
+
encoding="utf-8", errors="replace", timeout=timeout)
|
|
33
|
+
return r.returncode, ((r.stdout or "") + (r.stderr or ""))
|
|
34
|
+
except Exception as exc:
|
|
35
|
+
return 1, str(exc)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def main() -> int:
|
|
39
|
+
ver = cur_version()
|
|
40
|
+
if not ver:
|
|
41
|
+
print("[autotag] SKILL.md 读不出 version,跳过", file=sys.stderr)
|
|
42
|
+
return 0
|
|
43
|
+
tag = f"v{ver}"
|
|
44
|
+
# ① 本地已有 → 只补推;没有 → 创建 annotated tag
|
|
45
|
+
rc, out = run(["git", "rev-parse", tag])
|
|
46
|
+
if rc != 0:
|
|
47
|
+
rc, out = run(["git", "tag", "-a", tag,
|
|
48
|
+
"-m", f"lingshu {tag}: auto-tagged by npm postpublish"])
|
|
49
|
+
if rc != 0:
|
|
50
|
+
print(f"[autotag] 创建 tag {tag} 失败:{out[:200]}", file=sys.stderr)
|
|
51
|
+
return 1
|
|
52
|
+
print(f"[autotag] 已创建本地 tag {tag}")
|
|
53
|
+
else:
|
|
54
|
+
print(f"[autotag] 本地 tag {tag} 已存在,只补推")
|
|
55
|
+
# ② 推送到两个远端(GitHub 网络不稳:指数退避重试,最多 4 次)
|
|
56
|
+
ok = []
|
|
57
|
+
for remote in ("origin", "gitee"):
|
|
58
|
+
pushed = False
|
|
59
|
+
for attempt in range(4):
|
|
60
|
+
rc, out = run(["git", "push", remote, tag], timeout=90)
|
|
61
|
+
if rc == 0:
|
|
62
|
+
pushed = True
|
|
63
|
+
break
|
|
64
|
+
wait = 8 * (attempt + 1)
|
|
65
|
+
print(f"[autotag] push {remote} 第 {attempt + 1} 次失败,{wait}s 后重试:"
|
|
66
|
+
f"{out.strip()[-120:]}", file=sys.stderr)
|
|
67
|
+
time.sleep(wait)
|
|
68
|
+
if pushed:
|
|
69
|
+
ok.append(remote)
|
|
70
|
+
else:
|
|
71
|
+
print(f"[autotag] tag {tag} 推送 {remote} 全部重试失败——"
|
|
72
|
+
f"tag 留在本地,网络恢复后手推:git push {remote} {tag}",
|
|
73
|
+
file=sys.stderr)
|
|
74
|
+
if ok:
|
|
75
|
+
print(f"[autotag] tag {tag} 已推送:{', '.join(ok)}"
|
|
76
|
+
f"(GitHub Actions 将自动创建 Release,市场版本说明随之更新)")
|
|
77
|
+
return 0
|
|
78
|
+
return 1
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
if __name__ == "__main__":
|
|
82
|
+
sys.exit(main())
|
package/scripts/checkpoint.py
CHANGED
|
@@ -143,7 +143,13 @@ def collect(repo: str | None = None) -> dict | None:
|
|
|
143
143
|
|
|
144
144
|
|
|
145
145
|
def decide(ev: dict, state: dict, force: bool = False) -> dict:
|
|
146
|
-
"""是否需要写:HEAD 变了 /
|
|
146
|
+
"""是否需要写:HEAD 变了 / 工作区有**新**改动 / 强制。
|
|
147
|
+
|
|
148
|
+
LS-054(v5.71):避免同一脏工作区重复 checkpoint!
|
|
149
|
+
旧实现只看 `ev["changed"] > 0`——HEAD 没动、脏文件也没增减时(cron 每轮
|
|
150
|
+
收尾都会触发),同一份脏工作区会被反复 remember 成重复记忆。
|
|
151
|
+
现在同时比较上次记录的 changed 数:HEAD 与改动数均未变化 → 不重复记。
|
|
152
|
+
"""
|
|
147
153
|
prev = state.get(ev["repo"]) or {}
|
|
148
154
|
if force:
|
|
149
155
|
return {"write": True, "reason": "force"}
|
|
@@ -151,8 +157,13 @@ def decide(ev: dict, state: dict, force: bool = False) -> dict:
|
|
|
151
157
|
return {"write": True, "reason": "首次收尾"}
|
|
152
158
|
if prev.get("head") != ev["head"]:
|
|
153
159
|
return {"write": True, "reason": f"HEAD {prev.get('head', '?')} → {ev['head']}"}
|
|
160
|
+
_prev_changed = prev.get("changed")
|
|
154
161
|
if ev["changed"] > 0:
|
|
155
|
-
|
|
162
|
+
if _prev_changed == ev["changed"]:
|
|
163
|
+
return {"write": False,
|
|
164
|
+
"reason": f"HEAD 与改动数均未变化({ev['changed']} 处),不重复记"}
|
|
165
|
+
return {"write": True,
|
|
166
|
+
"reason": f"工作区改动 {_prev_changed} → {ev['changed']} 处"}
|
|
156
167
|
return {"write": False, "reason": "与上次收尾一致,不重复记"}
|
|
157
168
|
|
|
158
169
|
|
package/scripts/dream.py
CHANGED
|
@@ -766,7 +766,12 @@ def dream(trigger: str = "manual", dry_run: bool = False) -> dict:
|
|
|
766
766
|
"persona_updates": {"mood": {"value": "这次聊完的情绪", "reason": "..."},
|
|
767
767
|
"traits": {"幽默": 2},
|
|
768
768
|
"habits": [{"name": "深夜更容易说真话", "evidence": "..."}],
|
|
769
|
-
"likes": [], "dislikes": [], "insights": []
|
|
769
|
+
"likes": [], "dislikes": [], "insights": [],
|
|
770
|
+
"_prompt": "人格要随相处慢慢长:likes/dislikes 填这批记忆里"
|
|
771
|
+
"新出现的、稳定的用户偏好或反感(带证据 source_ids);"
|
|
772
|
+
"traits 填 -10~10 的倾向微调(如 {\"好奇\": 2});"
|
|
773
|
+
"insights 填对自己���新认识。只在确有多条一致证据时提,"
|
|
774
|
+
"宁缺勿滥。"},
|
|
770
775
|
"forget": ["m_..."],
|
|
771
776
|
"narrative": "这次梦的叙述(可选)",
|
|
772
777
|
},
|
|
@@ -787,6 +792,30 @@ def dream(trigger: str = "manual", dry_run: bool = False) -> dict:
|
|
|
787
792
|
keep_old = True
|
|
788
793
|
log_event("dream", f"已有未整理的梦(task_id={old['task_id']},"
|
|
789
794
|
f"{age / 3600:.1f}h 前触发),本次不重复生成新任务", level="warn")
|
|
795
|
+
# LS-030(v5.71):避免旧 pending 导致新簇永久丢失!
|
|
796
|
+
# 沿用旧任务时 new_pending 不写盘——本次新提取的簇原本会静默消失。
|
|
797
|
+
# 现在把新簇**合并进旧 pending 的 clusters**:task_id 保持不变
|
|
798
|
+
# (AI 拿到的 apply_schema 不失效),新碎片纳入同一场整理。
|
|
799
|
+
if clusters:
|
|
800
|
+
try:
|
|
801
|
+
_old_clusters = old.get("clusters") or []
|
|
802
|
+
_merged = _old_clusters + list(clusters)
|
|
803
|
+
old["clusters"] = _merged
|
|
804
|
+
# report 里的簇计数只属于本场,供日志观察合并规模
|
|
805
|
+
old.setdefault("report", {})
|
|
806
|
+
atomic_json(HOME / "dreams" / "pending.json", old)
|
|
807
|
+
log_event("dream",
|
|
808
|
+
f"新簇已并入未整理任务(+{len(clusters)} 组,"
|
|
809
|
+
f"合并后 {len(_merged)} 组)", level="info")
|
|
810
|
+
except Exception as _mg:
|
|
811
|
+
log_event("dream", f"新簇并入 pending 失败(新簇暂存 orphaned):{_mg}",
|
|
812
|
+
level="warn")
|
|
813
|
+
try:
|
|
814
|
+
atomic_json(HOME / "dreams" / f"orphaned_{task_id}_newclusters.json",
|
|
815
|
+
{"task_id": task_id, "clusters": clusters,
|
|
816
|
+
"created": now})
|
|
817
|
+
except Exception:
|
|
818
|
+
pass
|
|
790
819
|
else:
|
|
791
820
|
orphan_path = HOME / "dreams" / f"orphaned_{old['task_id']}.json"
|
|
792
821
|
atomic_json(orphan_path, old)
|
|
@@ -1037,9 +1066,30 @@ def apply_dream(result: dict) -> dict:
|
|
|
1037
1066
|
# AI 整理出来的记忆先标"待审核":防止做梦合并/编造的内容直接当事实沉淀。
|
|
1038
1067
|
# 例外:机械聚合摘要(aggregate=True)只是把 N 条原文用「;」连起来的派生视图,
|
|
1039
1068
|
# 没有可审的"新事实",进待审只会每天占住"待审核1条"(P9 #64)。
|
|
1069
|
+
# LS-032(v5.71):禁止 aggregate 标志绕过审核!
|
|
1070
|
+
# AI 结果里 aggregate 可以被任意伪造(想跳审核就标 true)。
|
|
1071
|
+
# 现在必须验证正文确实是源原文的「;」机械拼接才放行——内容与
|
|
1072
|
+
# source_ids 指向的原文完全一致才算机械视图��否则一律进待审。
|
|
1073
|
+
_is_mechanical = False
|
|
1040
1074
|
if item.get("aggregate"):
|
|
1075
|
+
_src_ids = [x for x in (item.get("source_ids") or []) if isinstance(x, str)]
|
|
1076
|
+
if _src_ids:
|
|
1077
|
+
_src_texts = []
|
|
1078
|
+
_by_id = {m.get("id"): m for m in records if isinstance(m, dict)}
|
|
1079
|
+
for _sid in _src_ids:
|
|
1080
|
+
_sm = _by_id.get(_sid)
|
|
1081
|
+
if _sm is not None and str(_sm.get("text") or "").strip():
|
|
1082
|
+
_src_texts.append(str(_sm.get("text")).strip())
|
|
1083
|
+
if _src_texts:
|
|
1084
|
+
_joined = ";".join(_src_texts)
|
|
1085
|
+
# 正文与机械拼接一致(允许首尾空白差异)才算真聚合
|
|
1086
|
+
_is_mechanical = text.strip() == _joined.strip()
|
|
1087
|
+
if _is_mechanical:
|
|
1041
1088
|
rec["aggregate"] = True
|
|
1042
1089
|
else:
|
|
1090
|
+
if item.get("aggregate"):
|
|
1091
|
+
applied["rejected"].append(
|
|
1092
|
+
"aggregate 标志未通过机械聚合校验(正文≠源原文拼接),已改入待审")
|
|
1043
1093
|
rec["review"] = "pending"
|
|
1044
1094
|
rec["review_source"] = "dream"
|
|
1045
1095
|
# #46 Memex 索引解引用:合并/蒸馏产物带 evidence_ids 指针(指向原始证据记忆),
|
package/scripts/emotion.py
CHANGED
|
@@ -1090,13 +1090,24 @@ def emotion_arc(days: int = 7) -> dict:
|
|
|
1090
1090
|
# 原依赖 brain.py 的星号合并命名空间——单独 import emotion 就 NameError
|
|
1091
1091
|
# (实测:persona.daily_drift 调 _emo.feel 时崩 "load_persona is not defined")。
|
|
1092
1092
|
# 这里补一个安全的本地绑定:优先用已有合并名,缺失则直接取 persona 模块的实现。
|
|
1093
|
+
# LS-028(v5.71):补齐 emotion.py 独立导入依赖——mind_state / default_onboarding
|
|
1094
|
+
# 同样定义在 persona.py(rational() 等运行路径会用到),一并纳入回退绑定。
|
|
1093
1095
|
try:
|
|
1094
|
-
load_persona # noqa: B018 已由 brain 合并命名空间提供
|
|
1096
|
+
load_persona, mind_state # noqa: B018 已由 brain 合并命名空间提供
|
|
1095
1097
|
except NameError: # pragma: no cover - 仅在单独 import 时触发
|
|
1096
1098
|
try:
|
|
1097
|
-
from persona import load_persona, save_persona
|
|
1099
|
+
from persona import (load_persona, save_persona, mind_state,
|
|
1100
|
+
default_onboarding) # type: ignore
|
|
1098
1101
|
except Exception:
|
|
1099
1102
|
pass
|
|
1103
|
+
else:
|
|
1104
|
+
try:
|
|
1105
|
+
mind_state # noqa: B018
|
|
1106
|
+
except NameError:
|
|
1107
|
+
try:
|
|
1108
|
+
from persona import mind_state # type: ignore
|
|
1109
|
+
except Exception:
|
|
1110
|
+
pass
|
|
1100
1111
|
|
|
1101
1112
|
|
|
1102
1113
|
def emotion_cfg() -> dict:
|
package/scripts/growth_parts.py
CHANGED
|
@@ -95,7 +95,11 @@ def parse_frontmatter(text: str) -> tuple:
|
|
|
95
95
|
以及常见简写(值里含冒号、以 # 开头)。够读 DSH / Claude / Trae 各家的 SKILL.md。
|
|
96
96
|
"""
|
|
97
97
|
text = text.lstrip("\ufeff")
|
|
98
|
-
|
|
98
|
+
# LS-055(v5.71):开界与闭界采用一致的整行判断!
|
|
99
|
+
# 旧写法 startswith("---") 会把 "---not-a-delimiter" 这种**整行**误当开界,
|
|
100
|
+
# 吞掉后面的正文。开界必须也是独立成行的 "---"(行尾只允许空白)。
|
|
101
|
+
_first_line = text.split("\n", 1)[0].rstrip()
|
|
102
|
+
if _first_line != "---":
|
|
99
103
|
return {}, text
|
|
100
104
|
# 闭界必须是整行 "---"(行尾可带空白):裸 find("\n---") 会把正文里
|
|
101
105
|
# "---xxx" 这类行误当边界,导致 head 被提前截断
|
package/scripts/memory.py
CHANGED
|
@@ -460,11 +460,19 @@ def bulk_memory_action(ids: list, action: str, value=None) -> dict:
|
|
|
460
460
|
raise ValueError("没有可用的标签")
|
|
461
461
|
want = set(ids)
|
|
462
462
|
updated = 0
|
|
463
|
+
skipped_pinned: list = []
|
|
463
464
|
with _locked(HOME / "hippocampus.jsonl"):
|
|
464
465
|
records = load_all()
|
|
465
466
|
for m in records:
|
|
466
467
|
if m.get("id") not in want:
|
|
467
468
|
continue
|
|
469
|
+
# LS-023(v5.71):批量操作遵守置顶保护!
|
|
470
|
+
# 单条 forget / set_memory_review(discard) / apply_dream(forget) 都
|
|
471
|
+
# 硬拒置顶记忆,但批量 discard/delete 原来不看 pinned——面板一次
|
|
472
|
+
# 全选就能把置顶记忆扫进淡忘区。现在口径统一:置顶记忆跳过并如实回报。
|
|
473
|
+
if action in ("discard", "delete") and m.get("pinned") and m.get("layer") != "dust":
|
|
474
|
+
skipped_pinned.append(m["id"])
|
|
475
|
+
continue
|
|
468
476
|
if action == "confirm":
|
|
469
477
|
m["review"] = "confirmed"
|
|
470
478
|
m["review_at"] = now_ts()
|
|
@@ -507,6 +515,7 @@ def bulk_memory_action(ids: list, action: str, value=None) -> dict:
|
|
|
507
515
|
# v4 #32:批量操作审计(含批量 delete/importance 等)
|
|
508
516
|
audit_log("panel", f"bulk_{action}", f"{len(ids)}条", f"成功 {updated} 条")
|
|
509
517
|
return {"updated": updated, "requested": len(ids), "action": action,
|
|
518
|
+
"skipped_pinned": skipped_pinned,
|
|
510
519
|
"review_counts": review_counts()}
|
|
511
520
|
|
|
512
521
|
|
|
@@ -2465,9 +2474,29 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
|
|
|
2465
2474
|
if not str(m.get("agent_id") or "").strip()
|
|
2466
2475
|
or str(m.get("agent_id")).strip() == aid]
|
|
2467
2476
|
if include_archive:
|
|
2477
|
+
# LS-019(v5.71):保留缺少 ID 的旧归档记录!
|
|
2478
|
+
# 旧实现 `if m.get("id")` 把无 id 的老归档记录整条丢弃——这些是
|
|
2479
|
+
# 早期版本写入的历史,静默丢失。现在按 load_all 同款做法合成稳定
|
|
2480
|
+
# 内容哈希 id(仅内存内生效,不写回 archive.jsonl)。
|
|
2481
|
+
import hashlib as _hashlib
|
|
2482
|
+
_raw_archive = load_archive()
|
|
2483
|
+
archive = []
|
|
2484
|
+
for m in _raw_archive:
|
|
2485
|
+
if not isinstance(m, dict):
|
|
2486
|
+
continue
|
|
2487
|
+
if not m.get("id"):
|
|
2488
|
+
_m = dict(m)
|
|
2489
|
+
try:
|
|
2490
|
+
_seed = json.dumps({k: _m.get(k) for k in
|
|
2491
|
+
("text", "kind", "created", "layer", "gist")},
|
|
2492
|
+
ensure_ascii=False, sort_keys=True, default=str)
|
|
2493
|
+
_m["id"] = "m_" + _hashlib.sha1(_seed.encode("utf-8")).hexdigest()[:12]
|
|
2494
|
+
except Exception:
|
|
2495
|
+
_m["id"] = "m_archive_noid"
|
|
2496
|
+
m = _m
|
|
2497
|
+
if _channel_visible(m, channel, group_id, user):
|
|
2498
|
+
archive.append(m)
|
|
2468
2499
|
# LS-004(v5.58):归档召回同样必须执行 agent_id 隔离。
|
|
2469
|
-
archive = [m for m in load_archive() if m.get("id")
|
|
2470
|
-
and _channel_visible(m, channel, group_id, user)]
|
|
2471
2500
|
if agent_id:
|
|
2472
2501
|
aid = str(agent_id).strip()
|
|
2473
2502
|
archive = [m for m in archive
|
|
@@ -3173,8 +3202,19 @@ def trash_restore(memory_id: str) -> dict:
|
|
|
3173
3202
|
except Exception:
|
|
3174
3203
|
keep.append(line)
|
|
3175
3204
|
continue
|
|
3176
|
-
if row.get("id") == memory_id
|
|
3177
|
-
|
|
3205
|
+
if row.get("id") == memory_id:
|
|
3206
|
+
# LS-021(v5.71):台账恢复应选取最新版本!
|
|
3207
|
+
# 同一记忆可能被删除多次(删→复存→再删),台账里有多条同 id 记录。
|
|
3208
|
+
# 旧实现取文件里的第一条(可能是最旧版本),恢复回的是过期内容。
|
|
3209
|
+
# 现在按 deleted_at 比较,始终保留时间戳最新的那条。
|
|
3210
|
+
if (target is None
|
|
3211
|
+
or _num(row.get("deleted_at"), 0) > _num(target.get("deleted_at"), 0)):
|
|
3212
|
+
# 之前选中的旧版本行要留在台账里(其他 restore 仍可能需要)
|
|
3213
|
+
if target is not None:
|
|
3214
|
+
keep.append(json.dumps(target, ensure_ascii=False))
|
|
3215
|
+
target = row
|
|
3216
|
+
else:
|
|
3217
|
+
keep.append(line)
|
|
3178
3218
|
else:
|
|
3179
3219
|
keep.append(line)
|
|
3180
3220
|
if target is None:
|
|
@@ -3246,7 +3286,13 @@ def purge(memory_id: str, confirm_token: str) -> dict:
|
|
|
3246
3286
|
target = next((m for m in archive if m.get("id") == memory_id), None)
|
|
3247
3287
|
if not target:
|
|
3248
3288
|
raise ValueError(f"没有这条记忆:{memory_id}")
|
|
3249
|
-
|
|
3289
|
+
# LS-020(v5.71):归档分支同样禁止异常时间戳绕过冷静期
|
|
3290
|
+
_raw_aa = target.get("archived_at") or target.get("forgotten_at")
|
|
3291
|
+
archived_at = _num(_raw_aa, -1)
|
|
3292
|
+
if archived_at <= 0:
|
|
3293
|
+
raise ValueError(
|
|
3294
|
+
f"这条归档记忆的时间戳缺失或无效(archived_at={_raw_aa!r}),"
|
|
3295
|
+
f"无法确认已过 {_PURGE_COOLDOWN_DAYS} 天冷静期,拒绝物理删除。")
|
|
3250
3296
|
if archived_at > cutoff:
|
|
3251
3297
|
raise ValueError(
|
|
3252
3298
|
f"归档记忆需冷静满 {_PURGE_COOLDOWN_DAYS} 天后才能物理删除"
|
|
@@ -3267,7 +3313,17 @@ def purge(memory_id: str, confirm_token: str) -> dict:
|
|
|
3267
3313
|
raise ValueError(
|
|
3268
3314
|
f"只有淡忘区(dust)的记忆才能物理删除,当前层:{target.get('layer')}。"
|
|
3269
3315
|
f"先 `memory forget {memory_id}` 转 dust,满 {_PURGE_COOLDOWN_DAYS} 天后再 purge。")
|
|
3270
|
-
|
|
3316
|
+
# LS-020(v5.71):禁止异常删除时间戳绕过冷静期!
|
|
3317
|
+
# 旧实现 _num(forgotten_at, 0) 把缺失/坏值当 0 —— 0 恒小于 cutoff,
|
|
3318
|
+
# 冷静期检查形同虚设,脏数据记忆可直接物理删除。现在 fail-closed:
|
|
3319
|
+
# 时间戳缺失或无法解析时拒绝 purge,要求先修正记录。
|
|
3320
|
+
_raw_fa = target.get("forgotten_at")
|
|
3321
|
+
forgotten_at = _num(_raw_fa, -1)
|
|
3322
|
+
if forgotten_at <= 0:
|
|
3323
|
+
raise ValueError(
|
|
3324
|
+
f"这条记忆的淡忘时间戳缺失或无效(forgotten_at={_raw_fa!r}),"
|
|
3325
|
+
f"无法确认已过 {_PURGE_COOLDOWN_DAYS} 天冷静期,拒绝物理删除。"
|
|
3326
|
+
"请先修复该记录的时间戳或用 forget 重新淡忘。")
|
|
3271
3327
|
if forgotten_at > cutoff:
|
|
3272
3328
|
raise ValueError(
|
|
3273
3329
|
f"淡忘记忆需冷静满 {_PURGE_COOLDOWN_DAYS} 天后才能物理删除"
|
|
@@ -4365,16 +4421,25 @@ def render_prior(p: dict, budget_chars: int = 1400) -> str:
|
|
|
4365
4421
|
|
|
4366
4422
|
|
|
4367
4423
|
def _lessons_injection(query: str = "") -> str:
|
|
4368
|
-
"""注入包小节:active 教训按 confidence 注入,命中 query 的排最前并标「已有教训」。
|
|
4424
|
+
"""注入包小节:active 教训按 confidence 注入,命中 query 的排最前并标「已有教训」。
|
|
4425
|
+
|
|
4426
|
+
TOKEN-TRIM(v5.72):教训正文可能把"被取代历史"整段带进来(错误闭环会把
|
|
4427
|
+
新旧结论一起写进 text),注入时截断到前 160 字符——教训是拿来用的提醒,
|
|
4428
|
+
不是完整调查报告;置信度注脚只在已验证 ≥1 次时才显示(0 次的注脚没信息量)。
|
|
4429
|
+
"""
|
|
4369
4430
|
ls = injectable_lessons(query, k=5)
|
|
4370
4431
|
if not ls:
|
|
4371
4432
|
return ""
|
|
4372
4433
|
lines = []
|
|
4373
4434
|
for l in ls:
|
|
4374
4435
|
mark = "已有教训" if query and l.get("_hit") else "教训"
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4436
|
+
_txt = str(l.get("text") or "").strip()
|
|
4437
|
+
if len(_txt) > 160:
|
|
4438
|
+
_txt = _txt[:160].rstrip() + "…"
|
|
4439
|
+
_v = int(_num(l.get("times_validated"), 0))
|
|
4440
|
+
conf = f"(已验证{_v}次)" if _v >= 1 else ""
|
|
4441
|
+
lines.append(f"- [{mark}] {_txt}{conf}")
|
|
4442
|
+
return "\n## 教训(先看坑再用)\n" + "\n".join(lines)
|
|
4378
4443
|
|
|
4379
4444
|
|
|
4380
4445
|
# ---------------------------------------------------------------- 记忆关联(联想能力)
|
package/scripts/panel_cloud.py
CHANGED
|
@@ -25,6 +25,7 @@ import base64
|
|
|
25
25
|
import hashlib
|
|
26
26
|
import json
|
|
27
27
|
import os
|
|
28
|
+
import threading
|
|
28
29
|
import time
|
|
29
30
|
import urllib.error
|
|
30
31
|
import urllib.request
|
|
@@ -413,6 +414,11 @@ def cloud_extension_download(ext_id: str) -> dict:
|
|
|
413
414
|
raise FileExistsError("该拓展已安装,请先删除 extensions/installed 下同名目录")
|
|
414
415
|
with zipfile.ZipFile(io.BytesIO(raw)) as z:
|
|
415
416
|
names = z.namelist()
|
|
417
|
+
# LS-068(v5.71):拒绝空扩展 ZIP 安装成功!
|
|
418
|
+
# 旧实现只查文件数上限——空包(0 个文件)也能"安装成功",装出一个
|
|
419
|
+
# 空目录还显示"已安装"。现在要求至少一个有效文件。
|
|
420
|
+
if not names or all(n.endswith("/") for n in names):
|
|
421
|
+
raise ValueError("拓展包是空的(没有任何文件),拒绝安装")
|
|
416
422
|
if len(names) > panels.ZIP_MAX_FILES:
|
|
417
423
|
raise ValueError("拓展包文件数超限")
|
|
418
424
|
total = sum(i.file_size for i in z.infolist())
|
|
@@ -464,7 +470,25 @@ def _safe_name(name: str) -> bool:
|
|
|
464
470
|
|
|
465
471
|
|
|
466
472
|
def cloud_shot(name: str, ext: str) -> bytes:
|
|
467
|
-
"""取云端截图字节(前端 <img> 直连本机代理端点,避免跨域/混合内容问题)。
|
|
473
|
+
"""取云端截图字节(前端 <img> 直连本机代理端点,避免跨域/混合内容问题)。
|
|
474
|
+
|
|
475
|
+
LS-062(v5.71):统一截图清单字段与读取参数!
|
|
476
|
+
清单里 `screenshot` 存的是**完整文件名**(如 "demo.png"),而旧实现要求
|
|
477
|
+
调用方把 ext 拆成 ".png" 单独传——前端直接把清单字段塞进 ext 参数时,
|
|
478
|
+
拼出 "shots/demo{demo.png}" 这种不存在的路径。现在兼容两种传法:
|
|
479
|
+
ext 以 "." 开头按扩展名处理;否则视为完整文件名(忽略多余的 name 前缀)。
|
|
480
|
+
"""
|
|
481
|
+
ext = str(ext or "").strip()
|
|
482
|
+
if not ext.startswith("."):
|
|
483
|
+
# 传入的是完整文件名(清单 screenshot 字段):剥掉 name 前缀留扩展名
|
|
484
|
+
_fname = ext.lower()
|
|
485
|
+
if _fname == str(name).strip().lower():
|
|
486
|
+
ext = ".png" # 只给了面板名(老清单只有名字):用默认 png
|
|
487
|
+
elif _fname.startswith(str(name).strip().lower()):
|
|
488
|
+
ext = _fname[len(str(name).strip()):]
|
|
489
|
+
if not ext.startswith("."):
|
|
490
|
+
ext = Path(ext).suffix or ".png"
|
|
491
|
+
ext = ext.lower()
|
|
468
492
|
if ext not in SHOT_WHITELIST:
|
|
469
493
|
raise ValueError("截图扩展名不支持")
|
|
470
494
|
c = _cfg()
|
|
@@ -615,12 +639,34 @@ def _push_one(kind: str, repo: str, token: str, branch: str, name: str,
|
|
|
615
639
|
|
|
616
640
|
kind_key 决定子目录与清单键:panels → panels/xxx.zip + index.json.panels,
|
|
617
641
|
extensions → extensions/xxx.zip + index.json.extensions(同一份 index.json)。
|
|
642
|
+
|
|
643
|
+
LS-067(v5.71):防止云发布并发覆盖共享 index!
|
|
644
|
+
旧实现的"读旧清单→合并→回写"在两个发布同时跑时会互相覆盖:
|
|
645
|
+
A 读到旧清单、B 读到旧清单、A 写回(带 A 条目)、B 写回(**丢掉 A 条目**)。
|
|
646
|
+
现在用进程级互斥锁串行化"读-改-写"窗口;锁只保护本机并发,
|
|
647
|
+
跨机器场景靠回写前二次读取对比 updated 做最后防线。
|
|
618
648
|
"""
|
|
649
|
+
global _PUBLISH_LOCK
|
|
619
650
|
put = _gitee_put if kind == "gitee" else _github_put
|
|
620
651
|
get = _gitee_get if kind == "gitee" else _github_get
|
|
621
652
|
put(repo, f"{kind_key}/{name}.zip", token, branch, zbytes, msg, author)
|
|
622
653
|
if shot is not None:
|
|
623
654
|
put(repo, f"shots/{name}{shot_ext}", token, branch, shot, msg, author)
|
|
655
|
+
with _PUBLISH_LOCK:
|
|
656
|
+
_push_index_entry(kind, repo, token, branch, name, entry, msg,
|
|
657
|
+
kind_key=kind_key, author=author)
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
# LS-067: 云发布共享 index 的读-改-写互斥锁(进程级;个人市场单机足够)
|
|
661
|
+
_PUBLISH_LOCK = threading.Lock()
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def _push_index_entry(kind: str, repo: str, token: str, branch: str, name: str,
|
|
665
|
+
entry: dict, msg: str, kind_key: str = "panels",
|
|
666
|
+
author: dict | None = None) -> None:
|
|
667
|
+
"""index.json 合并回写(必须在 _PUBLISH_LOCK 内调用)。"""
|
|
668
|
+
put = _gitee_put if kind == "gitee" else _github_put
|
|
669
|
+
get = _gitee_get if kind == "gitee" else _github_get
|
|
624
670
|
# index.json 合并回写:读旧清单 → 覆盖同名条目 → 写回(并发竞争可接受,个人市场)
|
|
625
671
|
#
|
|
626
672
|
# ⚠ fail-closed:**只有"清单确实不存在"才可以新建空清单**。
|
package/scripts/panel_server.py
CHANGED
|
@@ -2190,9 +2190,18 @@ def _api_skill(self, path, data):
|
|
|
2190
2190
|
res = growth.install_skill(_name, force=bool(data.get("force")), from_dir=_from,
|
|
2191
2191
|
accept_risk=risk_ok)
|
|
2192
2192
|
self._json({"ok": True, "result": res, "skill": res, "workspace": workspace()})
|
|
2193
|
-
elif act == "uninstall":
|
|
2193
|
+
elif act == "uninstall" or act == "delete":
|
|
2194
|
+
# LS-085(v5.71):统一技能操作的 action 协议——delete 是前端实际发送的名字
|
|
2194
2195
|
res = growth.uninstall_skill(data.get("name", ""), managed_only=True)
|
|
2195
2196
|
self._json({"ok": True, "skill": res, "workspace": workspace()})
|
|
2197
|
+
elif act == "check":
|
|
2198
|
+
# LS-085: 自检 = 列出技能区 + 全局根目录状态(前端"自检"按钮走这条)
|
|
2199
|
+
res = growth.scan_skills()
|
|
2200
|
+
self._json({"ok": True, "skills": res, "workspace": workspace()})
|
|
2201
|
+
elif act == "show":
|
|
2202
|
+
# LS-085: show = locate(前端查看/编辑入口用它定位技能)
|
|
2203
|
+
res = growth.locate_skill(data.get("name", ""), data.get("root"))
|
|
2204
|
+
self._json({"ok": True, "skill": res})
|
|
2196
2205
|
elif act == "use":
|
|
2197
2206
|
res = growth.locate_skill(data.get("name", ""), data.get("root"))
|
|
2198
2207
|
self._json({"ok": True, "skill": res})
|
|
@@ -2203,7 +2212,8 @@ def _api_skill(self, path, data):
|
|
|
2203
2212
|
elif act == "root_add":
|
|
2204
2213
|
res = growth.add_skill_root(data.get("path", ""))
|
|
2205
2214
|
self._json({"ok": True, "result": res, "workspace": workspace()})
|
|
2206
|
-
elif act == "root_remove":
|
|
2215
|
+
elif act == "root_remove" or act == "root_rm":
|
|
2216
|
+
# LS-085: root_rm 是前端实际发送的名字(与 root_remove 同义)
|
|
2207
2217
|
res = growth.remove_skill_root(data.get("path", ""))
|
|
2208
2218
|
self._json({"ok": True, "result": res, "workspace": workspace()})
|
|
2209
2219
|
elif act == "scan":
|
package/scripts/persona.py
CHANGED
|
@@ -350,10 +350,12 @@ def load_persona() -> dict:
|
|
|
350
350
|
log_event("persona", "检测到人格空态,已自动从 persona.lastgood.json 回滚", level="warn")
|
|
351
351
|
# AUTOHEAL-COMMIT(v5.56):立即写回盘,否则下次 load 又读到空态 →
|
|
352
352
|
# 反复回滚 + 反复告警(实测 5 分钟刷 78 条 warn)。写回失败不影响返回值。
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
353
|
+
# LS-026(v5.71):人格自愈绝不能在只读模式写盘!
|
|
354
|
+
if not READONLY:
|
|
355
|
+
try:
|
|
356
|
+
atomic_json(HOME / "persona.json", _good)
|
|
357
|
+
except Exception:
|
|
358
|
+
pass
|
|
357
359
|
except Exception:
|
|
358
360
|
pass
|
|
359
361
|
|
|
@@ -426,8 +428,12 @@ def save_persona(p: dict) -> None:
|
|
|
426
428
|
atomic_json(HOME / "persona.json", p)
|
|
427
429
|
# PERSONA-AUTOHEAL(v5.54):每次成功保存"有名字"的人格,同步留一份 lastgood。
|
|
428
430
|
# 这样无论哪条路径把人格写空,load_persona 都能自动回滚——不再依赖人工恢复。
|
|
431
|
+
# LS-027(v5.71):写回 lastgood 前执行完整结构校验!
|
|
432
|
+
# lastgood 是人格的最后一道网——若把带坏字段的人格快照进去,
|
|
433
|
+
# 空态回滚时会原样恢复坏数据。校验失败绝不留底(宁缺勿错)。
|
|
429
434
|
try:
|
|
430
435
|
if str(((p.get("identity") or {}).get("名字") or "")).strip():
|
|
436
|
+
_validate_persona_struct(p, "persona.lastgood.json")
|
|
431
437
|
atomic_json(HOME / "persona.lastgood.json", p)
|
|
432
438
|
except Exception:
|
|
433
439
|
pass
|
|
@@ -647,39 +653,43 @@ def persona_brief(p: dict, mood: bool = True) -> str:
|
|
|
647
653
|
if ident.get("自称"):
|
|
648
654
|
lines.append(f"我自称:{ident['自称']};称呼对方:{ident.get('称呼你') or ident.get('称呼用户') or '你'}。")
|
|
649
655
|
traits = p.get("traits", {})
|
|
656
|
+
drives = p.get("drives") or {}
|
|
657
|
+
# 与 mind_state() 同一套兜底:traits 已有数值而 drives 还空时,别在自我
|
|
658
|
+
# 描述里一边「性格:好奇85」一边「内驱:还没有数值」——自相矛盾每轮被读。
|
|
659
|
+
if drives.get("curiosity") is None and drives.get("reason") is None:
|
|
660
|
+
_t = p.get("traits") or {}
|
|
661
|
+
if _t.get("好奇") is not None or _t.get("理智") is not None:
|
|
662
|
+
drives = {"curiosity": trait_value(_t["好奇"]) if _t.get("好奇") is not None else None,
|
|
663
|
+
"reason": trait_value(_t["理智"]) if _t.get("理智") is not None else None}
|
|
650
664
|
if traits:
|
|
651
|
-
#
|
|
665
|
+
# TOKEN-TRIM(v5.72):性格+内驱合并成一行、砍掉长解释——
|
|
666
|
+
# 旧写法两行带「初识时用户指定(0-100,数值来自我们相处中真实发生过的事)」
|
|
667
|
+
# 和「理智先算值不值得深想……」两段固定说明,每轮注入都重复占 token。
|
|
668
|
+
# 现在格式:「性格 值(内驱 值)—— 一句来源」;内驱与性格同值时只写一次。
|
|
652
669
|
top = sorted(traits.items(), key=lambda x: trait_value(x[1]), reverse=True)
|
|
653
670
|
tb = p.get("traits_baseline") if isinstance(p.get("traits_baseline"), dict) else {}
|
|
654
671
|
parts = []
|
|
655
672
|
for k, v in top[:3]:
|
|
656
673
|
meta = trait_meta(v)
|
|
657
|
-
# 五-F:离基线够远时标一句,模型知道"这不是我本来的样子,会慢慢回落"
|
|
658
674
|
b = tb.get(k)
|
|
659
675
|
bv = _trait_int(b.get("value")) if isinstance(b, dict) else None
|
|
660
|
-
gap = "" if bv is None or abs(trait_value(v) - bv) < 15 else f"
|
|
661
|
-
|
|
662
|
-
|
|
676
|
+
gap = "" if bv is None or abs(trait_value(v) - bv) < 15 else f"(基线{bv})"
|
|
677
|
+
_why = meta.get("why") or ""
|
|
678
|
+
# why 只留短因(≤12 字),超长截断——「初识时用户指定」这类模板话不必全量注入
|
|
679
|
+
_why = _why[:12] + "…" if len(_why) > 12 else _why
|
|
680
|
+
parts.append(f"{k}{trait_value(v):.0f}{gap}" + (f"—{_why}" if _why else ""))
|
|
681
|
+
line = "性格:" + ";".join(parts)
|
|
663
682
|
low = [(k, v) for k, v in top[-2:] if trait_value(v) < 50]
|
|
664
683
|
if low:
|
|
665
684
|
lows = "、".join(f"{k}{trait_value(v):.0f}" for k, v in low)
|
|
666
685
|
line += f";偏低:{lows}"
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
# 描述里一边「性格:好奇85」一边「内驱:还没有数值」——自相矛盾每轮被读。
|
|
673
|
-
if drives.get("curiosity") is None and drives.get("reason") is None:
|
|
674
|
-
_t = p.get("traits") or {}
|
|
675
|
-
if _t.get("好奇") is not None or _t.get("理智") is not None:
|
|
676
|
-
drives = {"curiosity": trait_value(_t["好奇"]) if _t.get("好奇") is not None else None,
|
|
677
|
-
"reason": trait_value(_t["理智"]) if _t.get("理智") is not None else None}
|
|
678
|
-
if drives.get("curiosity") is not None or drives.get("reason") is not None:
|
|
679
|
-
lines.append(f"我的内驱:好奇心 {drives.get('curiosity', '未成形')} / 理智 {drives.get('reason', '未成形')}"
|
|
680
|
-
"(理智先算值不值得深想,好奇心负责找新问题)。")
|
|
686
|
+
# 内驱与性格同源时合并展示,避免"好奇80 / 好奇心88"两行并排的观感重复
|
|
687
|
+
_cur, _rea = drives.get("curiosity"), drives.get("reason")
|
|
688
|
+
if isinstance(_cur, (int, float)) and isinstance(_rea, (int, float)):
|
|
689
|
+
line += f";内驱 好奇{_cur:.0f}/理智{_rea:.0f}"
|
|
690
|
+
lines.append(line + "。")
|
|
681
691
|
else:
|
|
682
|
-
lines.append("
|
|
692
|
+
lines.append("性格:还没有。等初识时问用户,用户不知道就由我自己定。")
|
|
683
693
|
if p.get("style"):
|
|
684
694
|
lines.append("我说话的方式:" + ";".join(p["style"][:5]) + "。")
|
|
685
695
|
if p.get("values"):
|
|
@@ -706,11 +716,21 @@ def persona_brief(p: dict, mood: bool = True) -> str:
|
|
|
706
716
|
# 自认识概览:擅长/短板/还没弄清——只在自己真的积累了认知时才说,空块不出声
|
|
707
717
|
sm = p.get("self_model") if isinstance(p.get("self_model"), dict) else {}
|
|
708
718
|
if sm.get("strengths"):
|
|
709
|
-
|
|
719
|
+
_st = [s[:80].rstrip() + "…" if len(s) > 80 else s
|
|
720
|
+
for s in sm["strengths"][:3]]
|
|
721
|
+
lines.append("我擅长的:" + "、".join(_st) + "。")
|
|
710
722
|
if sm.get("limitations"):
|
|
711
|
-
|
|
723
|
+
# TOKEN-TRIM(v5.72):limitations 单条截到 80 字——短板是提醒不是报告,
|
|
724
|
+
# 实测单条 300+ 字、三条合计 900+ 字,占注入预算显著一块。
|
|
725
|
+
_lm = [s[:80].rstrip() + "…" if len(s) > 80 else s
|
|
726
|
+
for s in sm["limitations"][:3]]
|
|
727
|
+
lines.append("我的短板:" + "、".join(_lm) + "。")
|
|
712
728
|
if sm.get("uncertainties"):
|
|
713
|
-
|
|
729
|
+
# TOKEN-TRIM(v5.72):uncertainties 单条截到 60 字——这是"待验证清单",
|
|
730
|
+
# 不是全文回忆;太长会把注入预算吃光(实测单条 140+ 字、两条 300+ 字)。
|
|
731
|
+
_unc = [u[:60].rstrip() + "…" if len(u) > 60 else u
|
|
732
|
+
for u in sm["uncertainties"][:2]]
|
|
733
|
+
lines.append("我还没弄清的:" + "、".join(_unc) + "。")
|
|
714
734
|
return "\n".join(lines)
|
|
715
735
|
|
|
716
736
|
|
package/scripts/safety.py
CHANGED
|
@@ -126,8 +126,13 @@ def dangerous_reason(home: Path | str) -> str | None:
|
|
|
126
126
|
if _is_home_dir(r):
|
|
127
127
|
return "用户主目录本体不能当记忆库(restore --exact 会清空整个用户目录)"
|
|
128
128
|
low = str(r).lower().replace("/", "\\") if sys.platform == "win32" else str(r).lower()
|
|
129
|
+
# LS-001(v5.71):修复 POSIX 危险路径子目录绕过!
|
|
130
|
+
# 旧写法在所有平台都追加 "\\" 做前缀分隔——POSIX 路径分隔符是 "/",
|
|
131
|
+
# `/etc/passwd`、`/usr/share/x` 等子目录永远匹配不上前缀,整个系统目录树
|
|
132
|
+
# 在 Linux/macOS 上漏判。分隔符必须跟随平台。
|
|
133
|
+
_sep = "\\" if sys.platform == "win32" else "/"
|
|
129
134
|
for pref in _SYSTEM_PREFIXES:
|
|
130
|
-
if low == pref or low.startswith(pref.rstrip("
|
|
135
|
+
if low == pref or low.startswith(pref.rstrip("\\/") + _sep):
|
|
131
136
|
return f"系统目录不能当记忆库:{raw}"
|
|
132
137
|
# 所有用户的父目录(C:\Users 本身)
|
|
133
138
|
try:
|