lingshu-skill 5.23.0 → 5.25.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 +88 -0
- package/README.md +1 -1
- package/SKILL-lite.md +1 -1
- package/SKILL-tiny.md +1 -1
- package/SKILL.md +2 -1
- package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +13 -1
- package/package.json +1 -1
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +14 -13
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +88 -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 +2 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +43 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +90 -2
- package/scripts/astrbot_plugin_lingshu/engine/scripts/coverage_report.py +167 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +221 -219
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +23 -3
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +470 -460
- package/scripts/astrbot_plugin_lingshu/engine/scripts/release.py +14 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +29 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety_net.py +12 -0
- package/scripts/check_version.py +16 -0
- package/scripts/cli.py +43 -0
- package/scripts/core.py +90 -2
- package/scripts/coverage_report.py +167 -0
- package/scripts/mem_dialogue.py +221 -219
- package/scripts/memory.py +23 -3
- package/scripts/panels.py +470 -460
- package/scripts/release.py +14 -0
- package/scripts/safety.py +29 -1
- package/scripts/safety_net.py +12 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""零依赖行覆盖率报告:在**同一个进程**里打一遍主 API,用标准库 trace 统计。
|
|
3
|
+
|
|
4
|
+
为什么不用 `python -m trace` 跑整个测试集:
|
|
5
|
+
测试全是 `subprocess.run([python, ...])` 起的子进程,父进程的 trace 抓不到子进程,
|
|
6
|
+
报出来的覆盖率会低得毫无意义(还容易误判成"代码没被测到")。
|
|
7
|
+
|
|
8
|
+
所以这里换个口径:**在单进程内真实调用主链路**(记/回忆/注入/做梦/体检/情绪/成长…),
|
|
9
|
+
统计 `scripts/*.py` 里有哪些行被走到。它不是"测试覆盖率",而是
|
|
10
|
+
**"主 API 冒烟覆盖率"**——用来发现"某个模块整体没被任何入口碰过"这类问题。
|
|
11
|
+
|
|
12
|
+
用法:
|
|
13
|
+
python scripts/coverage_report.py # 报告 + 最低覆盖模块 Top10
|
|
14
|
+
python scripts/coverage_report.py --min 60 # 低于 60% 的模块视为可疑,退出码 1
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import pathlib
|
|
20
|
+
import sys
|
|
21
|
+
import tempfile
|
|
22
|
+
import trace
|
|
23
|
+
import os
|
|
24
|
+
|
|
25
|
+
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
|
26
|
+
SCRIPTS = ROOT / "scripts"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _exercise() -> list:
|
|
30
|
+
"""在临时 HOME 里真实调用主链路。返回 [(说明, 是否成功)]。"""
|
|
31
|
+
home = tempfile.mkdtemp(prefix="ls-cov-")
|
|
32
|
+
os.environ["BRAIN_MEMORY_HOME"] = home
|
|
33
|
+
os.environ["PYTHONIOENCODING"] = "utf-8"
|
|
34
|
+
sys.path.insert(0, str(SCRIPTS))
|
|
35
|
+
|
|
36
|
+
import brain # noqa: F401 合并命名空间
|
|
37
|
+
import core
|
|
38
|
+
import memory as mem
|
|
39
|
+
import emotion as em
|
|
40
|
+
import persona as pe
|
|
41
|
+
import dream
|
|
42
|
+
import growth
|
|
43
|
+
import safety_net
|
|
44
|
+
import shape_audit
|
|
45
|
+
|
|
46
|
+
core.ensure_home()
|
|
47
|
+
done = []
|
|
48
|
+
|
|
49
|
+
def step(name, fn):
|
|
50
|
+
try:
|
|
51
|
+
fn()
|
|
52
|
+
done.append((name, True))
|
|
53
|
+
except Exception as exc: # noqa: BLE001
|
|
54
|
+
done.append((f"{name}({type(exc).__name__}: {str(exc)[:60]})", False))
|
|
55
|
+
|
|
56
|
+
ids = {}
|
|
57
|
+
|
|
58
|
+
def _remember():
|
|
59
|
+
rec, _ = mem.remember("覆盖率冒烟:用户偏好把话说清楚,讨厌猜测",
|
|
60
|
+
kind="fact", importance=0.7, tags=["冒烟"])
|
|
61
|
+
ids["a"] = rec["id"]
|
|
62
|
+
mem.remember("覆盖率冒烟:备份要先留底再动手", kind="mistake", importance=0.8)
|
|
63
|
+
|
|
64
|
+
step("remember", _remember)
|
|
65
|
+
step("recall", lambda: mem.recall("备份 留底", k=5, mode="fast", strengthen=False))
|
|
66
|
+
step("stats", mem.stats)
|
|
67
|
+
step("inject", lambda: mem.build_injection("接着做覆盖率"))
|
|
68
|
+
step("capture", lambda: mem.capture("user: 覆盖率冒烟对话\nassistant: 收到",
|
|
69
|
+
tag="即记", kind="episode"))
|
|
70
|
+
step("injectable_lessons", lambda: mem.injectable_lessons("覆盖率"))
|
|
71
|
+
step("detect_conflicts", lambda: mem.detect_conflicts(limit=10))
|
|
72
|
+
step("set_frozen", lambda: ids.get("a") and mem.set_frozen(ids["a"], True))
|
|
73
|
+
step("touch_by_emotion", lambda: ids.get("a") and mem.touch_by_emotion(ids["a"], -0.7, 0.8))
|
|
74
|
+
step("fetch", lambda: ids.get("a") and mem.fetch(ids["a"]))
|
|
75
|
+
step("emotion now", em.mood_now)
|
|
76
|
+
step("emotion feel", lambda: em.feel("满足", intensity=0.5, why="冒烟"))
|
|
77
|
+
step("emotion auto", lambda: em.auto_appraise("这次真的很难过很委屈,气死了,"
|
|
78
|
+
"希望以后别再这样,我真的会很失望,也很难受"))
|
|
79
|
+
step("persona load", pe.load_persona)
|
|
80
|
+
step("persona snapshot", lambda: pe.persona_snapshot("覆盖率冒烟"))
|
|
81
|
+
step("dream report", lambda: dream.dream_report() if hasattr(dream, "dream_report") else None)
|
|
82
|
+
step("dream verify", lambda: dream.dream_verify() if hasattr(dream, "dream_verify") else None)
|
|
83
|
+
step("growth digest", lambda: growth.digest(3))
|
|
84
|
+
step("growth stage", growth.stage_state)
|
|
85
|
+
step("growth health", growth.health_score)
|
|
86
|
+
step("growth skill_evolve", lambda: growth.skill_evolve(days=7, dry_run=True))
|
|
87
|
+
step("safety snapshot", lambda: safety_net.snapshot("覆盖率冒烟"))
|
|
88
|
+
step("safety list", safety_net.list_snapshots)
|
|
89
|
+
step("shape audit", lambda: shape_audit.audit())
|
|
90
|
+
step("core doctor-ish", lambda: core.load_config())
|
|
91
|
+
return done
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _count_coverage(tracer: trace.Trace) -> dict:
|
|
95
|
+
"""从 trace 结果算每个文件的 (hit_lines, total_lines)。"""
|
|
96
|
+
counts = tracer.results().counts # {(filename, lineno): count}
|
|
97
|
+
hit = {}
|
|
98
|
+
for (fname, lineno), cnt in counts.items():
|
|
99
|
+
try:
|
|
100
|
+
p = pathlib.Path(fname).resolve()
|
|
101
|
+
except OSError:
|
|
102
|
+
continue
|
|
103
|
+
if p.parent != SCRIPTS.resolve() or p.suffix != ".py":
|
|
104
|
+
continue
|
|
105
|
+
if cnt > 0:
|
|
106
|
+
hit.setdefault(p.name, set()).add(lineno)
|
|
107
|
+
|
|
108
|
+
# 每个文件的可执行行数:用 ast 之外最省事的办法——非空、非纯注释行
|
|
109
|
+
out = {}
|
|
110
|
+
for py in sorted(SCRIPTS.glob("*.py")):
|
|
111
|
+
try:
|
|
112
|
+
lines = py.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
113
|
+
except OSError:
|
|
114
|
+
continue
|
|
115
|
+
total = 0
|
|
116
|
+
for raw in lines:
|
|
117
|
+
s = raw.strip()
|
|
118
|
+
if not s or s.startswith("#"):
|
|
119
|
+
continue
|
|
120
|
+
total += 1
|
|
121
|
+
n_hit = len(hit.get(py.name, ()))
|
|
122
|
+
if total:
|
|
123
|
+
out[py.name] = (n_hit, total)
|
|
124
|
+
return out
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def main(argv=None) -> int:
|
|
128
|
+
ap = argparse.ArgumentParser(description="零依赖主 API 冒烟覆盖率")
|
|
129
|
+
ap.add_argument("--min", type=int, default=0,
|
|
130
|
+
help="低于该百分比的模块视为可疑,退出码 1(默认 0 = 只报告)")
|
|
131
|
+
ap.add_argument("--top", type=int, default=10, help="列出覆盖率最低的 N 个模块")
|
|
132
|
+
args = ap.parse_args(argv)
|
|
133
|
+
|
|
134
|
+
tracer = trace.Trace(count=1, trace=0, ignoredirs=[sys.prefix, sys.exec_prefix])
|
|
135
|
+
done = tracer.runfunc(_exercise)
|
|
136
|
+
cov = _count_coverage(tracer)
|
|
137
|
+
|
|
138
|
+
ok = [n for n, good in done if good]
|
|
139
|
+
bad = [n for n, good in done if not good]
|
|
140
|
+
print(f"主链路冒烟:{len(ok)} 步成功 / {len(bad)} 步失败")
|
|
141
|
+
for name in bad:
|
|
142
|
+
print(f" ⚠ 失败:{name}")
|
|
143
|
+
|
|
144
|
+
rows = [(name, h, t, (h / t * 100 if t else 0.0)) for name, (h, t) in cov.items()]
|
|
145
|
+
rows.sort(key=lambda r: r[3])
|
|
146
|
+
tot_h = sum(r[1] for r in rows)
|
|
147
|
+
tot_t = sum(r[2] for r in rows)
|
|
148
|
+
print(f"\n脚本行覆盖(主 API 冒烟口径):{tot_h}/{tot_t} = "
|
|
149
|
+
f"{tot_h / tot_t * 100:.1f}%" if tot_t else "无数据")
|
|
150
|
+
|
|
151
|
+
print(f"\n覆盖率最低的 {args.top} 个模块:")
|
|
152
|
+
for name, h, t, pct in rows[:args.top]:
|
|
153
|
+
print(f" {pct:>5.1f}% {h:>4}/{t:<5} {name}")
|
|
154
|
+
|
|
155
|
+
suspects = [r for r in rows if r[3] < args.min and r[2] >= 20]
|
|
156
|
+
if args.min and suspects:
|
|
157
|
+
print(f"\n[失败] {len(suspects)} 个模块覆盖率低于 {args.min}%:")
|
|
158
|
+
for name, h, t, pct in suspects[:12]:
|
|
159
|
+
print(f" {pct:.1f}% {name}")
|
|
160
|
+
return 1
|
|
161
|
+
if bad:
|
|
162
|
+
return 2
|
|
163
|
+
return 0
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
if __name__ == "__main__":
|
|
167
|
+
sys.exit(main())
|
|
@@ -21,222 +21,224 @@ def _mem():
|
|
|
21
21
|
return memory
|
|
22
22
|
|
|
23
23
|
|
|
24
|
-
_DIALOGUE_EXTS = (".jsonl", ".md", ".txt")
|
|
25
|
-
_DIALOGUE_MAX_DEPTH = 2
|
|
26
|
-
_DIALOGUE_READ_CAP = 8 * 1024 * 1024 # 单次最多读 8MB;大文件按完整行分批推进偏移
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
def _dialogue_offsets_path() -> Path:
|
|
30
|
-
return core.HOME / "dialogue_offsets.json"
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
def _dialogue_load_offsets() -> dict:
|
|
34
|
-
p = _dialogue_offsets_path()
|
|
35
|
-
if not p.exists():
|
|
36
|
-
return {}
|
|
37
|
-
try:
|
|
38
|
-
d = json.loads(p.read_text(encoding="utf-8-sig"))
|
|
39
|
-
return d if isinstance(d, dict) else {}
|
|
40
|
-
except Exception:
|
|
41
|
-
return {}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
def _dialogue_decode(blob: bytes, source: str) -> str:
|
|
45
|
-
"""BOM → UTF-8 严格解码 → GB18030 回退;实际编码留日志,不乱码静默入库。"""
|
|
46
|
-
if not blob:
|
|
47
|
-
return ""
|
|
48
|
-
encoding = "utf-8"
|
|
49
|
-
if blob.startswith(b"\xef\xbb\xbf"):
|
|
50
|
-
encoding = "utf-8-sig"
|
|
51
|
-
elif blob.startswith((b"\xff\xfe", b"\xfe\xff")):
|
|
52
|
-
encoding = "utf-16"
|
|
53
|
-
else:
|
|
54
|
-
try:
|
|
55
|
-
return blob.decode("utf-8")
|
|
56
|
-
except UnicodeDecodeError:
|
|
57
|
-
encoding = "gb18030"
|
|
58
|
-
try:
|
|
59
|
-
text = blob.decode(encoding)
|
|
60
|
-
except UnicodeDecodeError:
|
|
61
|
-
text = blob.decode(encoding, errors="replace")
|
|
62
|
-
core.log_event("dialogue", f"对话摄取解码({source}):{encoding}", level="info")
|
|
63
|
-
return text
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
def _dialogue_turns_from_text(text: str, ext: str) -> list:
|
|
67
|
-
"""把导出片段解析成 [(role, text)];role ∈ user / ai / other。"""
|
|
68
|
-
turns = []
|
|
69
|
-
for ln in text.splitlines():
|
|
70
|
-
s = ln.strip()
|
|
71
|
-
if not s:
|
|
72
|
-
continue
|
|
73
|
-
if ext == ".jsonl":
|
|
74
|
-
try:
|
|
75
|
-
d = json.loads(s)
|
|
76
|
-
except Exception:
|
|
77
|
-
continue
|
|
78
|
-
if isinstance(d, str):
|
|
79
|
-
turns.append(("other", d))
|
|
80
|
-
continue
|
|
81
|
-
if not isinstance(d, dict):
|
|
82
|
-
continue
|
|
83
|
-
txt = d.get("content") or d.get("text") or d.get("message") or ""
|
|
84
|
-
if isinstance(txt, list): # OpenAI 风格 content parts
|
|
85
|
-
txt = " ".join(str(x.get("text") if isinstance(x, dict) else x) for x in txt)
|
|
86
|
-
txt = str(txt).strip()
|
|
87
|
-
if not txt:
|
|
88
|
-
continue
|
|
89
|
-
raw_role = str(d.get("role") or d.get("sender") or d.get("from") or "").lower()
|
|
90
|
-
if raw_role in ("user", "human", "me", "我", "用户"):
|
|
91
|
-
role = "user"
|
|
92
|
-
elif raw_role in ("assistant", "ai", "bot", "model", "灵枢", "助手"):
|
|
93
|
-
role = "ai"
|
|
94
|
-
else:
|
|
95
|
-
role = "other"
|
|
96
|
-
turns.append((role, txt))
|
|
97
|
-
else:
|
|
98
|
-
m = re.match(r"^\s*(user|human|assistant|ai|bot|model|我|用户|助手|灵枢)\s*[::]\s*(.+)$",
|
|
99
|
-
s, re.I)
|
|
100
|
-
if m:
|
|
101
|
-
who = m.group(1).lower()
|
|
102
|
-
role = "user" if who in ("user", "human", "我", "用户") else "ai"
|
|
103
|
-
turns.append((role, m.group(2).strip()))
|
|
104
|
-
else:
|
|
105
|
-
turns.append(("other", s))
|
|
106
|
-
return turns
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
def _dialogue_chunks(turns: list, max_chars: int = 700) -> list:
|
|
110
|
-
"""相邻轮次拼成块(用户/我 前缀);块满就切,一块 = 一条 episode 记忆。"""
|
|
111
|
-
chunks, buf, size = [], [], 0
|
|
112
|
-
for role, text in turns:
|
|
113
|
-
if len(text) < 2:
|
|
114
|
-
continue
|
|
115
|
-
prefix = "用户: " if role == "user" else ("我: " if role == "ai" else "")
|
|
116
|
-
piece = prefix + text
|
|
117
|
-
if buf and size + len(piece) > max_chars:
|
|
118
|
-
chunks.append("\n".join(buf))
|
|
119
|
-
buf, size = [], 0
|
|
120
|
-
buf.append(piece)
|
|
121
|
-
size += len(piece) + 1
|
|
122
|
-
if buf:
|
|
123
|
-
chunks.append("\n".join(buf))
|
|
124
|
-
return [c for c in chunks if len(c) >= 8]
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
def _dialogue_files(sources: list, max_files: int) -> list:
|
|
128
|
-
"""收集候选文件(最多 max_files 个,按 mtime 新→旧)。"""
|
|
129
|
-
found = []
|
|
130
|
-
for src in sources:
|
|
131
|
-
root = Path(str(src)).expanduser()
|
|
132
|
-
if not root.is_dir():
|
|
133
|
-
continue
|
|
134
|
-
base_depth = len(root.parts)
|
|
135
|
-
for f in root.rglob("*"):
|
|
136
|
-
try:
|
|
137
|
-
if len(f.parts) - base_depth > _DIALOGUE_MAX_DEPTH:
|
|
138
|
-
continue
|
|
139
|
-
if f.is_file() and f.suffix.lower() in _DIALOGUE_EXTS:
|
|
140
|
-
found.append(f)
|
|
141
|
-
except OSError:
|
|
142
|
-
continue
|
|
143
|
-
found.sort(key=lambda f: -(f.stat().st_mtime if f.exists() else 0))
|
|
144
|
-
return found[:max_files]
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
def ingest_dialogues(paths=None, limit: int | None = None, dry_run: bool = False) -> dict:
|
|
148
|
-
"""增量摄取其他会话的对话导出 → episode 记忆。
|
|
149
|
-
|
|
150
|
-
参数:
|
|
151
|
-
paths 额外/替代的源目录(缺省用 config.dialogue_sources)
|
|
152
|
-
limit 本次最多处理多少个文件(缺省 config.dialogue_ingest_max_files)
|
|
153
|
-
dry_run 只统计不写库(不推进偏移、不写记忆)
|
|
154
|
-
返回:{enabled, files, scanned, imported, skipped, chars, dry_run}
|
|
155
|
-
"""
|
|
156
|
-
cfg = load_config()
|
|
157
|
-
if not cfg.get("dialogue_ingest"):
|
|
158
|
-
return {"ok": True, "enabled": False, "files": 0, "scanned": 0,
|
|
159
|
-
"imported": 0, "skipped": 0, "chars": 0, "dry_run": dry_run,
|
|
160
|
-
"reason": "未开启:config dialogue_ingest=false"}
|
|
161
|
-
sources = [str(x) for x in (paths or cfg.get("dialogue_sources") or []) if str(x).strip()]
|
|
162
|
-
if not sources:
|
|
163
|
-
return {"ok": True, "enabled": True, "files": 0, "scanned": 0,
|
|
164
|
-
"imported": 0, "skipped": 0, "chars": 0, "dry_run": dry_run,
|
|
165
|
-
"reason": "没有配置 dialogue_sources 目录"}
|
|
166
|
-
max_files = max(1, min(int(limit or cfg.get("dialogue_ingest_max_files") or 50), 500))
|
|
167
|
-
max_chars = max(200, min(int(cfg.get("dialogue_ingest_max_chars") or 700), 2000))
|
|
168
|
-
imported, skipped, chars, touched = 0, 0, 0, 0
|
|
169
|
-
# offsets 既记读取位置,也记已导入块哈希:去重不再全量扫记忆库;
|
|
170
|
-
# 整个读偏移→写记忆→存偏移过程持同一把锁,避免两个进程重复导入。
|
|
171
|
-
with core._locked(_dialogue_offsets_path()):
|
|
172
|
-
files = _dialogue_files(sources, max_files)
|
|
173
|
-
offsets = _dialogue_load_offsets()
|
|
174
|
-
known = {h for entry in offsets.values() if isinstance(entry, dict)
|
|
175
|
-
for h in (entry.get("chunk_hashes") or [])}
|
|
176
|
-
for f in files:
|
|
177
|
-
key = str(f.resolve())
|
|
178
|
-
try:
|
|
179
|
-
st = f.stat()
|
|
180
|
-
except OSError:
|
|
181
|
-
continue
|
|
182
|
-
entry = offsets.get(key) or {}
|
|
183
|
-
# 用 offset==size 判断"已读干净":尾部半行没读完时不跳过,
|
|
184
|
-
# 下次等它补上换行再继续(否则会永久漏掉最后一条)。
|
|
185
|
-
if entry.get("offset") == st.st_size and entry.get("mtime") == st.st_mtime:
|
|
186
|
-
continue # 没变过:完全不读
|
|
187
|
-
start = int(entry.get("offset") or 0)
|
|
188
|
-
if st.st_size < start:
|
|
189
|
-
start = 0 # 文件被截断/重写:从头再来(块哈希去重兜底)
|
|
190
|
-
remaining = max(0, st.st_size - start)
|
|
191
|
-
try:
|
|
192
|
-
with open(f, "rb") as fh:
|
|
193
|
-
fh.seek(start)
|
|
194
|
-
blob = fh.read(min(_DIALOGUE_READ_CAP, remaining))
|
|
195
|
-
except OSError:
|
|
196
|
-
continue
|
|
197
|
-
if remaining > _DIALOGUE_READ_CAP:
|
|
198
|
-
core.log_event("dialogue", f"对话摄取分段读取({f.name}):"
|
|
199
|
-
f"偏移 {start},本次 {len(blob)} 字节,剩余下次继续",
|
|
200
|
-
level="info")
|
|
201
|
-
# 偏移永远落在完整行边界:尾部半行(正在写/无换行结尾)留到下次,
|
|
202
|
-
# 否则续读时会把一条完整的新记录误当成"残片"丢掉。
|
|
203
|
-
if blob and not blob.endswith(b"\n"):
|
|
204
|
-
cut = blob.rfind(b"\n")
|
|
205
|
-
if cut < 0:
|
|
206
|
-
continue
|
|
207
|
-
blob = blob[:cut + 1]
|
|
208
|
-
text = _dialogue_decode(blob, f.name)
|
|
209
|
-
turns = _dialogue_turns_from_text(text, f.suffix.lower())
|
|
210
|
-
file_hashes = list(entry.get("chunk_hashes") or [])
|
|
211
|
-
for chunk in _dialogue_chunks(turns, max_chars):
|
|
212
|
-
digest = hashlib.sha256(chunk.strip().encode("utf-8")).hexdigest()
|
|
213
|
-
if digest in known:
|
|
214
|
-
skipped += 1
|
|
215
|
-
continue
|
|
216
|
-
if not dry_run:
|
|
217
|
-
try:
|
|
218
|
-
_mem().remember(chunk, kind="episode", importance=0.45,
|
|
219
|
-
tags=["对话摄取", f.stem], source="dialogue",
|
|
220
|
-
channel=f"dialogue:{f.stem}")
|
|
221
|
-
except Exception as exc:
|
|
222
|
-
core.log_event("dialogue", f"对话摄取写入失败({f.name}):{exc}", level="warn")
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
core.
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
24
|
+
_DIALOGUE_EXTS = (".jsonl", ".md", ".txt")
|
|
25
|
+
_DIALOGUE_MAX_DEPTH = 2
|
|
26
|
+
_DIALOGUE_READ_CAP = 8 * 1024 * 1024 # 单次最多读 8MB;大文件按完整行分批推进偏移
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _dialogue_offsets_path() -> Path:
|
|
30
|
+
return core.HOME / "dialogue_offsets.json"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _dialogue_load_offsets() -> dict:
|
|
34
|
+
p = _dialogue_offsets_path()
|
|
35
|
+
if not p.exists():
|
|
36
|
+
return {}
|
|
37
|
+
try:
|
|
38
|
+
d = json.loads(p.read_text(encoding="utf-8-sig"))
|
|
39
|
+
return d if isinstance(d, dict) else {}
|
|
40
|
+
except Exception:
|
|
41
|
+
return {}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _dialogue_decode(blob: bytes, source: str) -> str:
|
|
45
|
+
"""BOM → UTF-8 严格解码 → GB18030 回退;实际编码留日志,不乱码静默入库。"""
|
|
46
|
+
if not blob:
|
|
47
|
+
return ""
|
|
48
|
+
encoding = "utf-8"
|
|
49
|
+
if blob.startswith(b"\xef\xbb\xbf"):
|
|
50
|
+
encoding = "utf-8-sig"
|
|
51
|
+
elif blob.startswith((b"\xff\xfe", b"\xfe\xff")):
|
|
52
|
+
encoding = "utf-16"
|
|
53
|
+
else:
|
|
54
|
+
try:
|
|
55
|
+
return blob.decode("utf-8")
|
|
56
|
+
except UnicodeDecodeError:
|
|
57
|
+
encoding = "gb18030"
|
|
58
|
+
try:
|
|
59
|
+
text = blob.decode(encoding)
|
|
60
|
+
except UnicodeDecodeError:
|
|
61
|
+
text = blob.decode(encoding, errors="replace")
|
|
62
|
+
core.log_event("dialogue", f"对话摄取解码({source}):{encoding}", level="info")
|
|
63
|
+
return text
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _dialogue_turns_from_text(text: str, ext: str) -> list:
|
|
67
|
+
"""把导出片段解析成 [(role, text)];role ∈ user / ai / other。"""
|
|
68
|
+
turns = []
|
|
69
|
+
for ln in text.splitlines():
|
|
70
|
+
s = ln.strip()
|
|
71
|
+
if not s:
|
|
72
|
+
continue
|
|
73
|
+
if ext == ".jsonl":
|
|
74
|
+
try:
|
|
75
|
+
d = json.loads(s)
|
|
76
|
+
except Exception:
|
|
77
|
+
continue
|
|
78
|
+
if isinstance(d, str):
|
|
79
|
+
turns.append(("other", d))
|
|
80
|
+
continue
|
|
81
|
+
if not isinstance(d, dict):
|
|
82
|
+
continue
|
|
83
|
+
txt = d.get("content") or d.get("text") or d.get("message") or ""
|
|
84
|
+
if isinstance(txt, list): # OpenAI 风格 content parts
|
|
85
|
+
txt = " ".join(str(x.get("text") if isinstance(x, dict) else x) for x in txt)
|
|
86
|
+
txt = str(txt).strip()
|
|
87
|
+
if not txt:
|
|
88
|
+
continue
|
|
89
|
+
raw_role = str(d.get("role") or d.get("sender") or d.get("from") or "").lower()
|
|
90
|
+
if raw_role in ("user", "human", "me", "我", "用户"):
|
|
91
|
+
role = "user"
|
|
92
|
+
elif raw_role in ("assistant", "ai", "bot", "model", "灵枢", "助手"):
|
|
93
|
+
role = "ai"
|
|
94
|
+
else:
|
|
95
|
+
role = "other"
|
|
96
|
+
turns.append((role, txt))
|
|
97
|
+
else:
|
|
98
|
+
m = re.match(r"^\s*(user|human|assistant|ai|bot|model|我|用户|助手|灵枢)\s*[::]\s*(.+)$",
|
|
99
|
+
s, re.I)
|
|
100
|
+
if m:
|
|
101
|
+
who = m.group(1).lower()
|
|
102
|
+
role = "user" if who in ("user", "human", "我", "用户") else "ai"
|
|
103
|
+
turns.append((role, m.group(2).strip()))
|
|
104
|
+
else:
|
|
105
|
+
turns.append(("other", s))
|
|
106
|
+
return turns
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _dialogue_chunks(turns: list, max_chars: int = 700) -> list:
|
|
110
|
+
"""相邻轮次拼成块(用户/我 前缀);块满就切,一块 = 一条 episode 记忆。"""
|
|
111
|
+
chunks, buf, size = [], [], 0
|
|
112
|
+
for role, text in turns:
|
|
113
|
+
if len(text) < 2:
|
|
114
|
+
continue
|
|
115
|
+
prefix = "用户: " if role == "user" else ("我: " if role == "ai" else "")
|
|
116
|
+
piece = prefix + text
|
|
117
|
+
if buf and size + len(piece) > max_chars:
|
|
118
|
+
chunks.append("\n".join(buf))
|
|
119
|
+
buf, size = [], 0
|
|
120
|
+
buf.append(piece)
|
|
121
|
+
size += len(piece) + 1
|
|
122
|
+
if buf:
|
|
123
|
+
chunks.append("\n".join(buf))
|
|
124
|
+
return [c for c in chunks if len(c) >= 8]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _dialogue_files(sources: list, max_files: int) -> list:
|
|
128
|
+
"""收集候选文件(最多 max_files 个,按 mtime 新→旧)。"""
|
|
129
|
+
found = []
|
|
130
|
+
for src in sources:
|
|
131
|
+
root = Path(str(src)).expanduser()
|
|
132
|
+
if not root.is_dir():
|
|
133
|
+
continue
|
|
134
|
+
base_depth = len(root.parts)
|
|
135
|
+
for f in root.rglob("*"):
|
|
136
|
+
try:
|
|
137
|
+
if len(f.parts) - base_depth > _DIALOGUE_MAX_DEPTH:
|
|
138
|
+
continue
|
|
139
|
+
if f.is_file() and f.suffix.lower() in _DIALOGUE_EXTS:
|
|
140
|
+
found.append(f)
|
|
141
|
+
except OSError:
|
|
142
|
+
continue
|
|
143
|
+
found.sort(key=lambda f: -(f.stat().st_mtime if f.exists() else 0))
|
|
144
|
+
return found[:max_files]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def ingest_dialogues(paths=None, limit: int | None = None, dry_run: bool = False) -> dict:
|
|
148
|
+
"""增量摄取其他会话的对话导出 → episode 记忆。
|
|
149
|
+
|
|
150
|
+
参数:
|
|
151
|
+
paths 额外/替代的源目录(缺省用 config.dialogue_sources)
|
|
152
|
+
limit 本次最多处理多少个文件(缺省 config.dialogue_ingest_max_files)
|
|
153
|
+
dry_run 只统计不写库(不推进偏移、不写记忆)
|
|
154
|
+
返回:{enabled, files, scanned, imported, skipped, chars, dry_run}
|
|
155
|
+
"""
|
|
156
|
+
cfg = load_config()
|
|
157
|
+
if not cfg.get("dialogue_ingest"):
|
|
158
|
+
return {"ok": True, "enabled": False, "files": 0, "scanned": 0,
|
|
159
|
+
"imported": 0, "skipped": 0, "chars": 0, "dry_run": dry_run,
|
|
160
|
+
"reason": "未开启:config dialogue_ingest=false"}
|
|
161
|
+
sources = [str(x) for x in (paths or cfg.get("dialogue_sources") or []) if str(x).strip()]
|
|
162
|
+
if not sources:
|
|
163
|
+
return {"ok": True, "enabled": True, "files": 0, "scanned": 0,
|
|
164
|
+
"imported": 0, "skipped": 0, "chars": 0, "dry_run": dry_run,
|
|
165
|
+
"reason": "没有配置 dialogue_sources 目录"}
|
|
166
|
+
max_files = max(1, min(int(limit or cfg.get("dialogue_ingest_max_files") or 50), 500))
|
|
167
|
+
max_chars = max(200, min(int(cfg.get("dialogue_ingest_max_chars") or 700), 2000))
|
|
168
|
+
imported, skipped, chars, touched = 0, 0, 0, 0
|
|
169
|
+
# offsets 既记读取位置,也记已导入块哈希:去重不再全量扫记忆库;
|
|
170
|
+
# 整个读偏移→写记忆→存偏移过程持同一把锁,避免两个进程重复导入。
|
|
171
|
+
with core._locked(_dialogue_offsets_path()):
|
|
172
|
+
files = _dialogue_files(sources, max_files)
|
|
173
|
+
offsets = _dialogue_load_offsets()
|
|
174
|
+
known = {h for entry in offsets.values() if isinstance(entry, dict)
|
|
175
|
+
for h in (entry.get("chunk_hashes") or [])}
|
|
176
|
+
for f in files:
|
|
177
|
+
key = str(f.resolve())
|
|
178
|
+
try:
|
|
179
|
+
st = f.stat()
|
|
180
|
+
except OSError:
|
|
181
|
+
continue
|
|
182
|
+
entry = offsets.get(key) or {}
|
|
183
|
+
# 用 offset==size 判断"已读干净":尾部半行没读完时不跳过,
|
|
184
|
+
# 下次等它补上换行再继续(否则会永久漏掉最后一条)。
|
|
185
|
+
if entry.get("offset") == st.st_size and entry.get("mtime") == st.st_mtime:
|
|
186
|
+
continue # 没变过:完全不读
|
|
187
|
+
start = int(entry.get("offset") or 0)
|
|
188
|
+
if st.st_size < start:
|
|
189
|
+
start = 0 # 文件被截断/重写:从头再来(块哈希去重兜底)
|
|
190
|
+
remaining = max(0, st.st_size - start)
|
|
191
|
+
try:
|
|
192
|
+
with open(f, "rb") as fh:
|
|
193
|
+
fh.seek(start)
|
|
194
|
+
blob = fh.read(min(_DIALOGUE_READ_CAP, remaining))
|
|
195
|
+
except OSError:
|
|
196
|
+
continue
|
|
197
|
+
if remaining > _DIALOGUE_READ_CAP:
|
|
198
|
+
core.log_event("dialogue", f"对话摄取分段读取({f.name}):"
|
|
199
|
+
f"偏移 {start},本次 {len(blob)} 字节,剩余下次继续",
|
|
200
|
+
level="info")
|
|
201
|
+
# 偏移永远落在完整行边界:尾部半行(正在写/无换行结尾)留到下次,
|
|
202
|
+
# 否则续读时会把一条完整的新记录误当成"残片"丢掉。
|
|
203
|
+
if blob and not blob.endswith(b"\n"):
|
|
204
|
+
cut = blob.rfind(b"\n")
|
|
205
|
+
if cut < 0:
|
|
206
|
+
continue
|
|
207
|
+
blob = blob[:cut + 1]
|
|
208
|
+
text = _dialogue_decode(blob, f.name)
|
|
209
|
+
turns = _dialogue_turns_from_text(text, f.suffix.lower())
|
|
210
|
+
file_hashes = list(entry.get("chunk_hashes") or [])
|
|
211
|
+
for chunk in _dialogue_chunks(turns, max_chars):
|
|
212
|
+
digest = hashlib.sha256(chunk.strip().encode("utf-8")).hexdigest()
|
|
213
|
+
if digest in known:
|
|
214
|
+
skipped += 1
|
|
215
|
+
continue
|
|
216
|
+
if not dry_run:
|
|
217
|
+
try:
|
|
218
|
+
_mem().remember(chunk, kind="episode", importance=0.45,
|
|
219
|
+
tags=["对话摄取", f.stem], source="dialogue",
|
|
220
|
+
channel=f"dialogue:{f.stem}")
|
|
221
|
+
except Exception as exc:
|
|
222
|
+
core.log_event("dialogue", f"对话摄取写入失败({f.name}):{exc}", level="warn")
|
|
223
|
+
# 这条吞掉等于"对话没进记忆"——用户以为记下了,其实没有
|
|
224
|
+
core.swallow("dialogue.ingest", exc, where="mem_dialogue")
|
|
225
|
+
continue
|
|
226
|
+
known.add(digest)
|
|
227
|
+
file_hashes.append(digest)
|
|
228
|
+
imported += 1
|
|
229
|
+
chars += len(chunk)
|
|
230
|
+
if not dry_run:
|
|
231
|
+
# offset 只推进到最后一个完整行末尾;尾部半行等下次补全
|
|
232
|
+
offsets[key] = {"offset": start + len(blob), "size": st.st_size,
|
|
233
|
+
"mtime": st.st_mtime, "ts": now_ts(),
|
|
234
|
+
"chunk_hashes": file_hashes}
|
|
235
|
+
touched += 1
|
|
236
|
+
if not dry_run and touched:
|
|
237
|
+
try:
|
|
238
|
+
core.atomic_json(_dialogue_offsets_path(), offsets)
|
|
239
|
+
except Exception as exc:
|
|
240
|
+
core.log_event("dialogue", f"对话摄取偏移保存失败:{exc}", level="warn")
|
|
241
|
+
return {"ok": True, "enabled": True, "files": len(files), "scanned": len(files),
|
|
242
|
+
"imported": imported, "skipped": skipped, "chars": chars,
|
|
243
|
+
"dry_run": dry_run, "sources": sources}
|
|
244
|
+
|
|
@@ -1126,6 +1126,19 @@ def make_record(text: str, kind: str = "fact", importance: float | None = None,
|
|
|
1126
1126
|
agent_id: str | None = None) -> dict:
|
|
1127
1127
|
ts = now_ts()
|
|
1128
1128
|
text = text.strip()
|
|
1129
|
+
# 捕获时脱敏:凭据不该进记忆库(备份默认不加密,一旦落盘就一起被拷走)。
|
|
1130
|
+
# 复用 `core.redact()`——它 v3.02 起就有、docstring 也写明"用于记忆写入",
|
|
1131
|
+
# 只是**这里一直没调用**。不另写一份,避免两套规则漂移
|
|
1132
|
+
# (实测过:我另写的 `_REDACT_PATTERNS` 被 brain 的命名空间合并覆盖成了死代码)。
|
|
1133
|
+
_raw_len = len(text)
|
|
1134
|
+
_clean = redact(text)
|
|
1135
|
+
if _clean != text:
|
|
1136
|
+
text = _clean
|
|
1137
|
+
try:
|
|
1138
|
+
log_event("memory", f"记忆文本已脱敏(原长 {_raw_len} → {len(text)})",
|
|
1139
|
+
level="warn")
|
|
1140
|
+
except Exception: # noqa: BLE001
|
|
1141
|
+
pass
|
|
1129
1142
|
tags = _dedupe([t.strip().lstrip("#") for t in (tags or []) if t.strip()])
|
|
1130
1143
|
entities = _dedupe([e.strip() for e in (entities or []) if e.strip()])
|
|
1131
1144
|
for tag in re.findall(r"#([\w\u4e00-\u9fff]{1,16})", text):
|
|
@@ -2720,9 +2733,16 @@ def purge(memory_id: str, confirm_token: str) -> dict:
|
|
|
2720
2733
|
"""
|
|
2721
2734
|
if READONLY:
|
|
2722
2735
|
raise PermissionError("记忆库当前只读,无法物理删除。")
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2736
|
+
# 统一走 safety 的确认原语(原先这里自己写了一段比对,文案与 safety 那套不一致,
|
|
2737
|
+
# 也让"破坏性确认"散落在两个模块里)。
|
|
2738
|
+
try:
|
|
2739
|
+
import safety as _safety
|
|
2740
|
+
_safety.require_token("物理删除记忆", confirm_token, memory_id[:8],
|
|
2741
|
+
hint=f"--confirm {memory_id[:8]}")
|
|
2742
|
+
except ImportError: # safety 未部署时退回原判据,别把删除功能整体搞挂
|
|
2743
|
+
if not confirm_token or confirm_token != memory_id[:8]:
|
|
2744
|
+
raise ValueError(
|
|
2745
|
+
f"物理删除需显式确认:--confirm {memory_id[:8]}(传入的确认码不匹配)")
|
|
2726
2746
|
cutoff = now_ts() - _PURGE_COOLDOWN_DAYS * DAY
|
|
2727
2747
|
with _locked(HOME / "hippocampus.jsonl"):
|
|
2728
2748
|
records = load_all()
|