dsh-qqbot-muu 0.1.20 → 0.1.21

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 (92) hide show
  1. package/CHANGELOG.md +168 -154
  2. package/client/qqbot-settings.js +13401 -13380
  3. package/dist/config.js +573 -581
  4. package/dist/features/contextless-store.js +247 -247
  5. package/dist/features/four-source.js +338 -336
  6. package/dist/features/group-join-request.js +289 -287
  7. package/dist/features/local-models.js +1494 -1467
  8. package/dist/features/style-layer.js +501 -498
  9. package/dist/features/thinking-log.js +71 -69
  10. package/dist/gateway/bootstrap.js +1704 -1652
  11. package/dist/model/settings-reader.js +193 -102
  12. package/dist/shared/paths.js +128 -0
  13. package/dist/shared/settings-io.js +79 -83
  14. package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
  15. package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -794
  16. package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
  17. package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
  18. package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -444
  19. package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
  20. package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
  21. package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
  22. package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
  23. package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
  24. package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
  25. package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
  26. package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
  27. package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
  28. package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
  29. package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
  30. package/package.json +119 -118
  31. package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
  32. package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
  33. package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
  34. package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
  35. package/scripts/ai-toolkit.py +607 -478
  36. package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
  37. package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
  38. package/scripts/chat-archive/build-sft-v4.py +566 -0
  39. package/scripts/chat-archive/build-sft.py +390 -0
  40. package/scripts/chat-archive/eval-sft.py +155 -0
  41. package/scripts/chat-archive/extract-memory.py +143 -0
  42. package/scripts/chat-archive/inventory.py +182 -0
  43. package/scripts/chat-archive/merge-sft.py +114 -0
  44. package/scripts/chat-archive/qce-pull.py +217 -0
  45. package/scripts/chat-archive/qqheader.py +110 -0
  46. package/scripts/chat-archive/qqkey2.py +113 -0
  47. package/scripts/chat-archive/qqprobe.py +153 -0
  48. package/scripts/chat-archive/screen-collect.py +163 -0
  49. package/scripts/chat-archive/sqlcipher_probe.py +444 -0
  50. package/scripts/episode.py +529 -0
  51. package/scripts/fan-curve.py +218 -0
  52. package/scripts/fan-guard.cmd +8 -0
  53. package/scripts/fan-mode.py +380 -263
  54. package/scripts/gen-image.py +420 -413
  55. package/scripts/gen-video.py +186 -178
  56. package/scripts/hw-profile.py +175 -0
  57. package/scripts/media-enhance.py +402 -0
  58. package/scripts/memory-audit.py +581 -0
  59. package/scripts/migrate-scope.mjs +140 -139
  60. package/scripts/qq-connect-login.py +133 -0
  61. package/scripts/qq-ip-sync-hidden.vbs +5 -0
  62. package/scripts/qq-ip-sync.py +300 -0
  63. package/scripts/qq-whitelist.py +71 -0
  64. package/scripts/release-all.mjs +636 -509
  65. package/scripts/release-check.mjs +244 -226
  66. package/scripts/secure-room/index.html +334 -0
  67. package/scripts/secure-room/server.py +582 -0
  68. package/scripts/stickers/auto-tag.mjs +161 -0
  69. package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
  70. package/scripts/train/gguf-quantize.py +92 -0
  71. package/scripts/train/gguf-to-hf.py +112 -0
  72. package/scripts/train/merge-lora.py +51 -0
  73. package/scripts/train/probe-mirrors.sh +12 -0
  74. package/scripts/train/probe-mirrors2.sh +20 -0
  75. package/scripts/train/setup-wsl.sh +23 -0
  76. package/scripts/train/setup-wsl2.sh +25 -0
  77. package/scripts/train/setup-wsl3.sh +22 -0
  78. package/scripts/train/setup-wsl4.sh +22 -0
  79. package/scripts/train/train-lora.py +319 -0
  80. package/dist/_backup_ctx_20261125_183653/dist/config.d.ts +0 -473
  81. package/dist/_backup_ctx_20261125_183653/dist/config.js +0 -450
  82. package/dist/_backup_ctx_20261125_183653/dist/features/contextless-trim.js +0 -304
  83. package/dist/_backup_ctx_20261125_183653/dist/session/session-manager.js +0 -1588
  84. package/dist/_backup_ctx_20261125_183653/dist/transport/inbound.js +0 -1567
  85. package/dist/_backup_ctx_20261125_183653/dist/transport/outbound.js +0 -647
  86. package/scripts/__pycache__/ai-mode.cpython-311.pyc +0 -0
  87. package/scripts/__pycache__/ai-toolkit.cpython-311.pyc +0 -0
  88. package/scripts/__pycache__/comfy_gen.cpython-311.pyc +0 -0
  89. package/scripts/__pycache__/gen-image.cpython-311.pyc +0 -0
  90. package/scripts/__pycache__/gen-video.cpython-311.pyc +0 -0
  91. package/scripts/__pycache__/model-registry.cpython-311.pyc +0 -0
  92. package/scripts/__pycache__/purge-standby.cpython-311.pyc +0 -0
