lingshu-skill 5.70.0 → 5.71.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 +45 -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 +35 -35
- package/package.json +1 -1
- package/scripts/assembler.py +8 -2
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +88 -16
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +45 -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/checkpoint.py +13 -2
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +45 -0
- 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 +62 -6
- 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 +10 -4
- 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/checkpoint.py +13 -2
- package/scripts/dream.py +45 -0
- package/scripts/emotion.py +13 -2
- package/scripts/growth_parts.py +5 -1
- package/scripts/memory.py +62 -6
- package/scripts/panel_cloud.py +47 -1
- package/scripts/panel_server.py +12 -2
- package/scripts/persona.py +10 -4
- package/scripts/safety.py +6 -1
- package/scripts/session_import.py +6 -2
- package/scripts/session_rag.py +68 -21
|
@@ -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":
|
|
@@ -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
|
|
@@ -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:
|
|
@@ -34,8 +34,6 @@ from __future__ import annotations
|
|
|
34
34
|
|
|
35
35
|
import argparse
|
|
36
36
|
import hashlib
|
|
37
|
-
import brain
|
|
38
|
-
import core
|
|
39
37
|
import json
|
|
40
38
|
import os
|
|
41
39
|
import re
|
|
@@ -47,10 +45,16 @@ import time
|
|
|
47
45
|
from dataclasses import dataclass
|
|
48
46
|
from pathlib import Path
|
|
49
47
|
|
|
48
|
+
# LS-057(v5.71):修正导入顺序——先设置模块目录再 import brain!
|
|
49
|
+
# 旧写法在 sys.path 注入前就 import brain/core,通过 spec_from_file_location
|
|
50
|
+
# 独立加载(测试沙箱/外部宿主)时本目录不在 sys.path,直接 ModuleNotFoundError。
|
|
50
51
|
HERE = Path(__file__).resolve().parent
|
|
51
52
|
if str(HERE) not in sys.path: # 允许 `python scripts/session_import.py` 与 tests 直接 import
|
|
52
53
|
sys.path.insert(0, str(HERE))
|
|
53
54
|
|
|
55
|
+
import brain # noqa: E402
|
|
56
|
+
import core # noqa: E402
|
|
57
|
+
|
|
54
58
|
import session_rag # noqa: E402
|
|
55
59
|
|
|
56
60
|
PLATFORM = "dsh"
|
|
@@ -95,7 +95,14 @@ def ingest_messages(rows, *, session: str = "default", platform: str = "",
|
|
|
95
95
|
skipped += 1
|
|
96
96
|
continue
|
|
97
97
|
role = str(r.get("role") or "other").lower()
|
|
98
|
-
|
|
98
|
+
# LS-046(v5.71):隔离会话批次中的脏时间戳!
|
|
99
|
+
# 旧实现 float("bad") 直接抛 ValueError——一条脏 ts 让**整批**合法
|
|
100
|
+
# 消息全部回滚。现在单条 try/except:脏时间戳记 skipped 并继续。
|
|
101
|
+
try:
|
|
102
|
+
ts = float(r.get("ts") or r.get("created") or 0)
|
|
103
|
+
except (TypeError, ValueError):
|
|
104
|
+
skipped += 1
|
|
105
|
+
continue
|
|
99
106
|
# LS-034(v5.65):主键纳入 platform 和 workspace 作用域
|
|
100
107
|
mid = _msg_id(session, role, ts, text, platform=platform, workspace=workspace)
|
|
101
108
|
try:
|
|
@@ -145,24 +152,39 @@ def _scope_clauses(*, workspace=None, platform=None,
|
|
|
145
152
|
|
|
146
153
|
def search(query: str, k: int = 10, *, path=None, workspace=None,
|
|
147
154
|
platform=None) -> list[dict]:
|
|
148
|
-
"""FTS/LIKE 检索;workspace/platform 为可选精确过滤,缺省不过滤(保持旧行为)。
|
|
155
|
+
"""FTS/LIKE 检索;workspace/platform 为可选精确过滤,缺省不过滤(保持旧行为)。
|
|
156
|
+
|
|
157
|
+
LS-047(v5.71):检索是只读操作——库不存在时返回空结果,绝不自动建库建表。
|
|
158
|
+
"""
|
|
149
159
|
q = str(query or "").strip()
|
|
150
160
|
if not q:
|
|
151
161
|
return []
|
|
152
162
|
limit = max(1, int(k))
|
|
153
|
-
|
|
154
|
-
|
|
163
|
+
# 库不存在:只读语义,返回空而不创建
|
|
164
|
+
_p = Path(path) if path else db_path()
|
|
165
|
+
if not _p.is_file():
|
|
166
|
+
return []
|
|
167
|
+
try:
|
|
168
|
+
conn = _connect_readonly(path)
|
|
169
|
+
except FileNotFoundError:
|
|
170
|
+
return []
|
|
171
|
+
with conn:
|
|
155
172
|
# FTS5 trigram 只对 ≥3 字符的词元建索引:中文两字词("云南")MATCH 不到,
|
|
156
173
|
# 短查询走 LIKE 兜底(200k 条内可接受;更长的词仍走 FTS 排序)。
|
|
157
174
|
if len(q) < 3:
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
175
|
+
try:
|
|
176
|
+
scope, scope_params = _scope_clauses(workspace=workspace, platform=platform)
|
|
177
|
+
rows = conn.execute(
|
|
178
|
+
"SELECT id, session, platform, workspace, role, ts, text, 0.0 AS score"
|
|
179
|
+
f" FROM messages WHERE text LIKE ?{scope} ORDER BY ts DESC LIMIT ?",
|
|
180
|
+
[f"%{q}%", *scope_params, limit]).fetchall()
|
|
181
|
+
return [{"id": r["id"], "session": r["session"], "platform": r["platform"],
|
|
182
|
+
"workspace": r["workspace"], "role": r["role"], "ts": r["ts"],
|
|
183
|
+
"text": r["text"], "score": 0.0} for r in rows]
|
|
184
|
+
except sqlite3.OperationalError:
|
|
185
|
+
# 表未建(空库文件):如实返回空
|
|
186
|
+
return []
|
|
187
|
+
# 长查询:FTS5 bm25 相关性排序(mode=ro 连接下 FTS 虚表只读可用)
|
|
166
188
|
try:
|
|
167
189
|
scope, scope_params = _scope_clauses(workspace=workspace, platform=platform,
|
|
168
190
|
prefix="m.")
|
|
@@ -185,16 +207,41 @@ def search(query: str, k: int = 10, *, path=None, workspace=None,
|
|
|
185
207
|
"text": r["text"], "score": float(r["score"] or 0.0)} for r in rows]
|
|
186
208
|
|
|
187
209
|
|
|
210
|
+
def _connect_readonly(path=None):
|
|
211
|
+
"""LS-047(v5.71):只读连接——文件不存在或只读时绝不自动建库建表。"""
|
|
212
|
+
p = Path(path) if path else db_path()
|
|
213
|
+
if not p.is_file():
|
|
214
|
+
raise FileNotFoundError(f"会话库不存在:{p}")
|
|
215
|
+
conn = sqlite3.connect(f"file:{p}?mode=ro", uri=True)
|
|
216
|
+
conn.row_factory = sqlite3.Row
|
|
217
|
+
return conn
|
|
218
|
+
|
|
219
|
+
|
|
188
220
|
def stats(path=None) -> dict:
|
|
189
|
-
"""库概览:总数 + 按 platform/workspace 分组计数(P1 多平台/多工作区可见性)。
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
221
|
+
"""库概览:总数 + 按 platform/workspace 分组计数(P1 多平台/多工作区可见性)。
|
|
222
|
+
|
|
223
|
+
LS-047(v5.71):只读查询用 mode=ro 连接且不自动建库建表——
|
|
224
|
+
查询一个不存在的库应报"不存在"而不是凭空创建一个空库。
|
|
225
|
+
"""
|
|
226
|
+
try:
|
|
227
|
+
conn = _connect_readonly(path)
|
|
228
|
+
except FileNotFoundError as exc:
|
|
229
|
+
return {"messages": 0, "sessions": 0, "path": str(path or db_path()),
|
|
230
|
+
"by_platform": {}, "by_workspace": {}, "error": str(exc)}
|
|
231
|
+
try:
|
|
232
|
+
with conn:
|
|
233
|
+
n = conn.execute("SELECT count(*) AS n FROM messages").fetchone()["n"]
|
|
234
|
+
sess = conn.execute("SELECT count(DISTINCT session) AS n FROM messages").fetchone()["n"]
|
|
235
|
+
by_platform = {str(r["platform"] or ""): r["n"] for r in conn.execute(
|
|
236
|
+
"SELECT platform, count(*) AS n FROM messages GROUP BY platform ORDER BY n DESC")}
|
|
237
|
+
by_workspace = {str(r["workspace"] or ""): r["n"] for r in conn.execute(
|
|
238
|
+
"SELECT workspace, count(*) AS n FROM messages GROUP BY workspace ORDER BY n DESC")}
|
|
239
|
+
except sqlite3.OperationalError as exc:
|
|
240
|
+
# 表还没建(空库文件):如实报告空态,不替用户建表
|
|
241
|
+
return {"messages": 0, "sessions": 0, "path": str(path or db_path()),
|
|
242
|
+
"by_platform": {}, "by_workspace": {}, "error": str(exc)}
|
|
243
|
+
finally:
|
|
244
|
+
conn.close()
|
|
198
245
|
return {"messages": n, "sessions": sess, "path": str(path or db_path()),
|
|
199
246
|
"by_platform": by_platform, "by_workspace": by_workspace}
|
|
200
247
|
|
|
@@ -43,12 +43,16 @@ def scan() -> dict[str, str]:
|
|
|
43
43
|
parts = set(rel.parts)
|
|
44
44
|
if parts & EXCLUDE_PARTS or rel.suffix.lower() in EXCLUDE_SUFFIXES or not p.is_file():
|
|
45
45
|
continue
|
|
46
|
-
#
|
|
47
|
-
#
|
|
48
|
-
|
|
49
|
-
|
|
46
|
+
# LS-122(v5.71):让 checksum 覆盖 _conf_schema.json!
|
|
47
|
+
# 下划线开头 = 作者本地的临时脚本(.gitignore 里 ``_*`` 永远不推送),
|
|
48
|
+
# 但显式列入 INCLUDE_FILES 的发布文件(如 _conf_schema.json)必须
|
|
49
|
+
# **先于**该启发式判定——否则合法发布文件被当成临时脚本排除,
|
|
50
|
+
# 引擎改配置校验规则后 checksum 不校验、同步后无人发现漂移。
|
|
50
51
|
if posix in INCLUDE_FILES or any(posix.startswith(x) for x in INCLUDE_PREFIXES):
|
|
51
52
|
out[posix] = _sha(p)
|
|
53
|
+
continue
|
|
54
|
+
if rel.name.startswith("_"):
|
|
55
|
+
continue
|
|
52
56
|
return out
|
|
53
57
|
|
|
54
58
|
|
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
|
@@ -787,6 +787,30 @@ def dream(trigger: str = "manual", dry_run: bool = False) -> dict:
|
|
|
787
787
|
keep_old = True
|
|
788
788
|
log_event("dream", f"已有未整理的梦(task_id={old['task_id']},"
|
|
789
789
|
f"{age / 3600:.1f}h 前触发),本次不重复生成新任务", level="warn")
|
|
790
|
+
# LS-030(v5.71):避免旧 pending 导致新簇永久丢失!
|
|
791
|
+
# 沿用旧任务时 new_pending 不写盘——本次新提取的簇原本会静默消失。
|
|
792
|
+
# 现在把新簇**合并进旧 pending 的 clusters**:task_id 保持不变
|
|
793
|
+
# (AI 拿到的 apply_schema 不失效),新碎片纳入同一场整理。
|
|
794
|
+
if clusters:
|
|
795
|
+
try:
|
|
796
|
+
_old_clusters = old.get("clusters") or []
|
|
797
|
+
_merged = _old_clusters + list(clusters)
|
|
798
|
+
old["clusters"] = _merged
|
|
799
|
+
# report 里的簇计数只属于本场,供日志观察合并规模
|
|
800
|
+
old.setdefault("report", {})
|
|
801
|
+
atomic_json(HOME / "dreams" / "pending.json", old)
|
|
802
|
+
log_event("dream",
|
|
803
|
+
f"新簇已并入未整理任务(+{len(clusters)} 组,"
|
|
804
|
+
f"合并后 {len(_merged)} 组)", level="info")
|
|
805
|
+
except Exception as _mg:
|
|
806
|
+
log_event("dream", f"新簇并入 pending 失败(新簇暂存 orphaned):{_mg}",
|
|
807
|
+
level="warn")
|
|
808
|
+
try:
|
|
809
|
+
atomic_json(HOME / "dreams" / f"orphaned_{task_id}_newclusters.json",
|
|
810
|
+
{"task_id": task_id, "clusters": clusters,
|
|
811
|
+
"created": now})
|
|
812
|
+
except Exception:
|
|
813
|
+
pass
|
|
790
814
|
else:
|
|
791
815
|
orphan_path = HOME / "dreams" / f"orphaned_{old['task_id']}.json"
|
|
792
816
|
atomic_json(orphan_path, old)
|
|
@@ -1037,9 +1061,30 @@ def apply_dream(result: dict) -> dict:
|
|
|
1037
1061
|
# AI 整理出来的记忆先标"待审核":防止做梦合并/编造的内容直接当事实沉淀。
|
|
1038
1062
|
# 例外:机械聚合摘要(aggregate=True)只是把 N 条原文用「;」连起来的派生视图,
|
|
1039
1063
|
# 没有可审的"新事实",进待审只会每天占住"待审核1条"(P9 #64)。
|
|
1064
|
+
# LS-032(v5.71):禁止 aggregate 标志绕过审核!
|
|
1065
|
+
# AI 结果里 aggregate 可以被任意伪造(想跳审核就标 true)。
|
|
1066
|
+
# 现在必须验证正文确实是源原文的「;」机械拼接才放行——内容与
|
|
1067
|
+
# source_ids 指向的原文完全一致才算机械视图��否则一律进待审。
|
|
1068
|
+
_is_mechanical = False
|
|
1040
1069
|
if item.get("aggregate"):
|
|
1070
|
+
_src_ids = [x for x in (item.get("source_ids") or []) if isinstance(x, str)]
|
|
1071
|
+
if _src_ids:
|
|
1072
|
+
_src_texts = []
|
|
1073
|
+
_by_id = {m.get("id"): m for m in records if isinstance(m, dict)}
|
|
1074
|
+
for _sid in _src_ids:
|
|
1075
|
+
_sm = _by_id.get(_sid)
|
|
1076
|
+
if _sm is not None and str(_sm.get("text") or "").strip():
|
|
1077
|
+
_src_texts.append(str(_sm.get("text")).strip())
|
|
1078
|
+
if _src_texts:
|
|
1079
|
+
_joined = ";".join(_src_texts)
|
|
1080
|
+
# 正文与机械拼接一致(允许首尾空白差异)才算真聚合
|
|
1081
|
+
_is_mechanical = text.strip() == _joined.strip()
|
|
1082
|
+
if _is_mechanical:
|
|
1041
1083
|
rec["aggregate"] = True
|
|
1042
1084
|
else:
|
|
1085
|
+
if item.get("aggregate"):
|
|
1086
|
+
applied["rejected"].append(
|
|
1087
|
+
"aggregate 标志未通过机械聚合校验(正文≠源原文拼接),已改入待审")
|
|
1043
1088
|
rec["review"] = "pending"
|
|
1044
1089
|
rec["review_source"] = "dream"
|
|
1045
1090
|
# #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} 天后才能物理删除"
|
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":
|