lingshu-skill 5.24.0 → 5.28.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 (61) hide show
  1. package/CHANGELOG.md +181 -0
  2. package/README.md +1577 -1577
  3. package/SKILL-lite.md +59 -59
  4. package/SKILL-tiny.md +38 -38
  5. package/SKILL.md +405 -404
  6. package/cordis-plugin/lingshu-cron/plugin.js +15 -5
  7. package/package.json +52 -52
  8. package/scripts/_ci_env_probe.py +81 -0
  9. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +23 -22
  10. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +181 -0
  11. package/scripts/astrbot_plugin_lingshu/engine/README.md +1577 -1577
  12. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +59 -59
  13. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +38 -38
  14. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +405 -404
  15. package/scripts/astrbot_plugin_lingshu/engine/scripts/_ci_env_probe.py +81 -0
  16. package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +28 -0
  17. package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +218 -190
  18. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +31 -0
  19. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +28 -0
  20. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +43 -0
  21. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +74 -0
  22. package/scripts/astrbot_plugin_lingshu/engine/scripts/coverage_report.py +195 -0
  23. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +28 -0
  24. package/scripts/astrbot_plugin_lingshu/engine/scripts/make_icon.py +24 -0
  25. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +221 -219
  26. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +10 -3
  27. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +31 -0
  28. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +28 -0
  29. package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +470 -460
  30. package/scripts/astrbot_plugin_lingshu/engine/scripts/release.py +42 -0
  31. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +29 -1
  32. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety_net.py +12 -0
  33. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +28 -0
  34. package/scripts/astrbot_plugin_lingshu/make_checksums.py +28 -0
  35. package/scripts/behavior_baseline.py +28 -0
  36. package/scripts/bench.py +218 -190
  37. package/scripts/check_pressure_sync.py +31 -0
  38. package/scripts/check_tag.py +28 -0
  39. package/scripts/check_version.py +47 -0
  40. package/scripts/cli.py +43 -0
  41. package/scripts/core.py +74 -0
  42. package/scripts/coverage_report.py +195 -0
  43. package/scripts/growth.py +28 -0
  44. package/scripts/make_icon.py +24 -0
  45. package/scripts/make_manifest.py +285 -254
  46. package/scripts/make_plugin_zip.py +28 -0
  47. package/scripts/mem_dialogue.py +221 -219
  48. package/scripts/memory.py +10 -3
  49. package/scripts/panel_build.py +31 -0
  50. package/scripts/panel_server.py +28 -0
  51. package/scripts/panels.py +470 -460
  52. package/scripts/release.py +42 -0
  53. package/scripts/run_tests.py +31 -0
  54. package/scripts/safety.py +29 -1
  55. package/scripts/safety_net.py +12 -0
  56. package/scripts/session_import.py +28 -0
  57. package/scripts/sync_engine.py +170 -139
  58. package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +0 -49
  59. package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +0 -53
  60. package/docs//345/217/221/345/270/203/350/207/252/345/212/250/345/214/226.md +0 -54
  61. package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +0 -189
