Files
QLinker/tools/probe/history-window-probe.mjs
xiaowang b6401116cb 采样第 25 章:纠正 history 窗口误判,补齐私聊 record 与转发节点形态
推翻本轮前一结论:history 单次返回条数不存在「私聊 10 / 群 46」的接口
硬上限。count 实际生效,语义为 min(count, 该会话可读总量);此前把「可读
总量恰好等于返回条数」误判为上限,补发消息后私聊由 10 条增至 14 条即证伪。
单次返回上限至今未测到,对 count 设上限的理由须改为「防止响应过大」。

分页结论维持但证据加强:start_id/end_id/message_id/msg_id 在窗口边界与
窗口中部两种取值下均返回同一页,12 个候选参数名穷举无效,连续翻页推进 0 页。
固化为 GC-015:history 只是本地滑动窗口,事件流实时落库是唯一完整来源。

补齐私聊 record 独立取证(base64://AMR 与新鲜 CDN 直链均三证据通过,本地
路径 1200),MSG-record 的 supports 扩为 group+private。

新增关键约束:node.content 传段数组时 news 降级为「[图片]」
「[该消息类型暂不支持查看]」等占位串、资源标识完全丢失;传 JSON 字符串时
段结构全保留但客户端按字面文本渲染,属语义损坏,发送侧禁止采用。
另记 GC-016(node 段不得与其他段混发,retcode=1400)、
GC-017(占位串禁止当用户正文入库)。

get_forward_msg 对本连接刚发出的 seq=3124/3125 立即调用仍 1200,
排除「消息已过期」的替代解释。

新增 6 个探针(默认 dry-run,写操作需 --yes),修正
history-page-alias-probe 与 seg-census 中会误导复跑的过期定性,
env-local.md 对应条目就地标注作废并给出更正结论。

门禁 capability-check:30 项能力,结构校验 0 错误 0 警告,PASS。

未执行:NAPCAT_WEBUI_PASSWORD 相关路由预检;HTTP 回调与反向 WS 的
NapCat 真实入站采集(按用户决定跳过本机防火墙改动);QQ 端 6 项手动
验证项仍全部待人工;REL-dedup 的重复投递/乱序/断线补推仍未采到。
2026-10-29 17:59:09 +08:00

