lingshu-skill 5.64.0 → 5.66.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.
Files changed (31) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +1 -1
  3. package/SKILL-lite.md +1 -1
  4. package/SKILL-tiny.md +1 -1
  5. package/SKILL.md +1 -1
  6. package/manifest.json +26 -26
  7. package/package.json +1 -1
  8. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +15 -15
  9. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +25 -0
  10. package/scripts/astrbot_plugin_lingshu/engine/README.md +1 -1
  11. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +1 -1
  12. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +1 -1
  13. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +1 -1
  14. package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +17 -3
  15. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +282 -259
  16. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +215 -209
  17. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_exchange.py +217 -171
  18. package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +219 -195
  19. package/scripts/astrbot_plugin_lingshu/engine/scripts/rss_ingest.py +190 -181
  20. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +11 -3
  21. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +148 -123
  22. package/scripts/astrbot_plugin_lingshu/engine/scripts/web_research.py +131 -124
  23. package/scripts/checkpoint.py +17 -3
  24. package/scripts/mem_dialogue.py +282 -259
  25. package/scripts/mem_embed.py +215 -209
  26. package/scripts/mem_exchange.py +217 -171
  27. package/scripts/retriever.py +219 -195
  28. package/scripts/rss_ingest.py +190 -181
  29. package/scripts/session_rag.py +11 -3
  30. package/scripts/session_summary.py +148 -123
  31. package/scripts/web_research.py +131 -124