@@ -0,0 +1,581 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ memory-audit.py — 小蓝记忆库体检 / 整理(本地、离线、零 token)
5
+
6
+ 背景(2026-12-02 主人任务):记忆里有记错的、没来源的、实体噪声,而且特别关心的人
7
+ (木囿 / 启星)的记忆不能被群聊召回或倾倒。这个脚本做四件事:
8
+
9
+ 1. 体检:来源缺失、实体噪声、重复/疑似矛盾、长期零召回、解密失败
10
+ 2. 归因:把每条记忆的 src 按 scope 补成可读来源(qq:c2c / qq:group / wechat / douyin / global)
11
+ 3. 隐私:特别关心的人的记忆是否越界(出现在别的 scope / 群召回里)、是否含敏感字段
12
+ 4. 整理:--fix 时先把库备份一份,再做**只增不减**的安全整理(补 src、删垃圾实体、合并完全重复)
13
+
14
+ 用法:
15
+ python scripts/memory-audit.py # 只体检,打印摘要 + 写 JSON 报告
16
+ python scripts/memory-audit.py --json # 只输出 JSON(给别的程序吃)
17
+ python scripts/memory-audit.py --fix # 体检 + 安全整理(自动备份)
18
+ python scripts/memory-audit.py --db X --key Y # 换库 / 换密钥文件
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import base64
24
+ import hashlib
25
+ import json
26
+ import os
27
+ import re
28
+ import shutil
29
+ import sqlite3
30
+ import sys
31
+ import time
32
+ from collections import Counter, defaultdict
33
+ from datetime import datetime, timezone
34
+
35
+ ENC_PREFIX = 'enc1:'
36
+ DEFAULT_DB = r'F:\qqbot\dshqqbot\.qqbot\memory.db'
37
+ DEFAULT_ROOT = r'F:\qqbot\dshqqbot'
38
+ OUT_DIR = r'F:\qqbot\out\memory-audit'
39
+
40
+ # 实体噪声:URL/代码碎片/虚词,不该当"人物/事物"记着
41
+ JUNK_ENTITY_EXACT = {
42
+ 'https', 'http', 'www', 'com', 'cn', 'org', 'net', 'html', 'json', 'js', 'mjs', 'py', 'md',
43
+ 'token', 'bug', 'ai', 'qq', 'dsh', 'api', 'url', 'id', 'ok', 'jpg', 'png', 'mp4', 'txt',
44
+ '而不', '就是', '但是', '因为', '所以', '然后', '而且', '已经', '可以', '还是', '这个', '那个',
45
+ '什么', '怎么', '自己', '一个', '没有', '不是', '这样', '那样', '现在', '时候', '东西',
46
+ }
47
+ JUNK_ENTITY_RE = re.compile(r'(https?|www\.|\.com|\.cn|\.org|\.net|/|\\|\d{4,})', re.I)
48
+ SENSITIVE_RE = re.compile(
49
+ r'(\b1[3-9]\d{9}\b' # 手机号
50
+ r'|\b\d{17}[\dXx]\b' # 身份证
51
+ r'|\b\d{16,19}\b' # 银行卡
52
+ r'|(密码|口令|验证码|支付密码|身份证号|银行卡号))'
53
+ )
54
+ STOP = {'的', '了', '是', '我', '你', '他', '她', '它', '在', '有', '和', '与', '就', '都', '也', '很'}
55
+
56
+
57
+ def now_ms() -> int:
58
+ return int(time.time() * 1000)
59
+
60
+
61
+ def load_key(path: str) -> bytes | None:
62
+ try:
63
+ h = open(path, encoding='utf-8').read().strip()
64
+ return bytes.fromhex(h) if re.fullmatch(r'[0-9a-fA-F]{64}', h) else None
65
+ except Exception:
66
+ return None
67
+
68
+
69
+ def decrypt(stored: str, key: bytes | None) -> tuple[str, bool]:
70
+ """返回 (明文, 是否解密失败)。明文直通。"""
71
+ s = str(stored or '')
72
+ if not s.startswith(ENC_PREFIX):
73
+ return s, False
74
+ if not key:
75
+ return '', True
76
+ try:
77
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
78
+ buf = base64.b64decode(s[len(ENC_PREFIX):])
79
+ iv, tag, body = buf[:12], buf[12:28], buf[28:]
80
+ return AESGCM(key).decrypt(iv, body + tag, None).decode('utf-8'), False
81
+ except Exception:
82
+ return '', True
83
+
84
+
85
+ def norm_text(t: str) -> str:
86
+ t = re.sub(r'[\s\u3000]+', '', str(t or ''))
87
+ t = re.sub(r'[,。!?、;:""''()()\[\]{}<>~!?,.;:]', '', t)
88
+ return t
89
+
90
+
91
+ def open_db(path: str, readonly: bool) -> sqlite3.Connection:
92
+ if readonly:
93
+ uri = 'file:%s?mode=ro' % path.replace('\\', '/')
94
+ conn = sqlite3.connect(uri, uri=True, timeout=10)
95
+ else:
96
+ conn = sqlite3.connect(path, timeout=20)
97
+ conn.row_factory = sqlite3.Row
98
+ return conn
99
+
100
+
101
+ def build_people(conn: sqlite3.Connection) -> dict:
102
+ """openid / 群号 → 可读名字(从 persona 卡片 + chat 台账里凑,不联网)"""
103
+ people = {}
104
+ try:
105
+ for scope, ckey, cvalue in conn.execute("select scope, ckey, cvalue from persona where ckey like 'card:%'"):
106
+ oid = str(ckey)[5:]
107
+ try:
108
+ name = str(cvalue).split(':')[0][:24]
109
+ except Exception:
110
+ name = ''
111
+ if name:
112
+ people[oid] = name
113
+ except Exception:
114
+ pass
115
+ try:
116
+ for sid, name, n in conn.execute(
117
+ "select sender_id, sender, count(*) c from chat where sender_id not in ('', 'self') group by sender_id, sender order by c desc"
118
+ ):
119
+ people.setdefault(str(sid), str(name))
120
+ except Exception:
121
+ pass
122
+ # 特别关心的人(配置在扩展数据里)
123
+ tiers_path = os.path.join(DEFAULT_ROOT, '.qqbot-extensions', 'data', 'group-tiers.json')
124
+ priority = []
125
+ try:
126
+ tiers = json.load(open(tiers_path, encoding='utf-8'))
127
+ priority = list(tiers.get('priorityPeople') or [])
128
+ except Exception:
129
+ pass
130
+ for oid in priority:
131
+ people.setdefault(oid, oid)
132
+ return {'names': people, 'priority': priority}
133
+
134
+
135
+ def audit(db_path: str, key: bytes | None) -> dict:
136
+ conn = open_db(db_path, readonly=True)
137
+ conn.row_factory = sqlite3.Row
138
+ meta = {r['k']: r['v'] for r in conn.execute('select k, v from meta')}
139
+ ppl = build_people(conn)
140
+ people, priority = ppl['names'], set(ppl['priority'])
141
+
142
+ rep: dict = {
143
+ 'db': db_path,
144
+ 'at': datetime.now(timezone.utc).astimezone().isoformat(timespec='seconds'),
145
+ 'schema_version': meta.get('schema_version'),
146
+ 'people': people,
147
+ 'priority_people': sorted(priority),
148
+ 'counts': {},
149
+ 'source_missing': {},
150
+ 'scope_rows': {},
151
+ 'decrypt_failed': 0,
152
+ 'duplicates': [],
153
+ 'suspected_conflicts': [],
154
+ 'junk_entities': [],
155
+ 'zero_hit_old': 0,
156
+ 'privacy': {},
157
+ 'recall': {},
158
+ 'samples': {},
159
+ }
160
+
161
+ mems = []
162
+ for r in conn.execute('select id, scope, kind, subj, text, ts, hits, last_hit, src from mem'):
163
+ plain, failed = decrypt(r['text'], key)
164
+ mems.append({
165
+ 'id': r['id'], 'scope': r['scope'], 'kind': r['kind'], 'subj': r['subj'] or '',
166
+ 'text': plain, 'ts': r['ts'], 'hits': r['hits'], 'last_hit': r['last_hit'],
167
+ 'src': r['src'] or '', 'decrypt_failed': failed,
168
+ })
169
+ rep['counts']['mem'] = len(mems)
170
+ rep['counts']['mem_decrypt_failed'] = sum(1 for m in mems if m['decrypt_failed'])
171
+ rep['decrypt_failed'] = rep['counts']['mem_decrypt_failed']
172
+
173
+ # scope 分布
174
+ rep['scope_rows'] = dict(Counter(m['scope'] for m in mems).most_common())
175
+
176
+ # ①a 主体与 scope 是否对得上(2026-12-04 主人要求先给比例,再谈修法)
177
+ # 注意:subj 是"这句话在讲谁",不是"这条记忆属于谁"——
178
+ # 爸爸的私聊里记"小蓝住在深海"是正常的(subj=小蓝,scope=c2c:爸爸)。
179
+ # 真正异常的是两类:subj 被写成 32 位 openid(机器号当人名),
180
+ # 以及同一段对话被写进两个 scope(同一内容跨 scope 重复)。
181
+ chat_owner = {}
182
+ try:
183
+ for r in conn.execute(
184
+ "select scope, sender, count(*) c from chat where dir='in' and sender not in ('', '对方', '群友') "
185
+ "group by scope, sender"
186
+ ):
187
+ key = r['scope']
188
+ if key not in chat_owner or r['c'] > chat_owner[key][1]:
189
+ chat_owner[key] = (r['sender'], r['c'])
190
+ except Exception:
191
+ pass
192
+ subj_rep = {'by_scope': {}, 'mismatch': 0, 'openid_subj': 0, 'empty_subj': 0, 'c2c_total': 0,
193
+ 'cross_scope_dup': 0, 'digest_mislabel': 0, 'mem_before_chat': 0}
194
+ texts = defaultdict(list)
195
+ for m in mems:
196
+ t = norm_text(m['text'])[:18]
197
+ if len(t) >= 10:
198
+ texts[t].append(m['scope'])
199
+ if m['kind'] == 'summary' and not m['scope'].startswith('group:') and '群里的' in m['text']:
200
+ subj_rep['digest_mislabel'] += 1
201
+ subj_rep['cross_scope_dup'] = sum(1 for v in texts.values() if len(set(v)) > 1)
202
+ for scope, rows in defaultdict(list, {k: [m for m in mems if m['scope'] == k] for k in rep['scope_rows']}).items():
203
+ if not scope.startswith('c2c:'):
204
+ continue
205
+ oid = scope[4:]
206
+ owner = people.get(oid) or (chat_owner.get(scope) or ('', 0))[0] or oid
207
+ cnt = Counter((m['subj'] or '').strip() for m in rows)
208
+ bad = sum(c for s, c in cnt.items() if s and not re.fullmatch(r'[0-9A-Fa-f]{16,}|wxid_\w+', s) and s != owner)
209
+ oidc = sum(c for s, c in cnt.items() if re.fullmatch(r'[0-9A-Fa-f]{16,}|wxid_\w+', s))
210
+ subj_rep['c2c_total'] += len(rows)
211
+ subj_rep['mismatch'] += bad
212
+ subj_rep['openid_subj'] += oidc
213
+ subj_rep['empty_subj'] += cnt.get('', 0)
214
+ subj_rep['by_scope'][scope] = {
215
+ 'mem': len(rows), 'owner': owner, 'subj_mismatch': bad,
216
+ 'subj_openid': oidc, 'subj_empty': cnt.get('', 0),
217
+ 'top_subj': dict(cnt.most_common(6)),
218
+ }
219
+ # 记忆早于台账最早消息 = 从旧数据目录继承的(不是本会话自己长出来的)
220
+ try:
221
+ for r in conn.execute(
222
+ "select scope, count(*) n from mem m where m.ts > 0 and m.ts < "
223
+ "(select min(ts) from chat c where c.scope = m.scope) group by scope"
224
+ ):
225
+ subj_rep['mem_before_chat'] += int(r['n'] or 0)
226
+ except Exception:
227
+ pass
228
+ rep['subject_scope'] = subj_rep
229
+ rep['counts']['subj_mismatch'] = subj_rep['mismatch']
230
+ rep['counts']['subj_openid'] = subj_rep['openid_subj']
231
+
232
+ # ① 来源缺失
233
+ missing = defaultdict(int)
234
+ for m in mems:
235
+ if not m['src']:
236
+ missing[m['scope']] += 1
237
+ rep['source_missing'] = dict(Counter(missing).most_common())
238
+ rep['counts']['source_missing'] = sum(missing.values())
239
+
240
+ # ② 重复(同 scope + 同 kind + 归一化文本相同)
241
+ groups = defaultdict(list)
242
+ for m in mems:
243
+ if m['text']:
244
+ groups[(m['scope'], m['kind'], norm_text(m['text']))].append(m)
245
+ dups = [g for g in groups.values() if len(g) > 1]
246
+ rep['duplicates'] = [
247
+ {'scope': g[0]['scope'], 'kind': g[0]['kind'], 'n': len(g), 'text': g[0]['text'][:80],
248
+ 'ids': [x['id'] for x in g]}
249
+ for g in sorted(dups, key=len, reverse=True)[:60]
250
+ ]
251
+ rep['counts']['duplicate_groups'] = len(dups)
252
+ rep['counts']['duplicate_rows'] = sum(len(g) - 1 for g in dups)
253
+
254
+ # ③ 疑似矛盾:同 scope 的 fact,主键(前 6 字)相同但数字不同
255
+ facts = defaultdict(list)
256
+ for m in mems:
257
+ if m['kind'] in ('fact', 'preference') and m['text']:
258
+ facts[(m['scope'], norm_text(m['text'])[:6])].append(m)
259
+ conflicts = []
260
+ for k, arr in facts.items():
261
+ if len(arr) < 2:
262
+ continue
263
+ nums = {tuple(re.findall(r'\d+(?:\.\d+)?', x['text'])) for x in arr}
264
+ if len(arr) > 1 and len(nums) > 1:
265
+ conflicts.append({
266
+ 'scope': k[0], 'key': k[1],
267
+ 'items': [{'id': x['id'], 'text': x['text'][:70], 'nums': re.findall(r'\d+(?:\.\d+)?', x['text'])} for x in arr[:6]],
268
+ })
269
+ rep['suspected_conflicts'] = conflicts[:40]
270
+ rep['counts']['suspected_conflicts'] = len(conflicts)
271
+
272
+ # ④ 实体噪声
273
+ junk = []
274
+ for r in conn.execute('select scope, name, kind, hits from mem_entity order by hits desc'):
275
+ name = str(r['name'] or '')
276
+ low = name.lower()
277
+ if (low in JUNK_ENTITY_EXACT or len(name) <= 1 or name in STOP
278
+ or JUNK_ENTITY_RE.search(name) or not re.search(r'[\u4e00-\u9fa5A-Za-z]', name)):
279
+ junk.append({'scope': r['scope'], 'name': name, 'kind': r['kind'], 'hits': r['hits']})
280
+ rep['junk_entities'] = junk[:80]
281
+ rep['counts']['junk_entities'] = len(junk)
282
+
283
+ # ⑤ 长期零召回
284
+ cutoff = now_ms() - 30 * 86400_000
285
+ rep['zero_hit_old'] = sum(1 for m in mems if (m['hits'] or 0) == 0 and (m['ts'] or 0) < cutoff)
286
+ rep['counts']['zero_hit_old'] = rep['zero_hit_old']
287
+
288
+ # ⑥ 隐私:特别关心的人
289
+ priv = {'encrypted_rows': sum(1 for m in mems if m['text'] != '' and not m['decrypt_failed'] and False),
290
+ 'priority_scopes': {}, 'sensitive_hits': [], 'cross_scope_leak': []}
291
+ for oid in priority:
292
+ scope = f'c2c:{oid}'
293
+ rows = [m for m in mems if m['scope'] == scope]
294
+ priv['priority_scopes'][f'{people.get(oid, oid)}({oid[:8]}…)'] = {
295
+ 'mem_rows': len(rows),
296
+ 'kinds': dict(Counter(m['kind'] for m in rows).most_common()),
297
+ 'src_missing': sum(1 for m in rows if not m['src']),
298
+ }
299
+ for m in rows:
300
+ if SENSITIVE_RE.search(m['text']):
301
+ priv['sensitive_hits'].append({'scope': scope, 'id': m['id'], 'text': m['text'][:60]})
302
+ # 越界:同一个人的记忆是否出现在群/别人的 scope 里(按文本前 12 字近似)
303
+ keys = {norm_text(m['text'])[:12] for m in rows if len(norm_text(m['text'])) >= 12}
304
+ if keys:
305
+ for m in mems:
306
+ if m['scope'] != scope and norm_text(m['text'])[:12] in keys:
307
+ priv['cross_scope_leak'].append({'from': scope, 'to': m['scope'], 'text': m['text'][:50]})
308
+ rep['privacy'] = priv
309
+ rep['counts']['sensitive_hits'] = len(priv['sensitive_hits'])
310
+ rep['counts']['cross_scope_leak'] = len(priv['cross_scope_leak'])
311
+
312
+ # ⑦ 召回统计(哪些记忆从来没被用过)
313
+ try:
314
+ top = conn.execute('select scope, count(*) n from mem_recall_log group by scope order by n desc limit 10').fetchall()
315
+ rep['recall'] = {'by_scope': {r['scope']: r['n'] for r in top},
316
+ 'total': conn.execute('select count(*) from mem_recall_log').fetchone()[0]}
317
+ except Exception as e:
318
+ rep['recall'] = {'error': str(e)}
319
+
320
+ # ⑧ 抽样(人眼核对记错没)
321
+ rep['samples'] = {
322
+ 'latest_20': [{'scope': m['scope'], 'kind': m['kind'], 'subj': m['subj'], 'text': m['text'][:90], 'src': m['src']}
323
+ for m in sorted(mems, key=lambda x: x['ts'] or 0, reverse=True)[:20]],
324
+ }
325
+ conn.close()
326
+ return rep
327
+
328
+
329
+ def propose_src(scope: str) -> str:
330
+ if scope == '__global__':
331
+ return 'global'
332
+ if scope.startswith('group:'):
333
+ return 'qq:group'
334
+ if scope.startswith('c2c:'):
335
+ return 'qq:c2c'
336
+ if scope.startswith('wechat:'):
337
+ return 'wechat'
338
+ if scope.startswith('douyin:'):
339
+ return 'douyin'
340
+ if scope.startswith('xtc:'):
341
+ return 'xtc'
342
+ return 'legacy:unknown'
343
+
344
+
345
+ def encrypt(plain: str, key: bytes) -> str:
346
+ """与 memory-db.mjs 的 encText 同格式: enc1:base64(iv12|tag16|cipher)"""
347
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
348
+ iv = os.urandom(12)
349
+ out = AESGCM(key).encrypt(iv, str(plain).encode('utf-8'), None) # ct||tag
350
+ ct, tag = out[:-16], out[-16:]
351
+ return ENC_PREFIX + base64.b64encode(iv + tag + ct).decode('ascii')
352
+
353
+
354
+ # 敏感的"值":密码/身份证/银行卡/手机号本身,脱敏只换值,不动句子
355
+ SECRET_VALUE_PATTERNS = [
356
+ re.compile(r'(密码|口令|支付密码|验证码)(是|为|:|:)?\s*\d{4,8}'),
357
+ re.compile(r'\b1[3-9]\d{9}\b'),
358
+ re.compile(r'\b\d{17}[\dXx]\b'),
359
+ re.compile(r'\b\d{16,19}\b'),
360
+ ]
361
+ # 谈到这些话题时,夹在句子里的 4~8 位数字很可能就是密码/验证码/金额 → 一并打码
362
+ SECRET_CONTEXT_RE = re.compile(r'(密码|验证码|支付|转账|身份证|银行卡|红包)')
363
+
364
+
365
+ def redact(text: str) -> tuple[str, int]:
366
+ """把敏感值打码(保留"密码是***"这种语义),返回 (新文本, 打码处数)"""
367
+ out, n = text, 0
368
+ for pat in SECRET_VALUE_PATTERNS:
369
+ def _sub(m):
370
+ nonlocal n
371
+ n += 1
372
+ s = m.group(0)
373
+ head = re.match(r'^(.*?)(?=\d)', s)
374
+ return (head.group(1) + '***') if head and head.group(1) else '***'
375
+ out = pat.sub(_sub, out)
376
+ if SECRET_CONTEXT_RE.search(out):
377
+ def _sub2(m):
378
+ nonlocal n
379
+ v = m.group(0)
380
+ if re.fullmatch(r'(19|20)\d{2}', v): # 年份放过
381
+ return v
382
+ n += 1
383
+ return '***'
384
+ out = re.sub(r'(?<!\d)\d{4,8}(?!\d)', _sub2, out)
385
+ return out, n
386
+
387
+
388
+ def fix(db_path: str, rep: dict, key: bytes | None) -> dict:
389
+ """安全整理:备份 → 补 src → 删垃圾实体 → 敏感值打码(只动这几类,不删记忆正文)"""
390
+ os.makedirs(OUT_DIR, exist_ok=True)
391
+ stamp = time.strftime('%Y%m%d-%H%M%S')
392
+ bak = os.path.join(OUT_DIR, f'memory-before-fix-{stamp}.db')
393
+ shutil.copy2(db_path, bak)
394
+ conn = open_db(db_path, readonly=False)
395
+ changed = {'src_filled': 0, 'junk_entities_deleted': 0, 'redacted': 0, 'backup': bak}
396
+ try:
397
+ conn.execute('BEGIN')
398
+ for r in conn.execute("select id, scope from mem where src is null or src = ''").fetchall():
399
+ conn.execute('update mem set src = ? where id = ?', (propose_src(r['scope']), r['id']))
400
+ changed['src_filled'] += 1
401
+ for j in rep.get('junk_entities', []):
402
+ cur = conn.execute('delete from mem_entity where scope = ? and name = ? and kind = ?',
403
+ (j['scope'], j['name'], j['kind']))
404
+ changed['junk_entities_deleted'] += cur.rowcount or 0
405
+ # 脱敏:只对"特别关心的人"的私聊记忆(以及任何命中敏感值的行)
406
+ if key:
407
+ for r in conn.execute('select id, scope, text from mem').fetchall():
408
+ plain, failed = decrypt(r['text'], key)
409
+ if failed or not plain or not SENSITIVE_RE.search(plain):
410
+ continue
411
+ new_text, n = redact(plain)
412
+ if n <= 0:
413
+ continue
414
+ stored = encrypt(new_text, key) if str(r['text']).startswith(ENC_PREFIX) else new_text
415
+ conn.execute('update mem set text = ? where id = ?', (stored, r['id']))
416
+ changed['redacted'] += 1
417
+ conn.execute('COMMIT')
418
+ except Exception as e:
419
+ conn.execute('ROLLBACK')
420
+ changed['error'] = str(e)
421
+ conn.close()
422
+ return changed
423
+
424
+
425
+ OPENID_SUBJ_RE = re.compile(r'^[0-9A-Fa-f]{16,}$|^wxid_[0-9a-zA-Z]+$')
426
+
427
+
428
+ def _name_index(conn) -> dict:
429
+ """sender_id → 最常用的人名(用来把 subj 里的机器号换回人名)"""
430
+ idx = {}
431
+ for r in conn.execute(
432
+ "select sender_id, sender, count(*) c from chat "
433
+ "where ifnull(sender_id,'')<>'' and ifnull(sender,'')<>'' "
434
+ "group by sender_id, sender order by c desc"):
435
+ idx.setdefault(r['sender_id'], r['sender'])
436
+ return idx
437
+
438
+
439
+ def fix_subj_copy(db_path: str, key: bytes | None) -> dict:
440
+ """把 subj 里的 openid 换成人名(查不到就留空)+ 私聊摘要错标改词。
441
+
442
+ ★ 产物写到一个**新库**,原库一个字节都不动(主人 2026-12-04 的硬约束:
443
+ 不许改导出的私聊,也不许改现有聊天库;要改就在副本里改)。
444
+ 只动两类:
445
+ 1. subj 是 32 位 openid / wxid 的(机器号当人名,面板上看着像"记到别人名下");
446
+ 2. 私聊 summary 里写成「群里的」(实际是本 scope 的 event),改成「这段对话里」。
447
+ """
448
+ os.makedirs(OUT_DIR, exist_ok=True)
449
+ stamp = time.strftime('%Y%m%d-%H%M%S')
450
+ out_db = os.path.join(os.path.dirname(db_path) or '.', f'memory.repaired-{stamp}.db')
451
+ shutil.copy2(db_path, out_db)
452
+ conn = open_db(out_db, readonly=False)
453
+ changed = {'out_db': out_db, 'subj_to_name': 0, 'subj_blanked': 0,
454
+ 'digest_relabeled': 0, 'fts_updated': 0}
455
+ try:
456
+ names = _name_index(conn)
457
+ conn.execute('BEGIN')
458
+ for r in conn.execute("select id, subj from mem where ifnull(subj,'')<>''").fetchall():
459
+ s = str(r['subj']).strip()
460
+ if not OPENID_SUBJ_RE.match(s):
461
+ continue
462
+ name = names.get(s, '')
463
+ conn.execute('update mem set subj = ? where id = ?', (name, r['id']))
464
+ changed['subj_to_name' if name else 'subj_blanked'] += 1
465
+ if key:
466
+ for r in conn.execute(
467
+ "select id, scope, text from mem "
468
+ "where kind = 'summary' and scope not like 'group:%'").fetchall():
469
+ plain, failed = decrypt(r['text'], key)
470
+ if failed or not plain or '群里的' not in plain:
471
+ continue
472
+ new_text = plain.replace('群里的', '这段对话里')
473
+ stored = encrypt(new_text, key) if str(r['text']).startswith(ENC_PREFIX) else new_text
474
+ conn.execute('update mem set text = ? where id = ?', (stored, r['id']))
475
+ try:
476
+ conn.execute('delete from mem_fts where id = ?', (r['id'],))
477
+ conn.execute('insert into mem_fts(id, scope, text) values (?, ?, ?)',
478
+ (r['id'], r['scope'], new_text))
479
+ changed['fts_updated'] += 1
480
+ except Exception:
481
+ pass
482
+ changed['digest_relabeled'] += 1
483
+ else:
484
+ changed['note'] = '没有 key,摘要措辞没改(只修了 subj)'
485
+ conn.execute('COMMIT')
486
+ except Exception as e:
487
+ conn.execute('ROLLBACK')
488
+ changed['error'] = str(e)
489
+ conn.close()
490
+ return changed
491
+
492
+
493
+ def print_human(rep: dict) -> None:
494
+ c = rep['counts']
495
+ print('=' * 62)
496
+ print(f"记忆库体检 {rep['at']}")
497
+ print(f"库: {rep['db']} schema={rep['schema_version']}")
498
+ print('=' * 62)
499
+ print(f"记忆 {c['mem']} 条 | 解密失败 {c['mem_decrypt_failed']} | 来源缺失 {c['source_missing']}"
500
+ f" | 重复组 {c['duplicate_groups']}(多 {c['duplicate_rows']} 条)"
501
+ f" | 疑似矛盾 {c['suspected_conflicts']} | 垃圾实体 {c['junk_entities']}"
502
+ f" | 30 天零召回 {c['zero_hit_old']}")
503
+ print('\n— scope 分布 —')
504
+ for k, v in rep['scope_rows'].items():
505
+ nm = rep['people'].get(k.split(':')[-1], '')
506
+ print(f" {v:5d} {k} {('(' + nm + ')') if nm else ''}")
507
+ if rep['source_missing']:
508
+ print('\n— 来源缺失(按 scope)—')
509
+ for k, v in rep['source_missing'].items():
510
+ print(f" {v:5d} {k} → 建议 src={propose_src(k)}")
511
+ ss = rep.get('subject_scope') or {}
512
+ if ss.get('by_scope'):
513
+ print('\n— 主体与 scope(私聊)—')
514
+ print(f" 合计 {ss['c2c_total']} 条 | subj 是 openid {ss['openid_subj']} | subj 为空 {ss['empty_subj']}"
515
+ f" | 跨 scope 重复文本 {ss['cross_scope_dup']} 组 | 私聊摘要错标『群里的』{ss['digest_mislabel']}"
516
+ f" | 记忆早于台账 {ss['mem_before_chat']} 条")
517
+ for k, v in sorted(ss['by_scope'].items(), key=lambda x: -x[1]['mem'])[:10]:
518
+ print(f" {v['mem']:5d} {k[:42]} owner={v['owner']} subj≠owner {v['subj_mismatch']}")
519
+ print(' subj: ' + ', '.join(f"{s or '(空)'}×{c}" for s, c in v['top_subj'].items()))
520
+ if rep['duplicates']:
521
+ print('\n— 重复 Top —')
522
+ for d in rep['duplicates'][:8]:
523
+ print(f" ×{d['n']} {d['scope']} [{d['kind']}] {d['text']}")
524
+ if rep['suspected_conflicts']:
525
+ print('\n— 疑似矛盾 Top —')
526
+ for x in rep['suspected_conflicts'][:6]:
527
+ print(f" {x['scope']} …{x['key']}")
528
+ for it in x['items'][:3]:
529
+ print(f" · {it['text']} 数字={it['nums']}")
530
+ if rep['junk_entities']:
531
+ print('\n— 垃圾实体 Top —')
532
+ names = Counter(j['name'] for j in rep['junk_entities'])
533
+ print(' ' + ', '.join(f'{n}×{k}' for n, k in names.most_common(20)))
534
+ p = rep['privacy']
535
+ print('\n— 特别关心的人(隐私)—')
536
+ for who, st in p['priority_scopes'].items():
537
+ print(f" {who}: {st['mem_rows']} 条 {st['kinds']} 来源缺失 {st['src_missing']}")
538
+ print(f" 敏感字段命中 {len(p['sensitive_hits'])} | 跨 scope 疑似越界 {len(p['cross_scope_leak'])}")
539
+ for h in p['sensitive_hits'][:5]:
540
+ print(f" ! {h['scope']} {h['text']}")
541
+ for l in p['cross_scope_leak'][:5]:
542
+ print(f" ! {l['from']} → {l['to']}: {l['text']}")
543
+ print('\n— 召回 —')
544
+ print(' ' + json.dumps(rep['recall'], ensure_ascii=False)[:300])
545
+
546
+
547
+ def main() -> int:
548
+ ap = argparse.ArgumentParser()
549
+ ap.add_argument('--db', default=DEFAULT_DB)
550
+ ap.add_argument('--key', default=os.path.join(DEFAULT_ROOT, '.qqbot', 'secrets', 'memory.key'))
551
+ ap.add_argument('--json', action='store_true')
552
+ ap.add_argument('--fix', action='store_true')
553
+ ap.add_argument('--fix-subj', action='store_true',
554
+ help='把 subj 里的 openid 换成人名(产物写新库 memory.repaired-*.db,原库不动)')
555
+ ap.add_argument('--out', default='')
556
+ args = ap.parse_args()
557
+
558
+ key = load_key(args.key)
559
+ rep = audit(args.db, key)
560
+ if args.fix:
561
+ rep['fix'] = fix(args.db, rep, key)
562
+ if args.fix_subj:
563
+ rep['fix_subj'] = fix_subj_copy(args.db, key)
564
+ os.makedirs(OUT_DIR, exist_ok=True)
565
+ out = args.out or os.path.join(OUT_DIR, 'audit-%s.json' % time.strftime('%Y%m%d-%H%M%S'))
566
+ with open(out, 'w', encoding='utf-8') as f:
567
+ json.dump(rep, f, ensure_ascii=False, indent=2)
568
+ if args.json:
569
+ print(json.dumps(rep, ensure_ascii=False, indent=2))
570
+ else:
571
+ print_human(rep)
572
+ print(f'\n报告已写入: {out}')
573
+ if 'fix' in rep:
574
+ print('整理结果: ' + json.dumps(rep['fix'], ensure_ascii=False))
575
+ if 'fix_subj' in rep:
576
+ print('整理结果(新库, 原库未动): ' + json.dumps(rep['fix_subj'], ensure_ascii=False))
577
+ return 0
578
+
579
+
580
+ if __name__ == '__main__':
581
+ sys.exit(main())