docs(p1): 补齐 record/私聊/转发读回三证据,定性合并转发不可还原

- 新增 forward-readback-probe(只读):对 history 全部 8 条外层 multimsg 逐条
  重试 get_forward_msg,含数分钟前的 seq=3115,19 种参数组合全失败,
  排除「消息已过期」解释,确认为接口能力缺口(第 20.2 旧依据就地标注缺陷)
- 关键发现:news[].text 能否 parse 成段数组取决于当初 node.content 传数组还是
  JSON 字符串,唯一能 parse 的两条恰是发送形态用错的那两条 ⇒ 属字面文本假象,
  非还原能力。正确形态下段类型与嵌套结构不可逆丢失(GC-012, severity high)
- 未采边界显式登记:正确形态样本节点全是 text,媒体节点降级形态无实测依据,
  不得宣称「只是降级为文本」
- get_msg 实测 9/9 retcode=0 ⇒ 新增 OP-get-msg,作为不依赖 history 窗口分页的
  单条定点读回路径,用于兜底 file 段零事件与私聊 history 分页缺口
- resid 非恒定存在(tsum=0 的静默失效消息 detail_keys 无 resid)⇒ 按可空建模
- record 定性收紧为 MSG-record / MSG-record-silk / MSG-record-transcode 三项;
  私聊段矩阵第三证据 6/6 一致;门禁缺测项 1 → 0
- 能力基线 29 → 30 项、globalConstraints 11 → 12;capability-check 识别
  forwardReadback 自动源。结构校验 0 错误 0 警告,漂移比对自动 21 项、
  漂移 0、缺测 0、人工确认 4 → PASS