@@ -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
- continue
224
- known.add(digest)
225
- file_hashes.append(digest)
226
- imported += 1
227
- chars += len(chunk)
228
- if not dry_run:
229
- # offset 只推进到最后一个完整行末尾;尾部半行等下次补全
230
- offsets[key] = {"offset": start + len(blob), "size": st.st_size,
231
- "mtime": st.st_mtime, "ts": now_ts(),
232
- "chunk_hashes": file_hashes}
233
- touched += 1
234
- if not dry_run and touched:
235
- try:
236
- core.atomic_json(_dialogue_offsets_path(), offsets)
237
- except Exception as exc:
238
- core.log_event("dialogue", f"对话摄取偏移保存失败:{exc}", level="warn")
239
- return {"ok": True, "enabled": True, "files": len(files), "scanned": len(files),
240
- "imported": imported, "skipped": skipped, "chars": chars,
241
- "dry_run": dry_run, "sources": sources}
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
+
@@ -2733,9 +2733,16 @@ def purge(memory_id: str, confirm_token: str) -> dict:
2733
2733
  """
2734
2734
  if READONLY:
2735
2735
  raise PermissionError("记忆库当前只读,无法物理删除。")
2736
- if not confirm_token or confirm_token != memory_id[:8]:
2737
- raise ValueError(
2738
- f"物理删除需显式确认:--confirm {memory_id[:8]}(传入的确认码不匹配)")
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]}(传入的确认码不匹配)")
2739
2746
  cutoff = now_ts() - _PURGE_COOLDOWN_DAYS * DAY
2740
2747
  with _locked(HOME / "hippocampus.jsonl"):
2741
2748
  records = load_all()
@@ -111,5 +111,36 @@ def main(argv=None) -> int:
111
111
  return 0
112
112
 
113
113
 
114
+ def _ensure_utf8_stdout() -> None:
115
+ """把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
116
+
117
+ 为什么必须有:CI 的 windows-latest stdout 是 cp1252,脚本一 print 中文就
118
+ UnicodeEncodeError 直接退出(实测 sync_engine.py 因此挂掉,Ubuntu 同期正常)。
119
+ 这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
120
+
121
+ reconfigure 不可用(3.6 及更早 / 被替换过的流)时静默跳过,绝不因此再崩。
122
+ """
123
+ for name in ("stdout", "stderr"):
124
+ stream = getattr(sys, name, None)
125
+ fn = getattr(stream, "reconfigure", None)
126
+ if callable(fn):
127
+ try:
128
+ fn(encoding="utf-8", errors="replace")
129
+ continue
130
+ except (OSError, ValueError, AttributeError):
131
+ pass
132
+ # 退路:包一层 UTF-8 writer(errors=replace,坏字符变 ?,不打断程序)
133
+ try:
134
+ import io
135
+ buf = getattr(stream, "buffer", None)
136
+ if buf is not None:
137
+ setattr(sys, name,
138
+ io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
139
+ line_buffering=True))
140
+ except Exception: # noqa: BLE001
141
+ pass
142
+
143
+
114
144
  if __name__ == "__main__":
145
+ _ensure_utf8_stdout()
115
146
  sys.exit(main())
@@ -3050,7 +3050,35 @@ def serve(port: int = 8765, open_browser: bool = True) -> None:
3050
3050
  httpd.server_close()
3051
3051
 
3052
3052
 
3053
+ def _ensure_utf8_stdout() -> None:
3054
+ """把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
3055
+
3056
+ CI 的 windows-latest stdout 是 cp1252:脚本一 print 中文就 UnicodeEncodeError
3057
+ 直接退出(实测 sync_engine.py / make_checksums.py 都因此挂过,Ubuntu 同期正常)。
3058
+ 这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
3059
+ """
3060
+ for name in ("stdout", "stderr"):
3061
+ stream = getattr(sys, name, None)
3062
+ fn = getattr(stream, "reconfigure", None)
3063
+ if callable(fn):
3064
+ try:
3065
+ fn(encoding="utf-8", errors="replace")
3066
+ continue
3067
+ except (OSError, ValueError, AttributeError):
3068
+ pass
3069
+ try:
3070
+ import io
3071
+ buf = getattr(stream, "buffer", None)
3072
+ if buf is not None:
3073
+ setattr(sys, name,
3074
+ io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
3075
+ line_buffering=True))
3076
+ except Exception: # noqa: BLE001
3077
+ pass
3078
+
3079
+
3053
3080
  if __name__ == "__main__":
3081
+ _ensure_utf8_stdout()
3054
3082
  import argparse
3055
3083
  ap = argparse.ArgumentParser()
3056
3084
  # 端口优先取 config.json 的 panel_port(设置页可改),再退回 8765。