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
|
@@ -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
|
# ---------------------------------------------------------------- 记忆关联(联想能力)
|
|
@@ -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:**只有"清单确实不存在"才可以新建空清单**。
|
|
@@ -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
|
|
@@ -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
|
|
|
@@ -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
|
|