This commit is contained in:
2026-10-29 16:27:51 +08:00
parent 49be62e38b
commit a2a781ab4c
9 changed files with 1120 additions and 27 deletions
+4 -2
View File
@@ -103,14 +103,16 @@ function validateAgainst(measureFiles) {
console.log(`\n载入实测记录 ${rows.length} 条,来自 ${measureFiles.map((f) => path.basename(f)).join(', ')}`);
// 建立 case -> 实测行 的索引(matrix / url-media / record / followup 都是 id 字段)
// kind=history 的行是「第三证据」专用行,只有段类型没有 retcode,
// 若混入 byCase 会把同名的发送侧行覆盖掉,造成 retcode 假漂移。
const byCase = new Map();
for (const r of rows) if (r.id && !r.__summary) byCase.set(String(r.id), r);
for (const r of rows) if (r.id && !r.__summary && r.kind !== 'history') byCase.set(String(r.id), r);
// history-audit 提供 history_segs
const audit = new Map();
for (const r of rows) if (r.history_segs) audit.set(String(r.id), r);
// probe 名为 manual/any 的项无法从实测 jsonl 自动比对,单列为人工确认项
const AUTO = new Set(['matrix', 'segments', 'record', 'urlMedia', 'forwardFollowup']);
const AUTO = new Set(['matrix', 'segments', 'record', 'recordAmr', 'recordDecoder', 'urlMedia', 'forwardFollowup', 'forwardReadback']);
let checked = 0, drifted = 0, missing = 0, manual = 0;
for (const c of caps) {
const p = c.regressionProbe;
+171
View File
@@ -0,0 +1,171 @@
// 合并转发读回的针对性补测:修正此前 8 组参数全部传「内层消息 id」的探测缺陷。
//
// 背景:fwd-record-followup.mjs 的 get_forward_msg 全部用 message_id=497853103,
// 那是被转发条目的 id;NapCat 的错误原文恰好是「消息已过期或者为内层消息」,
// 等于自己承认了传错对象。自己发出的那条转发消息的外层 id 从未被试过。
//
// 本脚本只读:先回读 history 找出所有 com.tencent.multimsg 外层消息,
// 再用外层 message_id / resid / uniseq 的多种组合调 get_forward_msg,
// 判定被转发条目到底能否还原、以及能从哪一路还原。不发送任何消息。
//
// 凭据只从环境变量读取。
import fs from 'node:fs';
import path from 'node:path';
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);
const OUT_DIR = process.env.PROBE_OUT || 'local';
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
fs.mkdirSync(OUT_DIR, { recursive: true });
const OUT = path.join(OUT_DIR, `forward-readback-${stamp}.jsonl`);
const say = (...a) => console.log(...a);
const rec = (o) => fs.appendFileSync(OUT, JSON.stringify(o) + '\n');
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);
const api = (action, params, ms = 40000) => new Promise((resolve) => {
const echo = `fr-${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 }));
});
// 1) 回读群 + 私聊 history,挑出所有 multimsg 外层消息,抽 resid/uniseq/tsum
const multimsg = [];
const collect = (msgs, scope) => {
for (const m of msgs ?? []) {
for (const s of m.message ?? []) {
if (s.type !== 'json') continue;
let d; try { d = JSON.parse(s.data.data); } catch { continue; }
if (d.app !== 'com.tencent.multimsg') continue;
const det = d.meta?.detail ?? {};
multimsg.push({
scope, seq: m.real_seq, message_id: m.message_id,
resid: det.resid ?? null, uniseq: det.uniseq ?? null,
filename: d.extra?.filename ?? null, tsum: d.extra?.tsum ?? null,
news_len: (det.news ?? []).length,
news0: (det.news ?? [])[0]?.text ?? null,
view: d.view ?? null,
});
}
}
};
const hg = await api('get_group_msg_history', { group_id: GROUP, count: 100 });
collect(hg?.data?.messages, 'group');
const hp = await api('get_friend_msg_history', { user_id: FRIEND, count: 60 });
collect(hp?.data?.messages, 'private');
say(`history 中 multimsg 外层消息 ${multimsg.length} 条`);
for (const m of multimsg) {
rec({ kind: 'multimsg_outer', ...m });
say(` [${m.scope}] seq=${m.seq} mid=${m.message_id} tsum=${m.tsum} news=${m.news_len} view=${m.view} uniseq=${String(m.uniseq).slice(0, 12)}…`);
}
if (!multimsg.length) { say('history 窗口内没有 multimsg 消息,无法继续(不是能力缺口,是窗口不足)'); try { ws.close(); } catch {} process.exit(3); }
// 2) news[].text 能否还原为段数组 —— 「不依赖任何读回 API」的唯一路径。
// 逐条打印全部 news 原文,因为不同发送形态(content 传段数组 vs 传字符串)落到的
// news 文本形态不同,必须逐条看清才能给「能否还原」下定论。
say('\n--- 还原路径 A:解析 json 段 meta.detail.news[].text ---');
for (const m of multimsg) {
const g = await api('get_msg', { message_id: Number(m.message_id) });
const gm = g?.data;
const jsonSeg = (gm?.message ?? []).find((s) => s.type === 'json');
let detail = null;
try { detail = JSON.parse(jsonSeg.data.data).meta?.detail ?? null; } catch {}
const news = detail?.news ?? [];
const items = news.map((n) => {
const t = String(n.text ?? '');
const colon = t.indexOf(': ');
const body = colon >= 0 ? t.slice(colon + 2) : t;
let parsed = null, err = null;
try { parsed = JSON.parse(body); } catch (e) { err = e.message; }
return { text: t, nick_prefix: colon >= 0 ? t.slice(0, colon) : null,
parse_ok: Array.isArray(parsed), seg_types: Array.isArray(parsed) ? parsed.map((s) => s.type).join('+') : null,
parse_err: err };
});
const okAll = items.length > 0 && items.every((i) => i.parse_ok);
rec({ kind: 'news_recover', scope: m.scope, seq: m.seq, message_id: m.message_id,
get_msg_retcode: g?.retcode ?? null, get_msg_segs: (gm?.message ?? []).map((s) => s.type).join('+') || null,
detail_keys: detail ? Object.keys(detail) : null, tsum: m.tsum, news_len: items.length,
all_parse_ok: okAll, items, resid: m.resid, uniseq: m.uniseq });
say(` [${m.scope}] seq=${String(m.seq).padEnd(5)} get_msg=${g?.retcode} news=${items.length} 全可解析=${okAll ? '★是' : '否'}`);
for (const it of items) {
say(` ${it.parse_ok ? '段数组 ' + it.seg_types : '纯文本 '} | ${it.text.slice(0, 90)}`);
}
}
// 3) get_forward_msg:对**每一条**外层 multimsg 消息都试外层 id,
// 避免把「单条消息过期」误判成「接口能力缺口」。
say('\n--- 还原路径 B:get_forward_msg(外层 message_id,逐条外层消息重试)---');
const outer = [...multimsg].sort((a, b) => Number(b.seq) - Number(a.seq))
.find((m) => m.scope === 'group' && Number(m.tsum) >= 2) ?? multimsg[0];
const outerIds = multimsg.filter((m) => m.scope === 'group');
for (const m of outerIds) {
const r = await api('get_forward_msg', { message_id: Number(m.message_id) });
const nodes = r?.data?.messages ?? r?.data?.nodes ?? null;
rec({ kind: 'get_forward_msg', id: `outer_mid_only:seq${m.seq}`, params: { message_id: Number(m.message_id) },
retcode: r.retcode ?? null, message: r.message ?? r.wording ?? null, timeout: !!r.__timeout,
node_count: Array.isArray(nodes) ? nodes.length : null, resp: r });
say(` 外层 seq=${String(m.seq).padEnd(5)} mid=${String(m.message_id).padEnd(11)} tsum=${m.tsum} retcode=${r.retcode} ${(r.retcode === 0 ? '★成功 ' + JSON.stringify(r.data).slice(0, 140) : (r.message || '').slice(0, 46))}`);
}
const variants = [
{ label: 'outer_mid', params: { message_id: Number(outer.message_id) } },
{ label: 'outer_mid_str', params: { message_id: String(outer.message_id) } },
{ label: 'outer_mid_group', params: { message_id: Number(outer.message_id), group_id: GROUP } },
{ label: 'outer_mid_resid_uniseq', params: { message_id: Number(outer.message_id), resid: outer.resid, uniseq: outer.uniseq } },
{ label: 'outer_mid_resid', params: { message_id: Number(outer.message_id), resid: outer.resid } },
{ label: 'forward_id', params: { forward_id: outer.uniseq } },
{ label: 'id_uniseq', params: { id: outer.uniseq } },
{ label: 'uniseq_only', params: { uniseq: outer.uniseq } },
{ label: 'resid_only', params: { resid: outer.resid } },
{ label: 'filename', params: { filename: outer.filename } },
{ label: 'outer_mid_resid_filename', params: { message_id: Number(outer.message_id), resid: outer.resid, filename: outer.filename } },
];
for (const v of variants) {
const r = await api('get_forward_msg', v.params);
const data = r?.data;
const nodes = data?.messages ?? data?.nodes ?? null;
const ok = r.retcode === 0;
rec({ kind: 'get_forward_msg', id: `outer:${v.label}`, params: v.params, retcode: r.retcode ?? null,
message: r.message ?? r.wording ?? null, timeout: !!r.__timeout,
data_keys: data && typeof data === 'object' ? Object.keys(data) : null,
node_count: Array.isArray(nodes) ? nodes.length : null,
node_segs: Array.isArray(nodes) ? nodes.map((n) => (n.message ?? []).map((s) => s.type).join('+')).join(',') : null,
resp: r });
say(` ${v.label.padEnd(26)} retcode=${r.retcode} ${ok ? '★成功 data=' + JSON.stringify(data).slice(0, 160) : (r.message || '').slice(0, 50)}`);
}
// 4) 其它可能读回转发内容的只读接口
say('\n--- 还原路径 C:其它只读接口 ---');
const others = [
{ label: 'get_msg', action: 'get_msg', params: { message_id: Number(outer.message_id) } },
{ label: 'get_group_msg', action: 'get_group_msg', params: { message_id: Number(outer.message_id) } },
{ label: 'get_forward_msg_no_param', action: 'get_forward_msg', params: {} },
];
for (const o of others) {
const r = await api(o.action, o.params);
rec({ kind: o.action, id: `outer:${o.label}`, action: o.action, params: o.params,
retcode: r.retcode ?? null, message: r.message ?? r.wording ?? null, timeout: !!r.__timeout, resp: r });
const d = JSON.stringify(r?.data ?? null);
say(` ${o.label.padEnd(26)} retcode=${r.retcode} ${(r.retcode === 0 ? 'data=' + d.slice(0, 200) : (r.message || '').slice(0, 60))}`);
}
say('\n结果 -> ' + OUT);
try { ws.close(); } catch {}
process.exit(0);
+92
View File
@@ -0,0 +1,92 @@
// 只读探测:确认「通知类事件」相关 API 是否存在、bot 是否有权限、
// 以及 file/forward 的替代读回路径是否可用。
// 目的是把「未采到 + 原因」写成有依据的结论,而不是猜测。
//
// 全部调用一律使用**不可能成功的参数**(不存在的 user_id / flag / file_id / message_id),
// 因此只暴露「API 是否存在」与「参数校验/权限」错误,不会产生真实外部副作用。
// 真实的通知事件触发需要群主或真人操作,判定结论见末尾输出。
//
// 凭据只从环境变量读取。
import fs from 'node:fs';
import path from 'node:path';
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 OUT_DIR = process.env.PROBE_OUT || 'local';
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
fs.mkdirSync(OUT_DIR, { recursive: true });
const OUT = path.join(OUT_DIR, `notice-capability-${stamp}.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);
const api = (action, params, ms = 25000) => new Promise((resolve) => {
const echo = `nc-${action}-${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 CASES = [
{ id: 'set_group_admin', desc: '管理员变动事件能否由 API 触发',
params: { group_id: GROUP, user_id: 1, enable: true }, reads: '存在性 + bot 权限' },
{ id: 'set_group_kick_members', desc: '成员移除事件能否由 API 触发',
params: { group_id: GROUP, user_id: [1] }, reads: '存在性 + bot 权限' },
{ id: 'set_group_add_request', desc: '加群申请处置接口',
params: { flag: 'NOPE', approve: false, reason: 'probe' }, reads: '存在性 + flag 语义' },
{ id: 'set_friend_add_request', desc: '好友申请处置接口',
params: { flag: 'NOPE', approve: false }, reads: '存在性 + flag 语义' },
{ id: 'get_group_root_files', desc: '群文件列表(file 事件缺失时的对账读回路径)',
params: { group_id: GROUP }, reads: '能否读到已上传文件及 file_id' },
{ id: 'get_group_file_url', desc: '群文件下载直链',
params: { group_id: GROUP, file_id: 'NOPE' }, reads: '存在性 + 参数名' },
// new_group_id=1 是不存在的群,保证「转发」这一步必然失败,只用于读取参数校验信息
{ id: 'forward_group_single_msg', desc: '转发单条消息(合并转发读回的替代路径)',
params: { group_id: GROUP, message_id: 1, new_group_id: 1 }, reads: '存在性 + 参数名校验' },
{ id: 'get_forward_msg', desc: '合并转发读回(已知缺口,留原始错误原文)',
params: { message_id: 1 }, reads: '错误原文' },
{ id: 'get_group_system_msg', desc: '系统通知/加群申请读回',
params: {}, reads: '可用,留原始结构' },
{ id: 'get_doubt_friends_add_request', desc: '可疑好友申请读回',
params: {}, reads: '可用,留原始结构' },
{ id: 'get_group_ignore_add_request', desc: '已忽略的加群申请读回',
params: {}, reads: '可用,留原始结构' },
];
const rows = [];
for (const c of CASES) {
const r = await api(c.id, c.params);
const rc = r.__timeout ? 'TIMEOUT' : r.retcode;
const msg = String(r.message ?? r.wording ?? '');
const verdict = r.__timeout ? '超时'
: /不支持的API/.test(msg) ? 'API 不存在'
: r.retcode === 0 ? '调用成功'
: 'API 存在但被拒';
const rec = { id: c.id, desc: c.desc, reads: c.reads, retcode: rc, verdict,
message: msg, params: c.params,
data_preview: JSON.stringify(r.data ?? null).slice(0, 600) };
rows.push(rec);
fs.appendFileSync(OUT, JSON.stringify({ kind: 'probe', ...rec }) + '\n');
say(`${c.id.padEnd(32)} retcode=${String(rc).padEnd(7)} ${verdict.padEnd(12)} ${msg.slice(0, 66)}`);
}
say('\n结果 -> ' + OUT);
try { ws.close(); } catch {}
process.exit(0);
+110
View File
@@ -0,0 +1,110 @@
// 私聊段类型矩阵的第三证据补齐:用 get_friend_msg_history 回读。
//
// 此前私聊用例(p_text / p_face / p_image_b64 / p_json / p_reply / p_at / p_upload_file)
// 只有「API retcode + 事件回推段」两条证据,缺 history 回读,
// 因为 get_group_msg_history 不适用于私聊。本脚本改用 get_friend_msg_history,
// 纯只读,不发送任何消息,把已有事件的段类型与私聊 history 的段类型逐条对齐。
//
// 判定口径与三证据矩阵一致:retcode=0 不等于送达,必须看回读段。
// 凭据只从环境变量读取。
import fs from 'node:fs';
import path from 'node:path';
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const FRIEND = Number(process.env.PROBE_FRIEND || 2161656029);
const OUT_DIR = process.env.PROBE_OUT || 'local';
const EVENT_FILE = process.env.PROBE_EV || 'local/matrix-ev-2026-10-29T06-48-10-358Z.jsonl';
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
fs.mkdirSync(OUT_DIR, { recursive: true });
const OUT = path.join(OUT_DIR, `private-history-audit-${stamp}.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);
const api = (action, params, ms = 40000) => new Promise((resolve) => {
const echo = `ph-${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 }));
});
// 1) 从已落盘的事件样本里提取私聊自发送消息的标记与段类型
const segsOf = (o) => (Array.isArray(o.message) ? o.message : []).map((s) => s.type).join('+');
const labelOf = (o) => {
const t = (Array.isArray(o.message) ? o.message : [])
.filter((s) => s.type === 'text').map((s) => s.data?.text ?? '').join('');
return (t.match(/\[QLm?:([a-z0-9_]+)\]/i) || [])[1] ?? null;
};
const evById = new Map();
if (fs.existsSync(EVENT_FILE)) {
for (const l of fs.readFileSync(EVENT_FILE, 'utf8').trim().split('\n')) {
let o; try { o = JSON.parse(l); } catch { continue; }
const d = o.data ?? o;
if (d.post_type !== 'message_sent' && d.message_type !== 'private') continue;
if (d.message_type !== 'private') continue;
const lab = labelOf(d);
if (lab) evById.set(lab, { segs: segsOf(d), message_id: d.message_id ?? null, seq: d.real_seq ?? null });
}
}
say(`事件样本中的私聊消息 ${evById.size} 条:${[...evById.keys()].join(', ') || '(无)'}`);
// 2) 只读回读私聊 history
const h = await api('get_friend_msg_history', { user_id: FRIEND, count: Number(process.env.PROBE_COUNT || 60) });
if (h.__timeout || h.retcode !== 0) {
say('get_friend_msg_history 失败:' + JSON.stringify(h).slice(0, 200));
try { ws.close(); } catch {} process.exit(2);
}
const msgs = h?.data?.messages ?? [];
say(`私聊 history 回读 ${msgs.length} 条`);
fs.appendFileSync(OUT, JSON.stringify({ kind: 'history_raw', count: msgs.length }) + '\n');
for (const m of msgs) {
fs.appendFileSync(OUT, JSON.stringify({ kind: 'history_msg', seq: m.real_seq,
message_id: m.message_id, segs: segsOf(m), raw: String(m.raw_message ?? '').slice(0, 300),
message: m.message }) + '\n');
}
// 3) 逐条对齐:事件段 vs history 段
const histByLabel = new Map();
for (const m of msgs) {
const lab = labelOf(m);
if (lab && !histByLabel.has(lab)) histByLabel.set(lab, { segs: segsOf(m), seq: m.real_seq, message_id: m.message_id });
}
say('\n--- 私聊三证据对齐(事件段 vs history 回读段)---');
const rows = [];
let hit = 0, total = 0;
for (const [lab, ev] of evById) {
total++;
const hb = histByLabel.get(lab);
if (!hb) { rows.push({ id: lab, event_segs: ev.segs, readback_segs: null, verdict: 'readback_gap' });
say(` ${lab.padEnd(16)} 事件段=${ev.segs.padEnd(18)} history=未命中 → 回读缺口`); continue; }
const same = ev.segs === hb.segs;
if (same) hit++;
rows.push({ id: lab, event_segs: ev.segs, readback_segs: hb.segs, seq: hb.seq,
verdict: same ? 'consistent' : 'seg_mismatch' });
// 与 history-audit / record-amr 探针保持同一字段口径,使 capability-check 能自动比对 history 列
fs.appendFileSync(OUT, JSON.stringify({ kind: 'history', id: lab, event_segs: ev.segs,
history_segs: hb.segs, history_seq: hb.seq }) + '\n');
say(` ${lab.padEnd(16)} 事件段=${ev.segs.padEnd(18)} history=${hb.segs.padEnd(18)} seq=${hb.seq} ${same ? '一致' : '★段不一致'}`);
}
say(`\n命中并对齐 ${hit}/${total}(history 中未带标记的私聊消息不参与统计)`);
fs.appendFileSync(OUT, JSON.stringify({ __summary: true, rows, hit, total }) + '\n');
say('结果 -> ' + OUT);
try { ws.close(); } catch {}
process.exit(0);
+168
View File
@@ -0,0 +1,168 @@
// record 发送侧的决定性重试:用**真实 amr** 载荷,而不是此前只测过的 silk。
//
// 此前 7 种传法全部失败,但素材只有一个来源:get_ai_record 产出的 silk。
// 这留下一个未排除的解释——「NapCat 只缺 silk 解码,amr 可能可用」。
// 本脚本改用群里**真实存在**的 record 段的 amr 载荷,穷举 NapCat 能拿到字节的三种途径:
// 1) file = 段里的 path(NapCat 宿主机上的本地绝对路径,它自己写的文件,必然可读)
// 2) file = 段里的 url(QQ CDN 新鲜直链,现取现用,避开 rkey 过期)
// 3) file = base64://<下载到的 amr 字节>(绕开 NapCat 的下载逻辑)
// 三者覆盖「读本地 / 自己下载 / 直接给字节」,若仍全失败,
// 「受 NapCat 运行环境解码能力限制」才成为可下笔的确定结论。
//
// 默认 dry-run,--yes 才真实发送(会向测试群发一条语音)。凭据只从环境变量读取。
import fs from 'node:fs';
import path from 'node:path';
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 DO_WRITE = process.argv.includes('--yes');
// 三证据补齐用:只回读 history 并落盘,不发送任何消息。
// 语音发送有真实副作用,不允许为了补一列证据而重复发一遍。
const HISTORY_ONLY = process.argv.includes('--history-only');
const OUT_DIR = process.env.PROBE_OUT || 'local';
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
fs.mkdirSync(OUT_DIR, { recursive: true });
const OUT = path.join(OUT_DIR, `record-amr-${stamp}.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;
const events = [];
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') { if (o.meta_event_type === 'lifecycle') authed = true; return; }
events.push({ el: Date.now(), data: o });
fs.appendFileSync(OUT, JSON.stringify({ kind: 'event', data: o }) + '\n');
};
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 && DO_WRITE) { console.error('未确认认证,中止。'); process.exit(2); }
const api = (action, params, ms = 45000) => new Promise((resolve) => {
const echo = `ra-${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 }));
});
// 取真实 amr 段(url 含时效 rkey,必须现取现用)
const h = await api('get_group_msg_history', { group_id: GROUP, count: 80 });
let seg = null;
for (const m of h?.data?.messages ?? []) {
const s = (m.message ?? []).find((x) => x.type === 'record');
if (s && String(s.data?.file ?? '').endsWith('.amr')) { seg = { seq: m.real_seq, ...s.data }; break; }
}
if (!seg) { say('history 中未找到 amr 形态的 record 段。'); try { ws.close(); } catch {} process.exit(3); }
say(`取到真实 amr 段: seq=${seg.seq} file=${seg.file}`);
say(` path=${seg.path ?? '-'}`);
fs.appendFileSync(OUT, JSON.stringify({ kind: 'source_amr_seg', seq: seg.seq, data: seg }) + '\n');
let amrB64 = null, amrBytes = 0, amrMagic = null, dlStatus = null;
if (seg.url) {
try {
const r = await fetch(seg.url);
const buf = Buffer.from(await r.arrayBuffer());
dlStatus = r.status; amrBytes = buf.byteLength;
amrMagic = buf.subarray(0, 8).toString('hex');
if (r.ok && buf.byteLength > 0) {
amrB64 = buf.toString('base64');
fs.writeFileSync(path.join(OUT_DIR, `record-amr-${stamp}.bin`), buf);
}
} catch (e) { dlStatus = 'ERR ' + e.message; }
}
say(` CDN 下载: HTTP ${dlStatus} ${amrBytes} 字节 magic=${amrMagic ?? '-'}`);
say(` (#!AMR 的 magic 应为 2321414d52,即 "#!AMR")`);
const CASES = [];
if (seg.path) CASES.push({ id: 'amr_localPath', desc: 'file = NapCat 宿主机本地路径(它自己写的文件)',
data: () => ({ file: seg.path }) });
if (seg.url) CASES.push({ id: 'amr_cdnUrl', desc: 'file = 新鲜 QQ CDN 直链',
data: () => ({ file: seg.url }) });
if (amrB64) {
CASES.push({ id: 'amr_b64', desc: 'file = base64://<amr 字节>',
data: () => ({ file: 'base64://' + amrB64 }) });
CASES.push({ id: 'amr_b64_fmt', desc: 'file = base64 + file_name=x.amr',
data: () => ({ file: 'base64://' + amrB64, file_name: 'probe.amr' }) });
CASES.push({ id: 'amr_b64_fmt_amr', desc: 'file = base64 + format=amr',
data: () => ({ file: 'base64://' + amrB64, format: 'amr' }) });
}
if (HISTORY_ONLY) {
const hist = await api('get_group_msg_history', { group_id: GROUP, count: 40 });
say(`\n[history-only] 只回读不发送,命中行:`);
let nHit = 0;
for (const m of hist?.data?.messages ?? []) {
const txt = (m.message ?? []).map((s) => s.data?.text ?? '').join('');
const mm = txt.match(/\[QLr:([A-Za-z0-9_]+)\]/);
if (!mm) continue;
nHit++;
const segs = (m.message ?? []).map((s) => s.type).join('+');
say(` ${mm[1].padEnd(18)} seq=${m.real_seq} 段=${segs}`);
fs.appendFileSync(OUT, JSON.stringify({ kind: 'history', id: mm[1], history_segs: segs, history_seq: m.real_seq }) + '\n');
}
say(`共 ${nHit} 条`);
try { ws.close(); } catch {}
process.exit(0);
}
say(`\n模式=${DO_WRITE ? '真实发送' : 'DRY-RUN'}\n`);
const rows = [];
for (const c of CASES) {
if (!DO_WRITE) { say(`${c.id.padEnd(18)} [计划] ${c.desc}`); continue; }
const t0 = Date.now();
const data = c.data();
const r = await api('send_group_msg', { group_id: GROUP, message: [
{ type: 'record', data }, { type: 'text', data: { text: `[QLr:${c.id}]` } }] });
await new Promise((x) => setTimeout(x, 6000));
const mid = Number(r?.data?.message_id);
const ev = events.find((e) => e.el >= t0 && Number(e.data.message_id) === mid);
const rec = { id: c.id, desc: c.desc, retcode: r.__timeout ? 'TIMEOUT' : r.retcode,
message: String(r.message ?? r.wording ?? ''), message_id: r?.data?.message_id ?? null,
event_segs: ev ? (ev.data.message || []).map((s) => s.type).join('+') : 'NO_EVENT',
event_seq: ev?.data?.real_seq ?? null };
rows.push(rec);
fs.appendFileSync(OUT, JSON.stringify({ kind: 'result', ...rec }) + '\n');
say(`${c.id.padEnd(18)} retcode=${String(rec.retcode).padEnd(6)} 事件段=${String(rec.event_segs).padEnd(12)} ${rec.message.slice(0, 56)}`);
}
if (DO_WRITE) {
// 上一版漏掉 amr_cdnUrl 的回读行,真因是标签正则 [a-z0-9_]+ 不匹配大小写混排的 case id,
// 不是窗口不足。窗口同时放宽到 40 以覆盖全部用例。
await new Promise((x) => setTimeout(x, 4000));
const hist = await api('get_group_msg_history', { group_id: GROUP, count: 40 });
say('\nhistory 回读:');
const seen = new Set();
for (const m of hist?.data?.messages ?? []) {
const hit = (m.message ?? []).some((s) => s.type === 'text' && /\[QLr:([A-Za-z0-9_]+)\]/.test(s.data?.text ?? ''));
if (!hit) continue;
const lab = (m.message ?? []).map((s) => s.data?.text ?? '').join('').match(/\[QLr:([A-Za-z0-9_]+)\]/)[1];
if (seen.has(lab)) continue;
seen.add(lab);
const segs = (m.message ?? []).map((s) => s.type).join('+');
say(` ${lab.padEnd(18)} seq=${m.real_seq} 段=${segs}`);
// 单独落一行,供门禁的 history 列自动比对(与 result 行按 id 关联)
fs.appendFileSync(OUT, JSON.stringify({ kind: 'history', id: lab, history_segs: segs, history_seq: m.real_seq }) + '\n');
const row = rows.find((x) => x.id === lab); if (row) row.history_segs = segs;
}
const miss = rows.filter((r) => r.retcode === 0 && !r.history_segs).map((r) => r.id);
if (miss.length) say(` ⚠️ 以下成功用例未在 history 窗口内回读到:${miss.join(', ')}`);
}
const ok = rows.filter((r) => r.retcode === 0);
say(`\n判定:amr 载荷成功 ${ok.length} 次 / 共 ${rows.length} 次`);
if (ok.length) say('→ 存在可用的 amr 传法,record 应改判为「受限可用」,不得写「环境缺解码器」');
else if (rows.length) say('→ 本地路径 / CDN 直链 / 直接给字节 三条途径全部失败,支持「受 NapCat 运行环境解码能力限制」');
else say('→ DRY-RUN 未实发,不下结论');
fs.appendFileSync(OUT, JSON.stringify({ __summary: true, rows, dlStatus, amrBytes, amrMagic }) + '\n');
say('\n结果 -> ' + OUT);
try { ws.close(); } catch {}
process.exit(0);
+100
View File
@@ -0,0 +1,100 @@
// get_record 正向对照:区分「NapCat 侧 ffmpeg 整体不可用」与「仅缺 silk/amr 解码器」。
//
// 上一轮结论只到「NapCat 连自己收到的真实 amr 也解不开」,但这有两种解释:
// A. ffmpeg 缺失/损坏 → 任何格式都转不了
// B. ffmpeg 在但缺 silk/amr 解码器 → 只有语音类失败
// 两者对 QLinker 的处置不同(A 需修运行环境,B 需换 NapCat 构建或自带转码),
// 因此用一个**自造的合法 WAV**(纯 PCM,无需任何编码器)做正向对照。
//
// 全部只读,不发送消息。凭据只从环境变量读取。
import fs from 'node:fs';
import path from 'node:path';
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const OUT_DIR = process.env.PROBE_OUT || 'local';
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
fs.mkdirSync(OUT_DIR, { recursive: true });
const OUT = path.join(OUT_DIR, `record-codec-probe-${stamp}.jsonl`);
const say = (...a) => console.log(...a);
// 生成 0.5s 8kHz 单声道 16bit PCM 正弦波 WAV
function wav(seconds = 0.5, hz = 440, rate = 8000) {
const n = Math.floor(seconds * rate);
const body = Buffer.alloc(n * 2);
for (let i = 0; i < n; i++) {
const v = Math.round(Math.sin((2 * Math.PI * hz * i) / rate) * 12000);
body.writeInt16LE(v, i * 2);
}
const h = Buffer.alloc(44);
h.write('RIFF', 0); h.writeUInt32LE(36 + body.length, 4); h.write('WAVE', 8);
h.write('fmt ', 12); h.writeUInt32LE(16, 16); h.writeUInt16LE(1, 20); h.writeUInt16LE(1, 22);
h.writeUInt32LE(rate, 24); h.writeUInt32LE(rate * 2, 28); h.writeUInt16LE(2, 32); h.writeUInt16LE(16, 34);
h.write('data', 36); h.writeUInt32LE(body.length, 40);
return Buffer.concat([h, body]);
}
const WAV = wav();
const WAV_B64 = WAV.toString('base64');
fs.writeFileSync(path.join(OUT_DIR, `probe-tone-${stamp}.wav`), WAV);
say(`自造 WAV: ${WAV.length} 字节,magic=${JSON.stringify(WAV.slice(0, 4).toString('latin1'))}`);
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);
const api = (action, params, ms = 40000) => new Promise((resolve) => {
const echo = `cc-${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 }));
});
// 自造 WAV 的输入形式穷举,找出 get_record 到底接受哪种载荷表达
const CASES = [
{ id: 'wav.base64Prefix', p: { file: 'base64://' + WAV_B64, out_format: 'mp3' } },
{ id: 'wav.dataUri', p: { file: 'data:audio/wav;base64,' + WAV_B64, out_format: 'mp3' } },
{ id: 'wav.bareBase64', p: { file: WAV_B64, out_format: 'mp3' } },
{ id: 'wav.b64Field', p: { file: WAV_B64, out_format: 'mp3', b64: true } },
];
const silkFile = fs.readdirSync(OUT_DIR).filter((f) => f.startsWith('record-silk-')).sort().pop();
if (silkFile) {
const silkB64 = fs.readFileSync(path.join(OUT_DIR, silkFile)).toString('base64');
CASES.push({ id: 'silk.base64Prefix', p: { file: 'base64://' + silkB64, out_format: 'mp3' } });
} else {
say('未找到 local/record-silk-*.bin,跳过 silk 对照');
}
const rows = [];
for (const c of CASES) {
const r = await api('get_record', c.p);
const rc = r.__timeout ? 'TIMEOUT' : r.retcode;
const msg = String(r.message ?? r.wording ?? '');
const rec = { id: c.id, retcode: rc, message: msg,
input_len: String(c.p.file ?? '').length,
data_preview: JSON.stringify(r.data ?? null).slice(0, 300) };
rows.push(rec);
fs.appendFileSync(OUT, JSON.stringify({ kind: 'probe', ...rec }) + '\n');
say(`${c.id.padEnd(20)} retcode=${String(rc).padEnd(7)} ${msg.slice(0, 58).padEnd(60)} ${rec.data_preview.slice(0, 50)}`);
}
const wavOk = rows.some((r) => r.id.startsWith('wav.') && r.retcode === 0);
say(`\n判定:自造合法 WAV ${wavOk ? '转换成功 → ffmpeg 可用,缺的是 silk/amr 解码支持' : '全部失败 → 需结合错误类型区分「输入形式不被接受」与「解码器缺失」'}`);
say('注意:若 WAV 各形式均报 file not found,说明 get_record 不接受内联载荷,'
+ '此时本对照**无法**区分 A/B,只能保留「环境解码能力受限」为待验证定性。');
say('\n结果 -> ' + OUT);
try { ws.close(); } catch {}
process.exit(0);
+95
View File
@@ -0,0 +1,95 @@
// record 解码能力的决定性验证(全部只读,不发送任何消息)。
//
// 此前 record 发送侧全部失败,错误为「Failed to open input: Invalid data found」,
// 只能定性为「疑似受 NapCat 运行环境解码能力限制」,但缺少旁证。
// 本脚本改用 NapCat **自己的** get_record(官方文档:获取语音文件信息并支持格式转换):
// 输入使用群里**真实存在**的 record 段的 file / file_id / url / path,
// 若转换成功 → 说明 NapCat 侧 silk/amr 解码链路可用,record 发送失败应归因于
// 发送路径的入参形态;若同样失败 → 才支持「运行环境解码能力受限」的结论。
//
// 凭据只从环境变量读取。
import fs from 'node:fs';
import path from 'node:path';
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 OUT_DIR = process.env.PROBE_OUT || 'local';
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
fs.mkdirSync(OUT_DIR, { recursive: true });
const OUT = path.join(OUT_DIR, `record-decoder-${stamp}.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);
const api = (action, params, ms = 40000) => new Promise((resolve) => {
const echo = `rd-${action}-${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 }));
});
// 现场取真实 record 段(record 的 url 含时效 rkey,必须现取现用)
const h = await api('get_group_msg_history', { group_id: GROUP, count: 80 });
let rec = null;
for (const m of h?.data?.messages ?? []) {
const s = (m.message ?? []).find((x) => x.type === 'record');
if (s) { rec = { seq: m.real_seq, ...s.data }; break; }
}
if (!rec) { say('history 中未找到 record 段,无法验证解码能力。'); try { ws.close(); } catch {} process.exit(3); }
say(`取到 record: seq=${rec.seq} file=${rec.file} file_id=${rec.file_id ?? '-'}`);
fs.appendFileSync(OUT, JSON.stringify({ kind: 'source_record_seg', seq: rec.seq, data: rec }) + '\n');
// 群文件直链(只读):验证 file 类媒体的下载读回路径
const rf = await api('get_group_root_files', { group_id: GROUP });
const firstFile = rf?.data?.files?.[0];
say(`取到群文件: file_id=${firstFile?.file_id ?? '-'} name=${firstFile?.file_name ?? '-'}`);
fs.appendFileSync(OUT, JSON.stringify({ kind: 'source_group_file', data: firstFile ?? null }) + '\n');
const CASES = [];
for (const fmt of ['mp3', 'wav', 'silk']) {
if (rec.file) CASES.push({ id: `get_record.file.${fmt}`, p: { file: rec.file, out_format: fmt } });
if (rec.file_id) CASES.push({ id: `get_record.file_id.${fmt}`, p: { file_id: rec.file_id, out_format: fmt } });
if (rec.url) CASES.push({ id: `get_record.url.${fmt}`, p: { file: rec.url, out_format: fmt } });
if (rec.path) CASES.push({ id: `get_record.path.${fmt}`, p: { file: rec.path, out_format: fmt } });
}
if (firstFile?.file_id) {
CASES.push({ id: 'get_group_file_url.real', p: { group_id: GROUP, file_id: firstFile.file_id } });
}
const rows = [];
for (const c of CASES) {
const r = await api(c.id.startsWith('get_group_file_url') ? 'get_group_file_url' : 'get_record', c.p);
const rc = r.__timeout ? 'TIMEOUT' : r.retcode;
const msg = String(r.message ?? r.wording ?? '');
const rec2 = { id: c.id, params_preview: JSON.stringify(c.p).slice(0, 160),
retcode: rc, message: msg,
data_preview: JSON.stringify(r.data ?? null).slice(0, 400) };
rows.push(rec2);
fs.appendFileSync(OUT, JSON.stringify({ kind: 'probe', ...rec2 }) + '\n');
say(`${c.id.padEnd(28)} retcode=${String(rc).padEnd(7)} ${msg.slice(0, 52).padEnd(54)} ${rec2.data_preview.slice(0, 60)}`);
}
const ok = rows.filter((r) => r.retcode === 0 && r.id.startsWith('get_record'));
say(`\n判定:get_record 成功 ${ok.length} 次 / 共 ${rows.filter((r) => r.id.startsWith('get_record')).length} 次`);
say(ok.length > 0
? '→ NapCat 侧 silk/amr 解码链路可用,record 发送失败应归因于发送路径入参形态,不得写「环境缺解码器」'
: '→ get_record 同样无法解码,支持「受 NapCat 运行环境解码能力限制」的定性');
say('\n结果 -> ' + OUT);
try { ws.close(); } catch {}
process.exit(0);