dsh-qqbot-muu 0.1.21 → 0.1.23

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.
@@ -325,12 +325,24 @@ export async function recall(dataRoot, scope, queryText, cfg = CONFIG) {
325
325
  }
326
326
 
327
327
  /** 把召回结果拼成注入块(≤ recallMaxChars 字) */
328
+ // 来源标签(2026-12-04):群 / 私聊 / 微信 + 日期,避免把 A 群的事当成 B 群的
329
+ function sourceTag(h) {
330
+ const sc = String(h?._scope || h?.scope || '');
331
+ if (!sc) return '';
332
+ const kind = sc.startsWith('group:') ? '群' : sc.startsWith('wechat:') ? '微信' : sc.startsWith('xtc:') ? '小天才' : sc.startsWith('c2c:') ? '私聊' : sc === '__global__' ? '长期' : '';
333
+ if (!kind) return '';
334
+ const d = new Date(Number(h?.ts) || 0);
335
+ const md = Number.isFinite(d.getTime()) && d.getFullYear() > 2000 ? `${d.getMonth() + 1}-${String(d.getDate()).padStart(2, '0')}` : '';
336
+ const gid = kind === '群' ? String(sc.slice(6)).slice(0, 6) : '';
337
+ return `(${kind}${gid ? ' ' + gid : ''}${md ? ' · ' + md : ''})`;
338
+ }
339
+
328
340
  export function formatRecallBlock(hits, cfg = CONFIG) {
329
341
  if (!hits || hits.length === 0) return '';
330
342
  const lines = [];
331
343
  let used = 0;
332
344
  for (const h of hits) {
333
- const line = `${lines.length + 1}. ${h.text}`;
345
+ const line = `${lines.length + 1}. ${sourceTag(h) ? sourceTag(h) + ' ' : ''}${h.text}`;
334
346
  if (used + line.length > cfg.recallMaxChars) break;
335
347
  lines.push(line);
336
348
  used += line.length;
@@ -1,4 +1,5 @@
1
- import { existsSync as __existsSync } from 'node:fs'
1
+ import { existsSync as __existsSync } from 'node:fs'
2
+ import { sanitizeForStore } from './sensitive.mjs';
2
3
  const __repoRoot = (() => {
3
4
  let cached = ''
4
5
  const norm = (p) => String(p || '').split(String.fromCharCode(92)).join('/')
@@ -1138,7 +1139,7 @@ export function cleanMemText(text) {
1138
1139
  }
1139
1140
 
1140
1141
  export async function remember(dataRoot, scope, { text, kind = 'fact', subj = '', srcMsgId = '' } = {}, cfg = CONFIG) {
1141
- const t = cleanMemText(text).slice(0, 300);
1142
+ const t = sanitizeForStore(cleanMemText(text)).slice(0, 300);
1142
1143
  if (t.length < 2) return { ok: false, reason: 'too-short' };
1143
1144
 
1144
1145
  const h = handle(dataRoot);
@@ -1692,12 +1693,25 @@ export function personProfile(dataRoot, senderId) {
1692
1693
  }
1693
1694
 
1694
1695
  /** 把召回结果拼成注入块(≤ recallMaxChars 字)——与 core 逐字一致 */
1696
+ // 来源标签(2026-12-04):让模型知道这条记忆"是群里说的还是私聊说的、哪天说的",
1697
+ // 避免把 A 群的事当成 B 群的;群只显示群号前 6 位,够区分且不泄露完整群号。
1698
+ function sourceTag(h) {
1699
+ const sc = String(h?._scope || h?.scope || '');
1700
+ if (!sc) return '';
1701
+ const kind = sc.startsWith('group:') ? '群' : sc.startsWith('wechat:') ? '微信' : sc.startsWith('xtc:') ? '小天才' : sc.startsWith('c2c:') ? '私聊' : sc === '__global__' ? '长期' : '';
1702
+ if (!kind) return '';
1703
+ const d = new Date(Number(h?.ts) || 0);
1704
+ const md = Number.isFinite(d.getTime()) && d.getFullYear() > 2000 ? `${d.getMonth() + 1}-${String(d.getDate()).padStart(2, '0')}` : '';
1705
+ const gid = kind === '群' ? String(sc.slice(6)).slice(0, 6) : '';
1706
+ return `(${kind}${gid ? ' ' + gid : ''}${md ? ' · ' + md : ''})`;
1707
+ }
1708
+
1695
1709
  export function formatRecallBlock(hits, cfg = CONFIG) {
1696
1710
  if (!hits || hits.length === 0) return '';
1697
1711
  const lines = [];
1698
1712
  let used = 0;
1699
1713
  for (const h of hits) {
1700
- const line = `${lines.length + 1}. ${h.text}`;
1714
+ const line = `${lines.length + 1}. ${sourceTag(h) ? sourceTag(h) + ' ' : ''}${h.text}`;
1701
1715
  if (used + line.length > cfg.recallMaxChars) break;
1702
1716
  lines.push(line);
1703
1717
  used += line.length;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * sensitive.mjs — 记忆审查的唯一实现(2026-12-04 抽出来共用)
3
+ *
4
+ * 背景:这套规则原来只写在 inbound/aa-memory-recall.mjs 里,只保护"召回注入"那一条路。
5
+ * 实际上还有两条路会把原文交出去:
6
+ * ① 模型调用 memory 工具 list(群友让 bot "看看你记得什么" 就能读到);
7
+ * ② 设置面板 /api/qqbot-settings/memory 的"最近记忆"预览。
8
+ * 所以把规则收成一份,三条路共用,避免规则漂移。
9
+ *
10
+ * 原则(主人设计):不是一刀切隐藏记忆,只遮蔽"能被拿去用的隐私字段"。
11
+ */
12
+ import { personalIds } from './personal-ids.mjs';
13
+
14
+ export const SENSITIVE_PATTERNS = [
15
+ { re: /(?<!\d)1[3-9]\d{9}(?!\d)/g, to: '(手机号略)' },
16
+ { re: /(?<!\d)\d{17}[\dXx](?!\d)/g, to: '(身份证略)' },
17
+ { re: /(?<!\d)\d{16,19}(?!\d)/g, to: '(卡号略)' },
18
+ { re: /(密码|口令|验证码)\s*[::=]?\s*\S{4,}/g, to: '$1(略)' },
19
+ { re: /(微信号|微信|vx|VX|QQ号|qq号|账号|帐号)\s*[::=]?\s*[A-Za-z0-9_-]{5,}/g, to: '$1(略)' },
20
+ // 地址只遮蔽"带门牌号"的完整地址(避免把"城市/在市区"这类普通词误伤)
21
+ { re: /([\u4e00-\u9fa5]{2,12}(?:省|市|区|县)[\u4e00-\u9fa5]{0,12}(?:路|街|道|小区|镇|村))(\s*\d{1,5}\s*(?:号|栋)(?:\s*\d{1,5}\s*(?:单元|室|楼|层))?|\s*\d{1,5}\s*(?:单元|室|楼|层))/g, to: '$1(门牌略)' },
22
+ // 令牌 / 密钥 / cookie(2026-12-04 补:这类字符串被记住最危险)
23
+ // sk-… / ghp_… / github_pat_… / npm_… 都是"前缀 + 连接符",两种连接符都要认
24
+ { re: /\b(?:sk|ghp|gho|ghu|ghs|github_pat|npm|xoxb)[-_][A-Za-z0-9_-]{12,}/g, to: '(密钥略)' },
25
+ { re: /(token|cookie|secret|passwd|password)\s*[::=]\s*\S{6,}/gi, to: '$1(略)' },
26
+ ];
27
+
28
+ export function redactSensitive(text) {
29
+ let s = String(text || '');
30
+ for (const p of SENSITIVE_PATTERNS) {
31
+ try { s = s.replace(p.re, p.to); } catch { /* 不支持 lookbehind 的运行时跳过这一条 */ }
32
+ }
33
+ return s;
34
+ }
35
+
36
+ /** 套记忆/倒资料的口吻(只拦"列全部/导出/念出来",普通询问不受影响) */
37
+ export function isDumpRequest(text) {
38
+ const s = String(text || '');
39
+ if (!s || s.length > 200) return false;
40
+ const wantsAll = /(全部|所有|全都|整个|完整|逐条|一条一条|列出来|列一下|导出|备份|复述|念出来|背出来|发给我|打包)/;
41
+ const target = /(记忆|记忆库|数据库|档案|设定|世界书|知识库|后台|系统提示|提示词|prompt|人设|配置)/i;
42
+ return wantsAll.test(s) && target.test(s);
43
+ }
44
+
45
+ /** 主人身份集合(本机身份表里的 owners + 妹妹);读不到就是空集 */
46
+ export function ownerIds() {
47
+ try {
48
+ const ids = personalIds();
49
+ const out = new Set((ids && Array.isArray(ids.owners) ? ids.owners : []).map((x) => String(x)).filter(Boolean));
50
+ if (ids && ids.stelle) out.add(String(ids.stelle));
51
+ return out;
52
+ } catch {
53
+ return new Set();
54
+ }
55
+ }
56
+
57
+ export function isOwnerId(id) {
58
+ const s = String(id || '').trim();
59
+ return Boolean(s) && ownerIds().has(s);
60
+ }
61
+
62
+ /**
63
+ * 入库前清洗(2026-12-04):遮码只保护"显示",密码/验证码/密钥这类**根本没有记忆价值**的
64
+ * 字符串不该被长期保存 —— 一旦落库,面板、备份、导出、模型上下文全是风险点。
65
+ * 所以这里只削"秘密本身"(密码/口令/验证码/密钥/token/cookie),
66
+ * 手机号、地址、人名等有语义的字段保持原样(那些靠显示层按身份遮蔽,主人仍可看全)。
67
+ */
68
+ const STORE_SECRET_PATTERNS = [
69
+ { re: /((?:密码|口令|验证码|支付密码)\s*(?:是|为|[::=])?\s*)\S{4,}/g, to: '$1(略)' },
70
+ { re: /\b(?:sk|ghp|gho|ghu|ghs|github_pat|npm|xoxb)[-_][A-Za-z0-9_-]{12,}/g, to: '(密钥略)' },
71
+ { re: /((?:token|cookie|secret|passwd|password)\s*[::=]\s*)\S{6,}/gi, to: '$1(略)' },
72
+ ];
73
+
74
+ export function sanitizeForStore(text) {
75
+ let s = String(text || '');
76
+ for (const p of STORE_SECRET_PATTERNS) {
77
+ try { s = s.replace(p.re, p.to); } catch { /* 运行时限制,跳过 */ }
78
+ }
79
+ return s;
80
+ }
@@ -45,6 +45,7 @@ const __repoRoot = (() => {
45
45
  */
46
46
  import { loadConfig, pushInbox, listAll, forgetAnywhere, remember } from '../lib/memory.mjs';
47
47
  import { scopeOfTarget } from '../lib/scope-util.mjs';
48
+ import { redactSensitive, ownerIds } from '../lib/sensitive.mjs';
48
49
 
49
50
  const DATA_ROOT_FALLBACK = __repoRoot() + "/dshqqbot";
50
51
 
@@ -132,15 +133,27 @@ export default {
132
133
 
133
134
  if (action === 'list') {
134
135
  const limit = Math.max(1, Math.min(100, Number(args?.limit) || 20));
136
+ // 记忆审查(2026-12-04 落地):非主人调用时
137
+ // ① 不允许翻全库(否则群友一句"列出来"就能看别人的记忆);
138
+ // ② 正文里的手机号/证件/卡号/密码/密钥一律遮蔽 —— 与召回注入同一套规则。
139
+ const asker = String(env?.message?.senderId || env?.caps?.peer?.peerId || '');
140
+ const isOwner = ownerIds().has(asker);
135
141
  // 拿不到当前会话时只能看全库,并在抬头里说明,不能假装"这个会话"
136
- const all = String(args?.scope || '').trim().toLowerCase() === 'all' || !here;
142
+ const wantAll = String(args?.scope || '').trim().toLowerCase() === 'all';
143
+ if (wantAll && !isOwner) {
144
+ return { ok: false, msg: '全库记忆只有主人能看;这里只能看当前会话(去掉 scope=all 即可)。' };
145
+ }
146
+ const all = wantAll || !here;
137
147
  let items = listAll(root, { limit: all ? limit : Math.min(500, limit * 5), scopeFilter: all ? '' : here });
138
148
  if (!all && here) items = items.filter((x) => x.scope === here);
139
149
  items = items.slice(0, limit);
140
150
  if (items.length === 0) {
141
151
  return { ok: true, msg: all ? '记忆库还是空的。' : `这个会话还没有记忆(${here})。` };
142
152
  }
143
- const lines = items.map((x, i) => `${i + 1}. [${x.id}] ${scopeLabel(x.scope)}·${x.kind || '?'} ${fmtTs(x.ts)}${x.subj ? '(' + x.subj + ')' : ''}:${x.text}`);
153
+ const lines = items.map((x, i) => {
154
+ const body = isOwner ? String(x.text || '') : redactSensitive(x.text);
155
+ return `${i + 1}. [${x.id}] ${scopeLabel(x.scope)}·${x.kind || '?'} ${fmtTs(x.ts)}${x.subj ? '(' + x.subj + ')' : ''}:${body}`;
156
+ });
144
157
  const head = all
145
158
  ? `全库最近 ${items.length} 条${here ? '' : '(当前会话未知,按全库列出)'}:`
146
159
  : `这个会话最近 ${items.length} 条(${here}):`;
@@ -160,7 +173,8 @@ export default {
160
173
  const hit = pool.find((x) => String(x.text || '').includes(needle) && (!here || x.scope === here));
161
174
  if (!hit) return { ok: false, msg: `本会话里没找到包含「${needle}」的记忆` };
162
175
  const ok = forgetAnywhere(root, hit.id);
163
- return { ok, msg: ok ? `已删 [${hit.id}] ${hit.text}` : `删除失败:${hit.id}` };
176
+ const shown = ownerIds().has(String(env?.message?.senderId || env?.caps?.peer?.peerId || '')) ? hit.text : redactSensitive(hit.text);
177
+ return { ok, msg: ok ? `已删 [${hit.id}] ${shown}` : `删除失败:${hit.id}` };
164
178
  }
165
179
 
166
180
  return { ok: false, msg: `不认识的 action: ${action}(add | list | forget)` };
package/package.json CHANGED
@@ -1,119 +1,119 @@
1
- {
2
- "name": "dsh-qqbot-muu",
3
- "version": "0.1.21",
4
- "description": "独立的 DSH QQ 桌宠助手插件:统一记忆库/印象卡、人格注入、表情包视觉打标、三形态桌宠+公网受限链接、逐帧视频流水线、B站运营(自持底盘,零 @zaofan 依赖)",
5
- "type": "module",
6
- "main": "./entry.js",
7
- "exports": {
8
- ".": {
9
- "types": "./dist/index.d.ts",
10
- "import": "./entry.js"
11
- },
12
- "./channel-tools": {
13
- "types": "./dist/channel-tools.d.ts",
14
- "import": "./dist/channel-tools.js"
15
- },
16
- "./sticker-store": {
17
- "types": "./dist/features/sticker-store.d.ts",
18
- "import": "./dist/features/sticker-store.js"
19
- },
20
- "./schedule-store": {
21
- "types": "./dist/features/schedule-store.d.ts",
22
- "import": "./dist/features/schedule-store.js"
23
- },
24
- "./client": "./client/qqbot-settings.js"
25
- },
26
- "bin": {
27
- "dsh-qqbot-muu-install": "install.mjs"
28
- },
29
- "files": [
30
- "index.js",
31
- "entry.js",
32
- "cordis.patch.yml",
33
- "install.mjs",
34
- "README.md",
35
- "CHANGELOG.md",
36
- "LICENSE",
37
- "package.json",
38
- "settings-host.js",
39
- "voice-convert.mjs",
40
- "dist/**",
41
- "!dist/_backup*/**",
42
- "client/**",
43
- "config/modules.json",
44
- "scripts/**",
45
- "dshqqbot/.qqbot-extensions/**",
46
- "!dshqqbot/.qqbot-extensions/data/**",
47
- "!dshqqbot/.qqbot-extensions/*.json",
48
- "dshqqbot/.qqbot-extensions/*.example.json",
49
- "!dshqqbot/.qqbot-extensions/**/*.bak*",
50
- "!dshqqbot/.qqbot-extensions/**/*.lnk",
51
- "!scripts/*.bak*",
52
- "!scripts/private-people*.json",
53
- "!dshqqbot/.qqbot-extensions/**/.state/**",
54
- "!scripts/wx4-*.ps1",
55
- "!scripts/wx4-*.cmd",
56
- "!tmp/**",
57
- "!data/**",
58
- "!scripts/publish-npm.mjs",
59
- "docs/RELEASE_CHECKLIST.md",
60
- "!scripts/*.ps1"
61
- ],
62
- "dsh": {
63
- "bundle": {
64
- "patch": "./cordis.patch.yml"
65
- },
66
- "client": {
67
- "platform": "web",
68
- "inject": [
69
- "@deepseek-ai/dsh-client-ui-settings",
70
- "@deepseek-ai/dsh-client-ui-slots"
71
- ],
72
- "immediately": true
73
- },
74
- "engines": {
75
- "dsh": ">=0.1.5-rc.2"
76
- },
77
- "manifestVersion": 1
78
- },
79
- "dependencies": {
80
- "@deepseek-ai/dsh-client-ui-settings": "0.1.7-rc.1",
81
- "@deepseek-ai/dsh-client-ui-slots": "0.1.7-rc.1",
82
- "@deepseek-ai/schemastery": "3.18.4",
83
- "@tencent-connect/qqbot-connector": "1.2.0",
84
- "@tencent-connect/qqbot-nodejs": "^1.0.4",
85
- "js-yaml": "^4.1.0",
86
- "lamejs-fixed": "^1.2.2",
87
- "silk-wasm": "^3.7.1"
88
- },
89
- "engines": {
90
- "node": ">=22.5"
91
- },
92
- "keywords": [
93
- "qqbot",
94
- "dsh",
95
- "memory",
96
- "sticker",
97
- "bilibili",
98
- "pet"
99
- ],
100
- "license": "MIT",
101
- "author": "wuwo1979",
102
- "repository": {
103
- "type": "git",
104
- "url": "git+https://github.com/wuwo1979/dsh-qqbot-muu.git"
105
- },
106
- "scripts": {
107
- "release:check": "node scripts/release-check.mjs",
108
- "release:check:strict": "node scripts/release-check.mjs --strict",
109
- "prepublishOnly": "node scripts/release-check.mjs --strict",
110
- "ci": "node scripts/release-all.mjs --check",
111
- "release": "node scripts/release-all.mjs",
112
- "flow": "node scripts/flows.mjs",
113
- "doctor": "node scripts/flows.mjs doctor",
114
- "security": "node scripts/security-check.mjs",
115
- "storage": "node scripts/storage.mjs stats",
116
- "clean": "node scripts/storage.mjs clean",
117
- "sync": "node scripts/flows.mjs sync"
118
- }
119
- }
1
+ {
2
+ "name": "dsh-qqbot-muu",
3
+ "version": "0.1.23",
4
+ "description": "独立的 DSH QQ 桌宠助手插件:统一记忆库/印象卡、人格注入、表情包视觉打标、三形态桌宠+公网受限链接、逐帧视频流水线、B站运营(自持底盘,零 @zaofan 依赖)",
5
+ "type": "module",
6
+ "main": "./entry.js",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./entry.js"
11
+ },
12
+ "./channel-tools": {
13
+ "types": "./dist/channel-tools.d.ts",
14
+ "import": "./dist/channel-tools.js"
15
+ },
16
+ "./sticker-store": {
17
+ "types": "./dist/features/sticker-store.d.ts",
18
+ "import": "./dist/features/sticker-store.js"
19
+ },
20
+ "./schedule-store": {
21
+ "types": "./dist/features/schedule-store.d.ts",
22
+ "import": "./dist/features/schedule-store.js"
23
+ },
24
+ "./client": "./client/qqbot-settings.js"
25
+ },
26
+ "bin": {
27
+ "dsh-qqbot-muu-install": "install.mjs"
28
+ },
29
+ "files": [
30
+ "index.js",
31
+ "entry.js",
32
+ "cordis.patch.yml",
33
+ "install.mjs",
34
+ "README.md",
35
+ "CHANGELOG.md",
36
+ "LICENSE",
37
+ "package.json",
38
+ "settings-host.js",
39
+ "voice-convert.mjs",
40
+ "dist/**",
41
+ "!dist/_backup*/**",
42
+ "client/**",
43
+ "config/modules.json",
44
+ "scripts/**",
45
+ "dshqqbot/.qqbot-extensions/**",
46
+ "!dshqqbot/.qqbot-extensions/data/**",
47
+ "!dshqqbot/.qqbot-extensions/*.json",
48
+ "dshqqbot/.qqbot-extensions/*.example.json",
49
+ "!dshqqbot/.qqbot-extensions/**/*.bak*",
50
+ "!dshqqbot/.qqbot-extensions/**/*.lnk",
51
+ "!scripts/*.bak*",
52
+ "!scripts/private-people*.json",
53
+ "!dshqqbot/.qqbot-extensions/**/.state/**",
54
+ "!scripts/wx4-*.ps1",
55
+ "!scripts/wx4-*.cmd",
56
+ "!tmp/**",
57
+ "!data/**",
58
+ "!scripts/publish-npm.mjs",
59
+ "docs/RELEASE_CHECKLIST.md",
60
+ "!scripts/*.ps1"
61
+ ],
62
+ "dsh": {
63
+ "bundle": {
64
+ "patch": "./cordis.patch.yml"
65
+ },
66
+ "client": {
67
+ "platform": "web",
68
+ "inject": [
69
+ "@deepseek-ai/dsh-client-ui-settings",
70
+ "@deepseek-ai/dsh-client-ui-slots"
71
+ ],
72
+ "immediately": true
73
+ },
74
+ "engines": {
75
+ "dsh": ">=0.1.5-rc.2"
76
+ },
77
+ "manifestVersion": 1
78
+ },
79
+ "dependencies": {
80
+ "@deepseek-ai/dsh-client-ui-settings": "0.1.7-rc.1",
81
+ "@deepseek-ai/dsh-client-ui-slots": "0.1.7-rc.1",
82
+ "@deepseek-ai/schemastery": "3.18.4",
83
+ "@tencent-connect/qqbot-connector": "1.2.0",
84
+ "@tencent-connect/qqbot-nodejs": "^1.0.4",
85
+ "js-yaml": "^4.1.0",
86
+ "lamejs-fixed": "^1.2.2",
87
+ "silk-wasm": "^3.7.1"
88
+ },
89
+ "engines": {
90
+ "node": ">=22.5"
91
+ },
92
+ "keywords": [
93
+ "qqbot",
94
+ "dsh",
95
+ "memory",
96
+ "sticker",
97
+ "bilibili",
98
+ "pet"
99
+ ],
100
+ "license": "MIT",
101
+ "author": "wuwo1979",
102
+ "repository": {
103
+ "type": "git",
104
+ "url": "git+https://github.com/wuwo1979/dsh-qqbot-muu.git"
105
+ },
106
+ "scripts": {
107
+ "release:check": "node scripts/release-check.mjs",
108
+ "release:check:strict": "node scripts/release-check.mjs --strict",
109
+ "prepublishOnly": "node scripts/release-check.mjs --strict",
110
+ "ci": "node scripts/release-all.mjs --check",
111
+ "release": "node scripts/release-all.mjs",
112
+ "flow": "node scripts/flows.mjs",
113
+ "doctor": "node scripts/flows.mjs doctor",
114
+ "security": "node scripts/security-check.mjs",
115
+ "storage": "node scripts/storage.mjs stats",
116
+ "clean": "node scripts/storage.mjs clean",
117
+ "sync": "node scripts/flows.mjs sync"
118
+ }
119
+ }
@@ -449,6 +449,15 @@ def fix_subj_copy(db_path: str, key: bytes | None) -> dict:
449
449
  stamp = time.strftime('%Y%m%d-%H%M%S')
450
450
  out_db = os.path.join(os.path.dirname(db_path) or '.', f'memory.repaired-{stamp}.db')
451
451
  shutil.copy2(db_path, out_db)
452
+ # WAL 模式:最新写入在 memory.db-wal 里,只拷 .db 会丢掉最近这段(2026-12-04 发现)。
453
+ # 连 -wal / -shm 一起拷,打开副本时 SQLite 会自动回放,得到完整一致快照。
454
+ for suf in ('-wal', '-shm'):
455
+ src = db_path + suf
456
+ if os.path.exists(src):
457
+ try:
458
+ shutil.copy2(src, out_db + suf)
459
+ except OSError:
460
+ pass
452
461
  conn = open_db(out_db, readonly=False)
453
462
  changed = {'out_db': out_db, 'subj_to_name': 0, 'subj_blanked': 0,
454
463
  'digest_relabeled': 0, 'fts_updated': 0}
@@ -27,7 +27,9 @@ const REPO = 'wuwo1979/dsh-qqbot-muu'
27
27
  const FORK = 'wuwo1979/awesome-dsh-plugin'
28
28
  const UPSTREAM = 'awesome-dsh-plugin/awesome-dsh-plugin'
29
29
  const MARKET_BRANCH = 'release/dsh-qqbot-muu-v0.1.7'
30
- let NPM_PENDING = ''
30
+ let NPM_PENDING = ''
31
+ let STAGE_ID = ''
32
+ let MARKET_PR_USED = 0
31
33
  const MARKET_PR = 17081 // 0 = 每次新开 PR;>0 表示复用该 PR 号
32
34
  const MARKET_FILE = 'data/plugins/wuwo1979__dsh-qqbot-muu.yml'
33
35
  const LOCAL_MARKET = 'submission/data/plugins/wuwo1979__dsh-qqbot-muu.yml'
@@ -240,6 +242,12 @@ function gitFetchMain(token) {
240
242
  const r = gitWithToken(['fetch', '--no-tags', `https://github.com/${REPO}.git`, 'main'], token)
241
243
  return { ok: r.status === 0, out: `${r.stdout || ''}${r.stderr || ''}` }
242
244
  }
245
+ /** 取本地 git 里某个 blob 的原始字节(二进制安全;不存在返回 null) */
246
+ function gitBlob(sha) {
247
+ if (!sha) return null
248
+ const r = spawnSync('git', ['cat-file', 'blob', sha], { maxBuffer: 256 * 1024 * 1024 })
249
+ return r.status === 0 ? r.stdout : null
250
+ }
243
251
  /** 直查注册表(带缓存穿刺)。npm 索引有约 1 分钟传播延迟,`npm view` 会读到旧索引。 */
244
252
  async function registryVersion(v) {
245
253
  try {
@@ -306,8 +314,12 @@ else {
306
314
  else {
307
315
  const tree = []
308
316
  for (const path of puts) {
309
- const buf = readFileSync(path)
310
- const blob = await api(`/repos/${REPO}/git/blobs`, { method: 'POST', body: JSON.stringify({ content: buf.toString('base64'), encoding: 'base64' }) })
317
+ // 必须用 git 里的 blob 内容(已按 .gitattributes / core.autocrlf 归一成 LF),
318
+ // 不能 readFileSync 直接读工作区 —— 那会把 CRLF 原样推上去,
319
+ // 于是远端每个文件都"整篇重写",diff 炸成几万行(0.1.21 实测踩过)。
320
+ const blobBuf = gitBlob(localMap.get(path))
321
+ if (!blobBuf) die(`读不到本地 blob:${path}`)
322
+ const blob = await api(`/repos/${REPO}/git/blobs`, { method: 'POST', body: JSON.stringify({ content: blobBuf.toString('base64'), encoding: 'base64' }) })
311
323
  if (!blob.ok) die(`上传 blob 失败:${path}`, JSON.stringify(blob.j).slice(0, 200))
312
324
  tree.push({ path, mode: '100644', type: 'blob', sha: blob.j.sha })
313
325
  }
@@ -372,28 +384,34 @@ else {
372
384
  const AUTH_FLAG = '--//registry.npmjs.org/:' + '_auth' + 'Token=' + nt
373
385
  if (!nt) die('没有 npm 令牌', '设置 NPM_TOKEN,或把令牌写进 secrets/npm.txt')
374
386
  const r = spawnSync('npm', ['publish', '--access', 'public', '--provenance=false', AUTH_FLAG], { encoding: 'utf8', shell: IS_WIN, stdio: 'pipe' })
375
- // npm 11 起是 staged publishing:PUT 202 只代表进了暂存区,必须 2FA 批准才上线;
376
- // 以前只看 exit code → 202 也报成功、其实注册表里没有。这里必须回查注册表。
377
- // 0.1.20 实测:publish 成功后 packument 有约 1 分钟传播延迟,`npm view` 会读到旧索引,
378
- // 于是"已发布"被误报成"没成功",紧接着重发又撞 409 —— 所以这里直连 registry 并放宽等待。
387
+ // npm 11 起发布是「异步接收」:PUT 会回 202 + “Your package is being processed”,
388
+ // 注册表里要过几分钟才查得到;这期间重发一定撞 409「Cannot publish over previously staged version」。
389
+ // 2026-12-04 实测:0.1.21/0.1.22 都是 202 之后约 3~4 分钟才出现,脚本原来只等 3 分钟 → 误报失败。
379
390
  let isLive = !!(await registryVersion(VERSION))
380
391
  if (!isLive) {
381
392
  const outTxt = `${r.stdout}\n${r.stderr}`
382
- // 「Cannot publish over previously published/staged versions」= 这个版本早就落库/暂存了,
383
- // 不是新失败;先等传播,别急着报错(否则会误导人去重发,再撞 409)。
393
+ const asyncAccepted = /\b202\b/i.test(outTxt) || /being processed/i.test(outTxt)
394
+ // 「Cannot publish over previously published/staged versions」= 这个版本已经在路上,别重发
384
395
  const alreadyLive = /previously published versions|previously staged|409 Conflict/i.test(outTxt)
385
- const staged = /\b202\b/i.test(outTxt)
386
- if (alreadyLive || staged || r.status !== 0) {
387
- for (let i = 0; i < 12 && !isLive; i += 1) {
388
- await new Promise((res) => setTimeout(res, 15000))
389
- isLive = !!(await registryVersion(VERSION))
396
+ if (asyncAccepted) ok('npm 已接收(202),正在处理,等它上线(不重发)')
397
+ const maxWait = asyncAccepted || alreadyLive ? 25 * 60_000 : 3 * 60_000
398
+ const t0 = Date.now()
399
+ for (let i = 0; !isLive && Date.now() - t0 < maxWait; i += 1) {
400
+ await new Promise((res) => setTimeout(res, 20000))
401
+ isLive = !!(await registryVersion(VERSION))
402
+ if (!isLive && i > 0 && i % 6 === 0) {
403
+ console.log(` ${c.dim}…已等 ${Math.round((Date.now() - t0) / 60000)} 分钟,注册表还没同步${c.end}`)
390
404
  }
391
405
  }
392
406
  if (!isLive) {
393
- NPM_PENDING = staged && !alreadyLive
394
- ? `npm 把 ${VERSION} 收进了暂存区(未上线)。去 npm 网页批准暂存版本,或 ` +
395
- `npm stage approve <stage-id>(需要 2FA 动态码)。`
396
- : `npm publish 没成功(exit ${r.status}),注册表里查不到 ${VERSION}。`
407
+ const stageId = (/staged with id ([0-9a-f-]{36})/i.exec(outTxt) || [])[1] || ''
408
+ if (stageId) STAGE_ID = stageId
409
+ NPM_PENDING = asyncAccepted || alreadyLive
410
+ ? `${VERSION} 已被 npm 接收但还没同步到注册表(异步发布常有几分钟到十几分钟延迟)。` +
411
+ `别重发(会撞 409):过几分钟用 npm view dsh-qqbot-muu version 复核即可。`
412
+ : (stageId
413
+ ? `npm 把 ${VERSION} 收进了暂存区(未上线),stage-id=${stageId}。批准:npm stage approve ${stageId}(要 2FA 动态码)。`
414
+ : `npm publish 没成功(exit ${r.status}),注册表里查不到 ${VERSION}。`)
397
415
  console.log(' ! ' + NPM_PENDING)
398
416
  }
399
417
  }
@@ -518,6 +536,7 @@ else {
518
536
  method: 'PATCH',
519
537
  body: JSON.stringify({ title: `dsh-qqbot-muu: ${TAG}`, body: `市场条目更新到 ${TAG}(详见仓库 CHANGELOG.md)。` })
520
538
  })
539
+ MARKET_PR_USED = reuse
521
540
  ok(`PR #${reuse} 标题/正文已更新`)
522
541
  } else {
523
542
  const pr = await api(`/repos/${UPSTREAM}/pulls`, {
@@ -545,6 +564,7 @@ else {
545
564
  body: JSON.stringify({ title: 'dsh-qqbot-muu: ' + TAG, body: '市场条目更新到 ' + TAG + '(详见仓库 CHANGELOG.md)。' })
546
565
  })
547
566
  ok('沿用已开的 PR #' + found.number + ',标题/正文已更新到 ' + TAG)
567
+ MARKET_PR_USED = found.number
548
568
  } else {
549
569
  die('开市场 PR 失败', '分支已存在 PR 但查不到 open 的(' + JSON.stringify(pr.j).slice(0, 200) + ')')
550
570
  }
@@ -552,7 +572,10 @@ else {
552
572
  die('开市场 PR 失败', JSON.stringify(pr.j).slice(0, 400))
553
573
  }
554
574
  }
555
- if (pr.ok) ok(`已新开市场 PR #${pr.j.number}:${pr.j.html_url}`)
575
+ if (pr.ok) {
576
+ MARKET_PR_USED = pr.j.number
577
+ ok(`已新开市场 PR #${pr.j.number}:${pr.j.html_url}`)
578
+ }
556
579
  }
557
580
  }
558
581
 
@@ -605,13 +628,15 @@ if (DRY) {
605
628
  else lines.push(`npm latest ${VERSION}`)
606
629
  }
607
630
 
608
- const pr = await api(`/repos/${UPSTREAM}/pulls/${MARKET_PR}`)
609
- if (!pr.ok) problems.push(`市场 PR #${MARKET_PR} 查不到(HTTP ${pr.status})`)
631
+ const prNum = MARKET_PR_USED || MARKET_PR
632
+ const pr = prNum ? await api(`/repos/${UPSTREAM}/pulls/${prNum}`) : { ok: false, status: 0, j: null }
633
+ if (!prNum) problems.push('这次没拿到市场 PR 编号(上一步没开/没复用成功)')
634
+ else if (!pr.ok) problems.push(`市场 PR #${prNum} 查不到(HTTP ${pr.status})`)
610
635
  else {
611
636
  const t = String(pr.j.title || '')
612
- if (pr.j.state !== 'open') problems.push(`市场 PR #${MARKET_PR} 状态是 ${pr.j.state}(应为 open)`)
613
- else if (!t.includes(VERSION)) problems.push(`市场 PR #${MARKET_PR} 标题还是「${t}」,没带上 ${VERSION}`)
614
- else lines.push(`市场 PR #${MARKET_PR} open · ${t}`)
637
+ if (pr.j.state !== 'open') problems.push(`市场 PR #${prNum} 状态是 ${pr.j.state}(应为 open)`)
638
+ else if (!t.includes(VERSION)) problems.push(`市场 PR #${prNum} 标题还是「${t}」,没带上 ${VERSION}`)
639
+ else lines.push(`市场 PR #${prNum} open · ${t}`)
615
640
  }
616
641
 
617
642
  console.log('')
@@ -94,6 +94,9 @@ const PAIRS = [
94
94
  [__repoRoot() + "/config/models.registry.json", 'dsh-qqbot-muu@', 'dsh-qqbot-muu/config/models.registry.json'],
95
95
  // 存储分区表(2026-11-30):过程性文件(截图/OCR/转码/临时)的唯一目录地图,随包一起走
96
96
  [__repoRoot() + "/config/storage.json", 'dsh-qqbot-muu@', 'dsh-qqbot-muu/config/storage.json'],
97
+ // 包元数据(2026-12-04):副本里的 package.json 是 pnpm 装那一刻拷的,不同步就永远停在旧版本号
98
+ // (0.1.22 重启后副本还显示 0.1.18,判断"到底跑的是哪版"全靠猜)
99
+ [__repoRoot() + "/package.json", 'dsh-qqbot-muu@', 'dsh-qqbot-muu/package.json'],
97
100
  // 两个子插件:整目录同步(2026-11-14 补上 dsh-xtc-muu,之前漏了,改小天才通道不生效)
98
101
  [__repoRoot() + "/dsh-wechat-muu", 'dsh-wechat-muu@', 'dsh-wechat-muu'],
99
102
  [__repoRoot() + "/dsh-xtc-muu", 'dsh-xtc-muu@', 'dsh-xtc-muu'],