Files

108 lines
5.7 KiB
JavaScript
Raw Permalink Normal View History

// 段类型普查(纯只读):把群/私聊 history 可读窗口内**每一条消息的每一段**列出来,
// 统计各段类型出现次数,并列出携带该段的消息标识。
//
// 目的:修正「静默丢段」这类只看事件推送就下的结论。
// 事件不推 ≠ 未落库。若某段在 history 里存在,则 QLinker 可通过 history 兜底恢复,
// 与「彻底丢弃」是两种完全不同的实现策略,不得混写。
//
// 只读:不发送任何消息,不修改任何配置。
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const GROUP = Number(process.env.PROBE_GROUP || 933280401);
const FRIEND = Number(process.env.PROBE_FRIEND || 2161656029);
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const fs = await import('node:fs');
const path = await import('node:path');
const OUT_DIR = process.env.PROBE_OUT || 'local';
fs.mkdirSync(OUT_DIR, { recursive: true });
const OUT = path.join(OUT_DIR, `seg-census-${new Date().toISOString().replace(/[:.]/g, '-')}.jsonl`);
const say = (...a) => console.log(...a);
const ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`);
const pending = new Map();
let opened = false, authed = false;
ws.onopen = () => { opened = true; };
ws.onmessage = (ev) => {
let o; try { o = JSON.parse(String(ev.data)); } catch { return; }
if (o.echo && pending.has(o.echo)) { pending.get(o.echo).resolve(o); pending.delete(o.echo); return; }
if (o.post_type === 'meta_event' && o.meta_event_type === 'lifecycle') authed = true;
};
for (let i = 0; i < 100 && !opened; i++) await new Promise((r) => setTimeout(r, 100));
if (!opened) { console.error('连接超时'); process.exit(1); }
for (let i = 0; i < 100 && !authed; i++) await new Promise((r) => setTimeout(r, 100));
say('认证=' + authed);
if (!authed) { console.error('未收到 lifecycle,中止。'); process.exit(2); }
const api = (action, params, ms = 30000) => new Promise((resolve) => {
const echo = `sc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
const to = setTimeout(() => { pending.delete(echo); resolve({ __timeout: true }); }, ms);
pending.set(echo, { resolve: (o) => { clearTimeout(to); resolve(o); }, to });
ws.send(JSON.stringify({ action, params, echo }));
});
const rec = (o) => { fs.appendFileSync(OUT, JSON.stringify(o) + '\n'); return o; };
const TARGETS = ['poke', 'music', 'location', 'at', 'record', 'video', 'image', 'file',
'json', 'xml', 'node', 'reply', 'face', 'forward', 'contact', 'dice', 'shake', 'miniapp', 'marketface'];
async function census(action, base, label) {
// count 语义为 min(count, 该会话可读总量),取 200 以覆盖当前可读全窗口。
// 返回条数取决于 NapCat 本地保留量,不是接口上限(见 GC-015)。
const r = await api(action, { ...base, count: 200 });
const msgs = r?.data?.messages ?? [];
say(`\n===== ${label} (${action}) retcode=${r.retcode} 共 ${msgs.length} 条 =====`);
if (!msgs.length) { say(' 窗口为空'); return {}; }
const seqs = msgs.map((m) => Number(m.real_seq));
say(` real_seq 范围 ${Math.min(...seqs)}..${Math.max(...seqs)}(升序=${Number(msgs[0].real_seq) < Number(msgs[msgs.length - 1].real_seq)})`);
const byType = new Map();
for (const m of msgs) {
for (const s of (m.message ?? [])) {
if (!byType.has(s.type)) byType.set(s.type, []);
byType.get(s.type).push({
seq: String(m.real_seq), message_id: m.message_id,
sender: m.sender?.user_id ?? null,
data_preview: JSON.stringify(s.data ?? {}).slice(0, 160),
});
}
}
say(' 段类型分布:');
for (const [t, arr] of [...byType.entries()].sort((a, b) => b[1].length - a[1].length)) {
say(` ${t.padEnd(12)} ${String(arr.length).padStart(3)} 条 例 seq=${arr[0].seq} ${arr[0].data_preview.slice(0, 90)}`);
}
const missing = TARGETS.filter((t) => !byType.has(t));
say(' 窗口内**未出现**的目标段类型:' + (missing.join(', ') || '(无)'));
for (const [t, arr] of byType.entries()) {
rec({ kind: 'census', scope: label, seg_type: t, count: arr.length, samples: arr.slice(0, 6) });
}
rec({ kind: 'census_window', scope: label, action, total: msgs.length,
seq_min: String(Math.min(...seqs)), seq_max: String(Math.max(...seqs)),
absent_types: missing });
return byType;
}
const g = await census('get_group_msg_history', { group_id: GROUP }, 'group');
const p = await census('get_friend_msg_history', { user_id: FRIEND }, 'private');
// 重点核对:此前定性为「静默丢段」的三类,在 history 里到底有没有
say('\n===== 静默丢段定性复核(事件无推送,但 history 是否有?)=====');
for (const [label, byType] of [['group', g], ['private', p]]) {
for (const t of ['poke', 'location', 'music', 'record', 'file']) {
const arr = byType.get(t);
say(` ${label.padEnd(8)} ${t.padEnd(9)} ${arr ? 'history 中存在 ' + arr.length + ' 条 → 事件缺失但可回读' : 'history 中不存在'}`);
}
}
// 私聊窗口只有 10 条,把全部原文打出来,便于确认私聊段矩阵的第三证据是否被窗口限制
say('\n===== 私聊窗口全部消息(窗口上限 10,逐条列出)=====');
const pr = await api('get_friend_msg_history', { user_id: FRIEND, count: 200 });
for (const m of pr?.data?.messages ?? []) {
say(` seq=${m.real_seq} mid=${m.message_id} 段=${(m.message ?? []).map((s) => s.type).join('+')} `
+ `文=${(m.message ?? []).filter((s) => s.type === 'text').map((s) => s.data?.text).join('').slice(0, 40)}`);
}
say('\n结果 -> ' + OUT);
try { ws.close(); } catch {}
process.exit(0);