@@ -1,259 +1,282 @@
1
- # -*- coding: utf-8 -*-
2
- """跨对话上下文摄取(v3.39 从 memory.py 拆出)。
3
-
4
- 依赖约定:
5
- - 可变全局(HOME/锁/原子写/日志)走 `core.*`,不复制值;
6
- - 需要 memory 的读写(remember/load_all)在调用时取模块,避免导入期循环。
7
- """
8
- from __future__ import annotations
9
-
10
- import hashlib
11
- import json
12
- import re
13
- from pathlib import Path
14
-
15
- import core
16
- from core import * # noqa: F401,F403 (now_ts/_num/_cfg_num 等纯函数)
17
-
18
-
19
- def _mem():
20
- import memory
21
- return memory
22
-
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
- # #29:整块没有换行 = 这个文件被压成了一行(或单行超长)。
207
- # 原来的裸 continue 不写日志、不推进 offset → 每次读 8MB、
208
- # 每次跳过,永远不摄取且无任何提示。这里记一次日志
209
- # (同一文件只报一次,避免每轮刷屏),让用户知道该换格式。
210
- try:
211
- _warned = globals().setdefault("_LONGLINE_WARNED", set())
212
- if str(f) not in _warned:
213
- _warned.add(str(f))
214
- core.log_event(
215
- "dialogue",
216
- f"跳过 {f.name}:单块 {len(blob)} 字节内没有换行,"
217
- "疑似被压成一行的导出文件——请改用逐行 JSONL",
218
- level="warn")
219
- except Exception: # noqa: BLE001
220
- pass
221
- continue
222
- blob = blob[:cut + 1]
223
- text = _dialogue_decode(blob, f.name)
224
- turns = _dialogue_turns_from_text(text, f.suffix.lower())
225
- file_hashes = list(entry.get("chunk_hashes") or [])
226
- for chunk in _dialogue_chunks(turns, max_chars):
227
- digest = hashlib.sha256(chunk.strip().encode("utf-8")).hexdigest()
228
- if digest in known:
229
- skipped += 1
230
- continue
231
- if not dry_run:
232
- try:
233
- _mem().remember(chunk, kind="episode", importance=0.45,
234
- tags=["对话摄取", f.stem], source="dialogue",
235
- channel=f"dialogue:{f.stem}")
236
- except Exception as exc:
237
- core.log_event("dialogue", f"对话摄取写入失败({f.name}):{exc}", level="warn")
238
- # 这条吞掉等于"对话没进记忆"——用户以为记下了,其实没有
239
- core.swallow("dialogue.ingest", exc, where="mem_dialogue")
240
- continue
241
- known.add(digest)
242
- file_hashes.append(digest)
243
- imported += 1
244
- chars += len(chunk)
245
- if not dry_run:
246
- # offset 只推进到最后一个完整行末尾;尾部半行等下次补全
247
- offsets[key] = {"offset": start + len(blob), "size": st.st_size,
248
- "mtime": st.st_mtime, "ts": now_ts(),
249
- "chunk_hashes": file_hashes}
250
- touched += 1
251
- if not dry_run and touched:
252
- try:
253
- core.atomic_json(_dialogue_offsets_path(), offsets)
254
- except Exception as exc:
255
- core.log_event("dialogue", f"对话摄取偏移保存失败:{exc}", level="warn")
256
- return {"ok": True, "enabled": True, "files": len(files), "scanned": len(files),
257
- "imported": imported, "skipped": skipped, "chars": chars,
258
- "dry_run": dry_run, "sources": sources}
259
-
1
+ # -*- coding: utf-8 -*-
2
+ """跨对话上下文摄取(v3.39 从 memory.py 拆出)。
3
+
4
+ 依赖约定:
5
+ - 可变全局(HOME/锁/原子写/日志)走 `core.*`,不复制值;
6
+ - 需要 memory 的读写(remember/load_all)在调用时取模块,避免导入期循环。
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import re
13
+ from pathlib import Path
14
+
15
+ import core
16
+ from core import * # noqa: F401,F403 (now_ts/_num/_cfg_num 等纯函数)
17
+
18
+
19
+ def _mem():
20
+ import memory
21
+ return memory
22
+
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
+
47
+ LS-037(v5.66):UTF-16 分块按字符边界处理!
48
+ UTF-16 用 2 字节编码一个字符。如果分块大小不是偶数,
49
+ 切割点可能落在代理对中间导致 decode 报错或产出乱码。
50
+ 修复:对 UTF-16 编码,先检查 blob 长度是否为偶数;如果不是,截掉最后一个字节。
51
+ """
52
+ if not blob:
53
+ return ""
54
+ encoding = "utf-8"
55
+ if blob.startswith(b"\xef\xbb\xbf"):
56
+ encoding = "utf-8-sig"
57
+ elif blob.startswith((b"\xff\xfe", b"\xfe\xff")):
58
+ encoding = "utf-16"
59
+ if len(blob) % 2 != 0:
60
+ blob = blob[:-1]
61
+ core.log_event("dialogue", f"{source}: UTF-16 长度为奇数,截掉尾部 1 字节",
62
+ level="info")
63
+ else:
64
+ try:
65
+ return blob.decode("utf-8")
66
+ except UnicodeDecodeError:
67
+ encoding = "gb18030"
68
+ try:
69
+ text = blob.decode(encoding)
70
+ except UnicodeDecodeError:
71
+ if encoding == "utf-16" and len(blob) % 2 != 0:
72
+ blob = blob[:-1]
73
+ text = blob.decode(encoding, errors="replace")
74
+ core.log_event("dialogue", f"对话摄取解码({source}):{encoding}", level="info")
75
+ return text
76
+
77
+
78
+ def _dialogue_turns_from_text(text: str, ext: str) -> list:
79
+ """把导出片段解析成 [(role, text)];role ∈ user / ai / other。"""
80
+ turns = []
81
+ for ln in text.splitlines():
82
+ s = ln.strip()
83
+ if not s:
84
+ continue
85
+ if ext == ".jsonl":
86
+ try:
87
+ d = json.loads(s)
88
+ except Exception:
89
+ continue
90
+ if isinstance(d, str):
91
+ turns.append(("other", d))
92
+ continue
93
+ if not isinstance(d, dict):
94
+ continue
95
+ txt = d.get("content") or d.get("text") or d.get("message") or ""
96
+ if isinstance(txt, list): # OpenAI 风格 content parts
97
+ txt = " ".join(str(x.get("text") if isinstance(x, dict) else x) for x in txt)
98
+ txt = str(txt).strip()
99
+ if not txt:
100
+ continue
101
+ raw_role = str(d.get("role") or d.get("sender") or d.get("from") or "").lower()
102
+ if raw_role in ("user", "human", "me", "我", "用户"):
103
+ role = "user"
104
+ elif raw_role in ("assistant", "ai", "bot", "model", "灵枢", "助手"):
105
+ role = "ai"
106
+ else:
107
+ role = "other"
108
+ turns.append((role, txt))
109
+ else:
110
+ m = re.match(r"^\s*(user|human|assistant|ai|bot|model|我|用户|助手|灵枢)\s*[::]\s*(.+)$",
111
+ s, re.I)
112
+ if m:
113
+ who = m.group(1).lower()
114
+ role = "user" if who in ("user", "human", "我", "用户") else "ai"
115
+ turns.append((role, m.group(2).strip()))
116
+ else:
117
+ turns.append(("other", s))
118
+ return turns
119
+
120
+
121
+ def _dialogue_chunks(turns: list, max_chars: int = 700) -> list:
122
+ """相邻轮次拼成块;块满就切。LS-052(v5.66):单轮超长对话也必须执行切分!"""
123
+ chunks, buf, size = [], [], 0
124
+ for role, text in turns:
125
+ if len(text) < 2:
126
+ continue
127
+ prefix = "用户: " if role == "user" else ("我: " if role == "ai" else "")
128
+ piece = prefix + text
129
+ while len(piece) > max_chars:
130
+ if buf:
131
+ chunks.append("\n".join(buf))
132
+ buf, size = [], 0
133
+ chunks.append(piece[:max_chars])
134
+ piece = piece[max_chars:]
135
+ if buf and size + len(piece) > max_chars:
136
+ chunks.append("\n".join(buf))
137
+ buf, size = [], 0
138
+ buf.append(piece)
139
+ size += len(piece) + 1
140
+ if buf:
141
+ chunks.append("\n".join(buf))
142
+ return [c for c in chunks if len(c) >= 8]
143
+
144
+
145
+ def _dialogue_files(sources: list, max_files: int) -> list:
146
+ """收集候选文件(最多 max_files 个,按 mtime 新→旧)。"""
147
+ found = []
148
+ for src in sources:
149
+ root = Path(str(src)).expanduser()
150
+ if not root.is_dir():
151
+ continue
152
+ base_depth = len(root.parts)
153
+ for f in root.rglob("*"):
154
+ try:
155
+ if len(f.parts) - base_depth > _DIALOGUE_MAX_DEPTH:
156
+ continue
157
+ if f.is_file() and f.suffix.lower() in _DIALOGUE_EXTS:
158
+ found.append(f)
159
+ except OSError:
160
+ continue
161
+ found.sort(key=lambda f: -(f.stat().st_mtime if f.exists() else 0))
162
+ return found[:max_files]
163
+
164
+
165
+ def ingest_dialogues(paths=None, limit: int | None = None, dry_run: bool = False) -> dict:
166
+ """增量摄取其他会话的对话导出 → episode 记忆。
167
+
168
+ 参数:
169
+ paths 额外/替代的源目录(缺省用 config.dialogue_sources)
170
+ limit 本次最多处理多少个文件(缺省 config.dialogue_ingest_max_files)
171
+ dry_run 只统计不写库(不推进偏移、不写记忆)
172
+ 返回:{enabled, files, scanned, imported, skipped, chars, dry_run}
173
+ """
174
+ cfg = load_config()
175
+ if not cfg.get("dialogue_ingest"):
176
+ return {"ok": True, "enabled": False, "files": 0, "scanned": 0,
177
+ "imported": 0, "skipped": 0, "chars": 0, "dry_run": dry_run,
178
+ "reason": "未开启:config dialogue_ingest=false"}
179
+ sources = [str(x) for x in (paths or cfg.get("dialogue_sources") or []) if str(x).strip()]
180
+ if not sources:
181
+ return {"ok": True, "enabled": True, "files": 0, "scanned": 0,
182
+ "imported": 0, "skipped": 0, "chars": 0, "dry_run": dry_run,
183
+ "reason": "没有配置 dialogue_sources 目录"}
184
+ max_files = max(1, min(int(limit or cfg.get("dialogue_ingest_max_files") or 50), 500))
185
+ max_chars = max(200, min(int(cfg.get("dialogue_ingest_max_chars") or 700), 2000))
186
+ imported, skipped, chars, touched = 0, 0, 0, 0
187
+ # offsets 既记读取位置,也记已导入块哈希:去重不再全量扫记忆库;
188
+ # 整个读偏移→写记忆→存偏移过程持同一把锁,避免两个进程重复导入。
189
+ with core._locked(_dialogue_offsets_path()):
190
+ files = _dialogue_files(sources, max_files)
191
+ offsets = _dialogue_load_offsets()
192
+ known = {h for entry in offsets.values() if isinstance(entry, dict)
193
+ for h in (entry.get("chunk_hashes") or [])}
194
+ for f in files:
195
+ key = str(f.resolve())
196
+ try:
197
+ st = f.stat()
198
+ except OSError:
199
+ continue
200
+ entry = offsets.get(key) or {}
201
+ # 用 offset==size 判断"已读干净":尾部半行没读完时不跳过,
202
+ # 下次等它补上换行再继续(否则会永久漏掉最后一条)。
203
+ if entry.get("offset") == st.st_size and entry.get("mtime") == st.st_mtime:
204
+ continue # 没变过:完全不读
205
+ start = int(entry.get("offset") or 0)
206
+ if st.st_size < start:
207
+ start = 0 # 文件被截断/重写:从头再来(块哈希去重兜底)
208
+ remaining = max(0, st.st_size - start)
209
+ try:
210
+ with open(f, "rb") as fh:
211
+ fh.seek(start)
212
+ blob = fh.read(min(_DIALOGUE_READ_CAP, remaining))
213
+ except OSError:
214
+ continue
215
+ if remaining > _DIALOGUE_READ_CAP:
216
+ core.log_event("dialogue", f"对话摄取分段读取({f.name}):"
217
+ f"偏移 {start},本次 {len(blob)} 字节,剩余下次继续",
218
+ level="info")
219
+ # 偏移永远落在完整行边界:尾部半行(正在写/无换行结尾)留到下次,
220
+ # 否则续读时会把一条完整的新记录误当成"残片"丢掉。
221
+ if blob and not blob.endswith(b"\n"):
222
+ cut = blob.rfind(b"\n")
223
+ if cut < 0:
224
+ # #29:整块没有换行 = 这个文件被压成了一行(或单行超长)。
225
+ # 原来的裸 continue 不写日志、不推进 offset → 每次读 8MB、
226
+ # 每次跳过,永远不摄取且无任何提示。这里记一次日志
227
+ # (同一文件只报一次,避免每轮刷屏),让用户知道该换格式。
228
+ try:
229
+ _warned = globals().setdefault("_LONGLINE_WARNED", set())
230
+ if str(f) not in _warned:
231
+ _warned.add(str(f))
232
+ core.log_event(
233
+ "dialogue",
234
+ f"跳过 {f.name}:单块 {len(blob)} 字节内没有换行,"
235
+ "疑似被压成一行的导出文件——请改用逐行 JSONL",
236
+ level="warn")
237
+ except Exception: # noqa: BLE001
238
+ pass
239
+ continue
240
+ blob = blob[:cut + 1]
241
+ text = _dialogue_decode(blob, f.name)
242
+ turns = _dialogue_turns_from_text(text, f.suffix.lower())
243
+ file_hashes = list(entry.get("chunk_hashes") or [])
244
+ for chunk in _dialogue_chunks(turns, max_chars):
245
+ digest = hashlib.sha256(chunk.strip().encode("utf-8")).hexdigest()
246
+ if digest in known:
247
+ skipped += 1
248
+ continue
249
+ if not dry_run:
250
+ try:
251
+ _mem().remember(chunk, kind="episode", importance=0.45,
252
+ tags=["对话摄取", f.stem], source="dialogue",
253
+ channel=f"dialogue:{f.stem}")
254
+ except Exception as exc:
255
+ core.log_event("dialogue", f"对话摄取写入失败({f.name}):{exc}", level="warn")
256
+ # 这条吞掉等于"对话没进记忆"——用户以为记下了,其实没有
257
+ core.swallow("dialogue.ingest", exc, where="mem_dialogue")
258
+ continue
259
+ known.add(digest)
260
+ file_hashes.append(digest)
261
+ imported += 1
262
+ chars += len(chunk)
263
+ if not dry_run:
264
+ # offset 只推进到最后一个完整行末尾;尾部半行等下次补全
265
+ offsets[key] = {"offset": start + len(blob), "size": st.st_size,
266
+ "mtime": st.st_mtime, "ts": now_ts(),
267
+ "chunk_hashes": file_hashes}
268
+ touched += 1
269
+ if not dry_run and touched:
270
+ try:
271
+ core.atomic_json(_dialogue_offsets_path(), offsets)
272
+ except Exception as exc:
273
+ # LS-042(v5.66):偏移写失败必须显式报告!
274
+ core.log_event("dialogue",
275
+ f"对话摄取偏移保存失败:{exc}(下次重试仍会处理同一批文件,"
276
+ "内容哈希幂等保证不重复入库)", level="error")
277
+ result["offset_saved"] = False
278
+ result = {"ok": True, "enabled": True, "files": len(files), "scanned": len(files),
279
+ "imported": imported, "skipped": skipped, "chars": chars,
280
+ "dry_run": dry_run, "sources": sources, "offset_saved": True}
281
+ return result
282
+