151 lines
7.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// history 读回窗口的**上限定性**(纯只读,零副作用)。
//
// 起因:上一轮 get_friend_msg_history 传 count=60 实测只回 10 条。这个数字直接决定
// QLinker 的补拉策略:上限是 10 就要多次分页往返,是 100 则完全不同,不得凭猜测写进设计。
//
// 必须区分三种解释(对补拉策略含义不同):
// A) 接口有硬上限,超出部分被截断
// B) 该会话消息本就不足,返回的是全部
// C) count 参数被忽略(参数名/类型不对),返回的是默认值
// 区分方法:递增 count 多次请求看返回条数何时不再增长;再用 start_id/end_id 翻页,
// 验证翻页能否突破单次上限。
//
// 群与私聊分别测:不同接口,上限不保证一致,不得互相外推。
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, `history-window-${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,中止(GC-008:onopen 不代表认证成功)。'); process.exit(2); }
const api = (action, params, ms = 30000) => new Promise((resolve) => {
const echo = `hw-${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 sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const COUNTS = [1, 5, 10, 20, 30, 50, 60, 80, 100, 200];
async function probe(action, base, label) {
say(`\n===== ${label} (${action}) =====`);
const rows = [];
for (const count of COUNTS) {
const r = await api(action, { ...base, count });
const msgs = r?.data?.messages ?? [];
const row = {
kind: 'result', id: `${label}:count=${count}`, action,
retcode: r.__timeout ? 'TIMEOUT' : r.retcode,
message: String(r.message ?? r.wording ?? ''),
count_param: count,
returned: msgs.length,
first_seq: msgs.length ? String(msgs[0].real_seq) : null,
last_seq: msgs.length ? String(msgs[msgs.length - 1].real_seq) : null,
has_more: r?.data?.has_more ?? null,
};
rows.push(rec(row));
say(` count=${String(count).padStart(3)} -> 返回 ${String(row.returned).padStart(3)} 条 seq ${row.first_seq ?? '-'}..${row.last_seq ?? '-'} ${row.message.slice(0, 40)}`);
await sleep(400);
}
const maxReturned = Math.max(...rows.map((r) => r.returned || 0));
const plateau = rows.filter((r) => r.returned === maxReturned).map((r) => r.count_param);
say(` 最大返回 ${maxReturned} 条,首次达到该值的 count=${plateau[0] ?? '-'}`);
return { rows, maxReturned };
}
const gBase = { group_id: GROUP };
const pBase = { user_id: FRIEND };
const g = await probe('get_group_msg_history', gBase, 'group');
const p = await probe('get_friend_msg_history', pBase, 'private');
say('\n===== 默认值(不传 count)=====');
for (const [action, base, label] of [
['get_group_msg_history', gBase, 'group'],
['get_friend_msg_history', pBase, 'private'],
]) {
const r = await api(action, base);
const n = (r?.data?.messages ?? []).length;
rec({ kind: 'result', id: `${label}:count=default`, action, retcode: r.retcode, returned: n, message: String(r.message ?? '') });
say(` ${label.padEnd(8)} 不传 count -> 返回 ${n} 条`);
}
// 翻页:history 的 real_seq 是 string(GC-010),同时验数字与字符串形式的边界参数
say('\n===== 翻页能力(决定补拉能否覆盖长历史)=====');
// ⚠️ 实测 messages 数组按 real_seq **升序**排列(count=10 → seq 1231..1240),
// 即 m[0] 是窗口内**最旧**、m[last] 是**最新**。取错端会把「最新消息 id」当边界传给
// 翻页参数,返回相同结果属正常,从而误判成「参数未生效」。边界必须取 m[0]。
async function pageProbe(action, base, label) {
const first = await api(action, { ...base, count: 40 });
const m1 = first?.data?.messages ?? [];
if (!m1.length) { say(` ${label}: 无数据,跳过`); return; }
const asc = Number(m1[0].real_seq) < Number(m1[m1.length - 1].real_seq);
say(` ${label}: 第 1 页 ${m1.length} 条,排列=${asc ? '升序(m[0]最旧)' : '降序(m[0]最新)'}`);
const oldest = asc ? m1[0] : m1[m1.length - 1];
const minMid = oldest.message_id;
const minSeq = oldest.real_seq;
say(` ${label}: 窗口内最旧 real_seq=${minSeq} message_id=${minMid}`);
for (const pk of ['start_id', 'end_id']) {
for (const [vform, v] of [['number', minMid], ['string', String(minMid)]]) {
const r = await api(action, { ...base, count: 40, [pk]: v });
const m = r?.data?.messages ?? [];
const gotOldest = m.length ? (asc ? m[0] : m[m.length - 1]) : null;
// 翻页生效的判据:返回窗口里出现了**比 minSeq 更旧**的消息
const pushedBack = m.length > 0 && gotOldest
&& Number(gotOldest.real_seq) < Number(minSeq);
const identical = m.length > 0 && String(m[0].real_seq) === String(m1[0].real_seq)
&& String(m[m.length - 1].real_seq) === String(m1[m1.length - 1].real_seq);
rec({
kind: 'result',
id: `${label}:page:${pk}:${vform}`,
action, retcode: r.retcode, returned: m.length,
first_seq: m.length ? String(m[0].real_seq) : null,
last_seq: m.length ? String(m[m.length - 1].real_seq) : null,
pushed_back: !!pushedBack, identical_to_page1: !!identical,
message: String(r.message ?? ''),
});
say(` ${pk}(${vform})=${v} -> ${m.length} 条 seq ${m.length ? m[0].real_seq + '..' + m[m.length - 1].real_seq : '-'}${pushedBack ? ' [OK] 翻到更旧' : (identical ? ' [!] 与第 1 页完全相同,参数未生效' : '')} ${String(r.message ?? '').slice(0, 40)}`);
}
}
}
await pageProbe('get_group_msg_history', gBase, 'group');
await pageProbe('get_friend_msg_history', pBase, 'private');
say('\n===== 定性 =====');
for (const [label, r] of [['group', g], ['private', p]]) {
const max = r.maxReturned;
const rets = r.rows.map((x) => x.returned);
const allSame = rets.every((n) => n === rets[0]);
say(` ${label}: 各 count 返回条数 = [${rets.join(',')}]`);
if (allSame)
say(` -> 返回条数不随 count 变化(恒为 ${max}):count 未生效,或该会话总数恰为 ${max}。需结合翻页结果区分。`);
else
say(` -> 返回条数随 count 增长,观测到单次上限约 ${max}。`);
}
say('\n结果 -> ' + OUT);
try { ws.close(); } catch {}
process.exit(0);