From b6401116cb4505ed0db2d0fdd5405afa3276c471 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E7=8E=8B-=E7=AC=94=E8=AE=B0=E6=9C=AC?= <2161656029@qq.com> Date: Thu, 29 Oct 2026 17:59:09 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=87=E6=A0=B7=E7=AC=AC=2025=20=E7=AB=A0?= =?UTF-8?q?=EF=BC=9A=E7=BA=A0=E6=AD=A3=20history=20=E7=AA=97=E5=8F=A3?= =?UTF-8?q?=E8=AF=AF=E5=88=A4=EF=BC=8C=E8=A1=A5=E9=BD=90=E7=A7=81=E8=81=8A?= =?UTF-8?q?=20record=20=E4=B8=8E=E8=BD=AC=E5=8F=91=E8=8A=82=E7=82=B9?= =?UTF-8?q?=E5=BD=A2=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 推翻本轮前一结论: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 的重复投递/乱序/断线补推仍未采到。 --- docs/capability-baseline.json | 84 +++++++--- docs/decision-baseline.md | 93 +++++++++++ docs/sampling-findings-19-25.md | 23 +++ tools/probe/fwd-media-node-probe.mjs | 137 +++++++++++++++++ tools/probe/history-page-alias-probe.mjs | 115 ++++++++++++++ tools/probe/history-window-probe.mjs | 150 ++++++++++++++++++ tools/probe/history-window-recheck.mjs | 133 ++++++++++++++++ tools/probe/private-record-fwd-media.mjs | 188 +++++++++++++++++++++++ tools/probe/seg-census.mjs | 107 +++++++++++++ 9 files changed, 1006 insertions(+), 24 deletions(-) create mode 100644 docs/sampling-findings-19-25.md create mode 100644 tools/probe/fwd-media-node-probe.mjs create mode 100644 tools/probe/history-page-alias-probe.mjs create mode 100644 tools/probe/history-window-probe.mjs create mode 100644 tools/probe/history-window-recheck.mjs create mode 100644 tools/probe/private-record-fwd-media.mjs create mode 100644 tools/probe/seg-census.mjs diff --git a/docs/capability-baseline.json b/docs/capability-baseline.json index b18c805..2299471 100644 --- a/docs/capability-baseline.json +++ b/docs/capability-baseline.json @@ -21,21 +21,27 @@ "selfQq": 3575608514 }, "evidenceRule": "三证据 = API retcode + 入站事件段 + get_group_msg_history/get_friend_msg_history 回读段。retcode=0 单独不构成成功结论。", - "probes": { - "matrix": "tools/probe/matrix-probe.mjs", - "segments": "tools/probe/seg-probe.mjs", - "record": "tools/probe/record-probe.mjs", - "recordAmr": "tools/probe/record-amr-probe.mjs", - "recordDecoder": "tools/probe/record-decoder-probe.mjs", - "forwardFollowup": "tools/probe/fwd-record-followup.mjs", - "urlMedia": "tools/probe/url-media-probe.mjs", - "historyAudit": "tools/probe/history-audit.mjs", - "historyDump": "tools/probe/history-dump.mjs", - "privateHistoryAudit": "tools/probe/private-history-audit.mjs", - "forwardReadback": "tools/probe/forward-readback-probe.mjs", - "noticeCapability": "tools/probe/notice-capability.mjs", - "aiRecordSideeffect": "tools/probe/ai-record-sideeffect.mjs" - } + "probes": { + "matrix": "tools/probe/matrix-probe.mjs", + "segments": "tools/probe/seg-probe.mjs", + "record": "tools/probe/record-probe.mjs", + "recordAmr": "tools/probe/record-amr-probe.mjs", + "recordDecoder": "tools/probe/record-decoder-probe.mjs", + "forwardFollowup": "tools/probe/fwd-record-followup.mjs", + "urlMedia": "tools/probe/url-media-probe.mjs", + "historyAudit": "tools/probe/history-audit.mjs", + "historyDump": "tools/probe/history-dump.mjs", + "privateHistoryAudit": "tools/probe/private-history-audit.mjs", + "forwardReadback": "tools/probe/forward-readback-probe.mjs", + "noticeCapability": "tools/probe/notice-capability.mjs", + "aiRecordSideeffect": "tools/probe/ai-record-sideeffect.mjs", + "historyWindow": "tools/probe/history-window-probe.mjs", + "historyPageAlias": "tools/probe/history-page-alias-probe.mjs", + "historyWindowRecheck": "tools/probe/history-window-recheck.mjs", + "segCensus": "tools/probe/seg-census.mjs", + "privateRecordFwdMedia": "tools/probe/private-record-fwd-media.mjs", + "fwdMediaNode": "tools/probe/fwd-media-node-probe.mjs" + } }, "enums": { "status": { @@ -131,9 +137,10 @@ { "id": "GC-012", "title": "合并转发内层节点不可还原;news 的『可解析性』是发送形态造成的假象", - "detail": "get_forward_msg 对 history 当场回读的 8 条外层 multimsg 消息(含刚发出数分钟的 seq=3115)逐条重试,含 resid/uniseq/filename/forward_id 共 19 种参数组合,全部 retcode=1200『消息已过期或者为内层消息』⇒ 最新鲜消息同样失败,排除『已过期』解释,属接口能力缺口。唯一附带内容 meta.detail.news 是否可 JSON.parse,取决于当初 node.content 传的是段数组还是 JSON 字符串:正确形态(段数组)落库后 news 全是『昵称: 纯文本』,段类型与嵌套结构不可逆丢失;只有当初误把 content 当 JSON 字符串发出去的那两条反而能 parse 出数组——那是我们误发的字面文本,不是协议还原能力。因此标准化模型禁止把 news 当作结构化节点来源,必须原样保留 json.data.data 全文与 resid/uniseq/filename/tsum,并按降级摘要处理节点内容。媒体节点在正确形态下的具体降级形态尚无样本,属待验证。", + "detail": "get_forward_msg 对本轮同一连接刚发出(seq=3124/3125)的合并转发立即调用,仍返回 retcode=1200『消息已过期或者为内层消息』;改用 forward_id/resid/uniseq 则直接回『message_id is required』⇒ 既排除『消息已过期』的时序解释,也证明这些参数根本不被接受,属接口能力缺口。唯一附带内容 meta.detail.news 的形态由当初 node.content 的传法决定,两种形态可还原性完全相反(已用同一批含 image/record/at 的节点做定点对照):content 传【段数组】时 news 是渲染后的降级摘要——image→『[图片]』、record→『[该消息类型暂不支持查看]』、at→『@昵称』,资源标识不可逆丢失;content 传【JSON.stringify(段数组)】时 news 里原样嵌入原始段数组文本,段类型/file/CDN url/甚至 base64 全部保留。注意两者不是『一个对一个错』:段数组形态渲染正确(人能看到图片/占位符)但结构在 news 中丢失,JSON 字符串形态结构可取回但 QQ 客户端会把整段 JSON 当字面文本显示(对收件人是语义损坏),因此 QLinker 发送侧仍必须用段数组形态,禁止为了『能取回结构』改用字符串形态。结论:标准化模型禁止把 news 当作可靠的结构化节点来源(他人转发的形态由上游决定、本地不可控),必须原样保留 json.data.data 全文与 resid/uniseq/filename/tsum,并把『[图片]』『[该消息类型暂不支持查看]』识别为上游降级占位串而非用户正文。", "severity": "high", - "evidence": ["local/forward-readback-2026-10-29T08-13-22-610Z.jsonl", "local/forward-readback-2026-10-29T08-00-43-746Z.jsonl"] + "sizeRisk": "content 传 JSON 字符串时 base64 会被整段写入 news,单条外层消息体积可膨胀数 KB 以上。落库与日志必须按不可信大负载处理(大小上限、脱敏、不无条件写日志),对应 AGENTS 5.2/7.3/16.1。", + "evidence": ["local/forward-readback-2026-10-29T08-13-22-610Z.jsonl", "local/forward-readback-2026-10-29T08-00-43-746Z.jsonl", "local/fwd-media-node-2026-10-29T09-44-17-649Z.jsonl"] }, { "id": "GC-013", @@ -147,6 +154,31 @@ "detail": "实测本机 Windows 防火墙三个 profile 全部启用,node.exe 的规则按 profile 行为相反:公用=阻止 TCP/UDP 入站,专用=允许。而本机以太网(192.168.200.3)与 WLAN(192.168.43.173) 的 NetworkCategory 实测均为 Public,唯一 Private 网络是 Tailscale(该地址已实测 NapCat 侧不可达)。⇒ 任何『NapCat 主动连 QLinker』的链路(HTTP 回调、反向 WS)在解决此规则前必然收不到连接,且失败表现为『零连接尝试』,与路由不可达的现象完全相同,极易误判为拓扑问题。排查顺序:先 netsh advfirewall 查本机规则(零凭据零副作用),再做路由预检,最后才动配置。修改本机防火墙规则属改变本机安全配置,需单独授权。", "severity": "high", "evidence": ["docs/decision-baseline.md#24"] + }, + { + "id": "GC-015", + "title": "history 只能读回 NapCat 本地的一段滑动窗口且【不可翻页】,事件流实时落库是唯一完整来源", + "detail": "实测 count 语义为『返回该会话最近的 min(count, 可读总量) 条』:群 count=10/20/30 精确返回 10/20/30,私聊 count=5/10/13/14 精确返回 5/10/13/14,超过可读总量后不再增长(群 50 条 seq=3076..3125、私聊 14 条 seq=1231..1244),不传 count 时默认 20 条,messages 为升序数组。⚠️ 前一轮『私聊硬上限 10 条 / 群 46 条』的结论错误并已作废:当时把『可读总量恰好等于返回条数』误判为接口上限,补发消息后私聊条数即由 10 增至 14,直接证伪,故单次返回条数上限本轮未测到。翻页方面,start_id/end_id/message_id/msg_id 在窗口边界与窗口中部两种取值下均返回同一页,12 个候选参数名(start_id,end_id,message_id,msg_id,start_seq,end_seq,seq,offset,page,index,from_seq,to_seq)穷举全部无效,连续翻页推进 0 页 ⇒ 禁止把 history 设计成可分页补拉的数据源。设计后果:可读起点随窗口滑动,QLinker 必须依靠事件流实时落库作为唯一完整消息来源,history 仅作有限窗口的兜底核对;对 count 设上限的理由是『防止单次响应过大』而非『接口只给这么多』。", + "severity": "high", + "evidence": [ + "local/history-recheck-2026-10-29T09-47-33-494Z.jsonl", + "local/history-page-alias-2026-10-29T09-39-22-278Z.jsonl", + "docs/decision-baseline.md#25" + ] + }, + { + "id": "GC-016", + "title": "node 段不得与其他段混发,后端以 retcode=1400 拒绝,QLinker 发送侧必须前置校验", + "detail": "send_group_msg 的 message 同时含 node 段与 text 段时,上游返回 retcode=1400『转发消息不能和普通消息混在一起发送,转发需要保证message只有type为node的元素』;同一探针中纯 node 的 fwd_media_flat 返回 retcode=0(seq=3122)。⇒ 统一发送服务(第 8.1 参数校验)应在检测到 node 段时要求 message 全部为 node,并在前端给出明确错误,而不是把上游错误原样抛给用户。", + "severity": "medium", + "evidence": ["local/pr-fwd-2026-10-29T09-40-59-566Z.jsonl", "docs/decision-baseline.md#25"] + }, + { + "id": "GC-017", + "title": "news 中的『[图片]』『[该消息类型暂不支持查看]』等是上游渲染占位串,禁止当作用户正文入库", + "detail": "合并转发 meta.detail.news[].text 是上游渲染后的降级摘要,实测占位串包括『[图片]』『[该消息类型暂不支持查看]』,at 段被渲染为『@昵称』。这些字符串不是用户输入、也不携带任何资源标识,若直接入库会污染标准化消息与后续规则匹配(第 9 章规则输入必须来自可信字段)。解析层需将其识别为降级占位并标记原段类型未知,同时保留 json.data.data 原文供上游能力修复后重放。", + "severity": "medium", + "evidence": ["local/fwd-media-node-2026-10-29T09-44-17-649Z.jsonl", "docs/decision-baseline.md#25"] } ], "capabilities": [ @@ -261,12 +293,12 @@ "name": "语音段", "kind": "message-segment", "api": ["send_group_msg", "send_private_msg"], - "supports": ["group"], + "supports": ["group", "private"], "sendStatus": "verified", "eventStatus": "verified", "historyStatus": "verified", "parseStatus": "pending", - "automationTest": "record-amr-probe --yes: amr_cdnUrl/amr_b64/amr_b64_fmt/amr_b64_fmt_amr 四次 retcode=0,事件段=record+text,history seq=3118-3121 回读 record+text;对照组 amr_localPath=1200", + "automationTest": "record-amr-probe --yes: amr_cdnUrl/amr_b64/amr_b64_fmt/amr_b64_fmt_amr 四次 retcode=0,事件段=record+text,history seq=3118-3121 回读 record+text;对照组 amr_localPath=1200。私聊独立取证:private-record-fwd-media --yes 的 p_rec_b64/p_rec_cdn 均 retcode=0,事件段=record+text,history seq=1241/1242 回读 record+text;p_rec_path=1200", "realEnvTest": "verified", "regressionProbe": { "probe": "recordAmr", "case": "amr_b64", "expect": { "retcode": 0, "eventSegs": "record+text", "historySegs": "record+text" } }, "limitations": [ @@ -274,9 +306,10 @@ "定性:不是 record 功能损坏,也不是素材非法或参数形态错误,而是本 NapCat 环境**缺 silk 解码/转码链**,只保留 AMR 直通路径。发送侧必须保证上传 AMR,或在 QLinker 侧先转码为 AMR。", "file 传 NapCat 宿主机本地绝对路径(history record 段的 path 字段原值)仍 retcode=1200 'Failed to open input'。可用途径仅两条:QQ CDN 新鲜直链、base64://<字节>。禁止依赖本地路径。", "can_send_record=yes 未区分载荷格式,与 silk 失败矛盾,再次印证 GC-002:上游自检不可采信。", - "转码/读回接口 get_record 与本能力是两回事:真实 amr 的 file/url/path × mp3/wav/silk 共 9 组全部 retcode=1200,自造 WAV 内联形式全部 'file not found'(不接受内联载荷)。故 get_record 既不能用于验证也不能用于转码,标 blocked,见 MSG-record-transcode。" + "转码/读回接口 get_record 与本能力是两回事:真实 amr 的 file/url/path × mp3/wav/silk 共 9 组全部 retcode=1200,自造 WAV 内联形式全部 'file not found'(不接受内联载荷)。故 get_record 既不能用于验证也不能用于转码,标 blocked,见 MSG-record-transcode。", + "私聊作用域已独立取证,不再依赖群结论外推:send_private_msg + record 的 base64://AMR 与新鲜 CDN 直链两种载荷均 retcode=0,事件段与 history 段均为 record+text(seq=1241/1242);宿主机本地路径形态在私聊同样 1200。可用路径与群侧完全一致。" ], - "todo": ["私聊 send_private_msg 的 amr 载荷未测,private 支持度不得提前宣称。", "确认 QLinker 侧 AMR 转码方案(发送前转码 vs 仅接受 AMR 上传)并写入功能设计。", "silk 支持需换用具备完整解码依赖的 NapCat 部署重测,属上游环境项。"] + "todo": ["确认 QLinker 侧 AMR 转码方案(发送前转码 vs 仅接受 AMR 上传)并写入功能设计。", "silk 支持需换用具备完整解码依赖的 NapCat 部署重测,属上游环境项。"] }, { "id": "MSG-record-silk", @@ -373,7 +406,9 @@ "node.data.content 必须是【消息段数组】。传 JSON 字符串会被当字面文本渲染(matrix-probe: g_forward_api 的 news 里出现被转义的 {\"type\":\"text\"...} 原文),这是典型静默语义损坏。", "forward 段的 data.nodes 容器形式无效(tsum=0);必须用并列 node 段或 send_*_forward_msg 的 messages 数组。", "落库形态是 json 段(app=com.tencent.multimsg),真实节点内容在 meta.detail.news,每项是 '昵称: 内容' 的拼接字符串,非结构化段数组。", - "send_group_msg 里 node 段与 text 段混用会 retcode=1400;纯 node 段数组才 retcode=0。" + "send_group_msg 里 node 段与 text 段混用会 retcode=1400『转发消息不能和普通消息混在一起发送』(GC-016);纯 node 段数组才 retcode=0。统一发送服务必须前置校验,不得把上游错误原样抛给用户。", + "节点内容不限于 text:image/record/at 节点在段数组形态下均可正常发出并在 QQ 端渲染(fwd-media-node-probe: fwd_media_arr retcode=0,seq=3123)。但『能发出』不等于『能读回』,读回限制见 MSG-forward-read。", + "禁止为了『news 里能取回结构』把 content 改传 JSON.stringify(段数组):该形态虽使 news 保留原始段数组文本(含 CDN url 与 base64),但 QQ 客户端会把整段 JSON 当字面文本显示,对收件人属语义损坏;且 base64 会被整段写入 news 导致单条消息体积膨胀,落库与日志须按不可信大负载处理(大小上限、脱敏、不无条件写日志)。" ], "todo": [] }, @@ -387,7 +422,7 @@ "eventStatus": "readback_gap", "historyStatus": "readback_gap", "parseStatus": "pending", - "automationTest": "forward-readback-probe 穷举 19 种参数组合 + 对 8 条外层 multimsg 消息逐条重试,全部失败;同时逐条解析 9 条外层消息的 meta.detail.news 判定可还原性", + "automationTest": "forward-readback-probe 穷举 19 种参数组合 + 对 8 条外层 multimsg 消息逐条重试,全部失败;同时逐条解析 9 条外层消息的 meta.detail.news 判定可还原性。fwd-media-node-probe 追加:对本连接刚发出的 seq=3124/3125 立即调用 get_forward_msg 仍 1200,并用同一批含 image/record/at 的节点做 content 两形态定点对照", "realEnvTest": "verified", "regressionProbe": { "probe": "forwardReadback", "case": "outer:outer_mid", "expect": { "retcode": 1200, "messageContains": "无法获取转发消息" } }, "limitations": [ @@ -396,7 +431,8 @@ "get_forward_msg 不在 docs/NapcatOpenAPI.md 的 API 清单中(清单只有 send_forward_msg / send_group_forward_msg / send_private_forward_msg),属未文档化的残缺实现。get_group_msg 直接 1404 不支持。", "⚠️ news[].text 的『可解析性』是发送形态的假象,不是还原能力:9 条外层消息中只有 seq=3101 与私聊 seq=1238 能 JSON.parse 成功,而这两条恰恰是【发送形态用错】的那两条(node.content 传 JSON 字符串,被当字面文本渲染)。能 parse 出来的是我们误发的字面串,不是协议还原的结构。", "正确发送形态(node.content 传段数组)的 5 条消息,news[].text 全是 '昵称: 纯文本'(如 '雪珂: 数组形-A'、'雪珂: 纯节点一'、'雪珂: 并列节点一'),段类型与嵌套结构在 news 里【已不可逆丢失】。⇒ 依赖 news 还原只能拿到文本摘要,必须按降级摘要对待。", - "⚠️ 未采到的边界:上述 5 条正确形态样本的节点内容全部是 text,没有『正确形态 + image/record 等非文本节点』的样本。因此媒体节点在正确形态转发的 news 里具体降级成什么形态【无实测依据】,只能确定拿不回段数组。不得宣称『转发内的媒体只是降级为文本』。", + "【已补齐,原『无实测依据』标记作废】已用正确形态(content 传段数组)+ 非文本节点定点采样:news[].text 依次为『昵称: 文本正文』『昵称: [图片]』『昵称: @昵称+正文』『昵称: [该消息类型暂不支持查看]』。即 image→『[图片]』、record→『[该消息类型暂不支持查看]』、at→『@昵称』,file_id/url 等资源标识【完全丢失】,确认不可还原(不是『只是降级为文本』这种轻描淡写,媒体内容本身在 news 中不存在)。", + "反向形态(content 传 JSON.stringify(段数组))在同一批节点上会把原始段数组文本整段写进 news,段类型/file/CDN url/base64 全部保留。这【不是】协议还原能力、也不是可用的取回路径:该形态下 QQ 客户端把整段 JSON 当字面文本显示,对收件人属语义损坏,QLinker 发送侧禁止采用。它只说明 news 是上游渲染结果的搬运,形态由发送方决定。", "get_msg 是本项唯一可用的读回接口:对群与私聊的外层转发消息均 retcode=0,返回与 history 同构的完整消息对象(含 message 段数组、real_seq、sender),可拿到 json 段原文。它读回的是外层卡片,仍读不到内层节点。", "标准化模型对转发段必须保留:json.data.data 原始 JSON 全文、app、view、desc/prompt、extra.filename、extra.tsum、meta.detail.resid、meta.detail.uniseq、meta.detail.source、meta.detail.summary、meta.detail.news 数组原文。不得只存 prompt/summary。resid/uniseq 即使当前无法用于读回也必须保留,供上游修复后重放。", "⚠️ meta.detail.resid 不是恒定存在:seq=3085/3088 两条 tsum=0 的静默失效消息,detail_keys 实测只有 news/source/summary/uniseq(无 resid)⇒ 该字段必须按可空建模;'缺 resid' 可作为静默失效的辅助判据。", diff --git a/docs/decision-baseline.md b/docs/decision-baseline.md index bcbd3bd..71b73b9 100644 --- a/docs/decision-baseline.md +++ b/docs/decision-baseline.md @@ -1450,3 +1450,96 @@ WLAN 192.168.43.173 ← 未试(同上) 3. 无论哪种,都仍需先完成第 23.3 的 proxy 路由预检(需 `NAPCAT_WEBUI_PASSWORD`),避免「防火墙放行了但路由本来就不通」的无效改动。 > 凭据现状复核:本轮 shell 环境 `NAPCAT_WS_TOKEN` / `NAPCAT_WEBUI_PASSWORD` / `NAPCAT_HTTP_BASE` / `NAPCAT_WS_URL` **全部未注入**,故第 23.3 的路由预检与任何需要连 NapCat 的动作在本轮均无法执行,已如实记为未执行。 +> +> 后续更新(同日):`NAPCAT_WS_TOKEN` 已可从 gitignored 的 OB11 配置快照恢复到环境变量并实测连通(`get_login_info` 返回 `retcode=0`)。`NAPCAT_WEBUI_PASSWORD` 仍缺,第 23.3 的 proxy 路由预检仍未执行。 + +## 25. 历史读回窗口纠正、私聊 record 补齐与合并转发节点形态(2026-10-29 第四轮采样) + +本章包含一处**对本文档既有结论的推翻**,以及三项能力补齐。 + +### 25.1 【结论纠正】history 单次返回条数不存在「私聊 10 / 群 46」的接口硬上限 + +前一轮记为「`get_friend_msg_history` 在 `count>=10` 时恒返回 10 条、`get_group_msg_history` 在 `count>=50` 时恒返回 46 条」,并据此推断存在窗口硬上限。**该结论错误,现予以作废。** + +错误原因:把「该会话当时可读消息总数恰好等于返回条数」误判为「接口上限」。发送若干条测试消息后,私聊返回条数从 10 变为 14,直接证伪。 + +复测事实(`tools/probe/history-window-recheck.mjs`,`local/history-recheck-2026-10-29T09-47-07-569Z.jsonl`): + +- 群:`count=10/20/30` 精确返回 10/20/30 条;`count=40` 返回 39、`count=50` 返回 49、`count>=100` 返回 50 条(`seq 3076..3125`)。 +- 私聊:`count=5/10/13/14` 精确返回 5/10/13/14 条;`count>=15` 返回 14 条(`seq 1231..1244`)。 +- `count` 语义确定为:**返回该会话最近的 `min(count, 该会话可读消息总数)` 条**;`count` 增大时最新一条不变、最旧一条前移;`messages` 数组为**升序**(`m[0]` 最旧)。 +- 不传 `count` 时群返回 20 条,即默认值为 20。 + +因此:**条数上限本轮未测到**(群侧 50 条是本地可读量耗尽,不是接口截断)。QLinker 侧仍必须对 `count` 设上限,但理由应是「防止单次响应过大」,而不是「接口只给这么多」。 + +### 25.2 history 不支持翻页:结论维持,且证据强度提高 + +`start_id` / `end_id` / `message_id` / `msg_id` 在**窗口边界**与**窗口中部**两种取值下均无效;12 个候选参数名(`start_id, end_id, message_id, msg_id, start_seq, end_seq, seq, offset, page, index, from_seq, to_seq`)穷举后全部返回同一窗口;连续翻页推进实验推进 0 页。 + +- 证据:`local/history-page-alias-2026-10-29T09-39-22-278Z.jsonl`、`local/history-recheck-2026-10-29T09-47-07-569Z.jsonl` +- 待排除项:不排除 NapCat 通过 HTTP 路由层丢弃了未知字段,故「OB11 标准翻页参数在本版本无效」成立,「本版本任何翻页手段均无效」仍属待验证。 + +对设计的直接影响:**补拉(backfill)不能依赖 history 翻页**。可读历史是 NapCat 本地的一段滑动窗口,QLinker 必须依靠**事件流实时落库**作为唯一完整来源,history 只能作为有限窗口的兜底核对。 + +### 25.3 私聊 record 支持度补齐:可用(不得由群结论外推,现已独立取证) + +`send_private_msg` + `record` 段,三种载荷形态(`local/private-record-fwd-2026-10-29T09-41-32-864Z.jsonl`): + +| 载荷形态 | API | 自发事件回推 | history 回读 | +| --- | --- | --- | --- | +| `file = base64://<#!AMR 字节>` | `retcode=0` | `record+text` | `seq 1241`,段 `record+text` | +| `file = <新鲜 QQ CDN 直链>` | `retcode=0` | `record+text` | `seq 1242`,段 `record+text` | +| `file = ` | `retcode=1200` `Failed to open input: Invalid data found when processing input` | 无事件 | 无 | + +定性:**私聊 record 可用**,可用路径与群侧一致(AMR base64 内联 / 新鲜 CDN 直链)。本地路径形态在私聊同样不可用,与群侧第 21 章结论一致。silk 与 `get_record` 转码路径仍失败(第 21 章),故 `MSG-record` 的完整定性仍是「AMR 直通可用、silk 解码/转码链缺失」,且现已确认**群与私聊两个作用域均适用**。 + +### 25.4 【新增关键约束】合并转发 `node.content` 的两种形态导致内部结构可还原性完全不同 + +同一批节点(文本 / image / at / record 各一),仅改变 `node.data.content` 的传法(`tools/probe/fwd-media-node-probe.mjs`,`local/fwd-media-node-2026-10-29T09-44-17-649Z.jsonl`): + +- `content = JSON.stringify(段数组)` → 外层仍是 `json` 段(`app=com.tencent.multimsg`),但 `meta.detail.news[i].text` 形如 + `雪珂: [{"type":"image","data":{"file":"....png","url":"https://multimedia.nt.qq.com.cn/download?...&rkey=..."}}]` + 即**原始段数组的 JSON 文本被原样嵌进 news**,段类型、`file`、`url`、甚至 base64 全部保留。 +- `content = 段数组`(对象形式) → `news[i].text` 是**渲染后的纯文本**: + `雪珂: FWDIMG2-文本对照` / `雪珂: [图片]` / `小王: @小王FWDAT2-带at` / `雪珂: [该消息类型暂不支持查看]` + 即 image 降级为 `[图片]`、record 降级为 `[该消息类型暂不支持查看]`、at 降级为 `@昵称`,**资源标识完全丢失,不可还原**。 + +两种形态 `retcode` 均为 0,`summary` 均为「查看4条转发消息」,各自获得独立 `resid` / `uniseq`,`forward_id` 均为 `null`,`tsum` 均为 `null`。 + +设计影响(重要): + +1. 上一轮「合并转发内部结构不可还原」的结论**需要限定作用域**:对**自发**转发,采用 JSON 字符串形态即可在 `news` 中保留完整段结构;对**他人发送**的转发,形态由上游决定、本地不可控,必须按「可能已被降级为占位文本」设计。 +2. JSON 字符串形态会把 base64 整段塞进 `news`,单条消息体积可膨胀到数 KB 以上。落库与日志必须按不可信大负载处理(大小上限、脱敏、不无条件写日志),符合第 5.2、7.3、16.1 的约束。 +3. `[该消息类型暂不支持查看]` 是 NapCat/QQ 的降级占位串,不是 QLinker 产生的错误,解析层不得把它当作用户正文入库。 + +### 25.5 `get_forward_msg` 不可用于还原:结论维持,并排除「消息过期」替代解释 + +对本轮**刚刚发出**(同一连接、`seq 3124/3125`,非陈旧消息)的转发立即调用: + +- `get_forward_msg {message_id}` → `retcode=1200`,`消息已过期或者为内层消息,无法获取转发消息`(两种 content 形态均如此)。 +- `get_forward_msg {forward_id | resid | uniseq}` → `retcode=1200`,`message_id is required`,即这些参数根本不被接受。 + +这排除了第 22 章结论可能只是「测试样本太旧」的替代解释。`get_forward_msg` 在本版本对本端发出的合并转发**确实不可用**,唯一可用读回是 `get_msg` 加外层 `json` 段的 `news`。 + +### 25.6 转发与正文混发被后端拒绝(可用于发送侧校验对齐) + +`send_group_msg` 的 `message` 同时包含 `node` 段与 `text` 段时: + +`retcode=1400`,`转发消息不能和普通消息混在一起发送,转发需要保证message只有type为node的元素` + +QLinker 统一发送服务(第 8.1)的参数校验可直接对齐这条约束:检测到 `node` 段时要求 `message` 全部为 `node`,并在前端给出明确错误而非等上游报错。 + +### 25.7 段类型普查(窗口内分布,**不构成能力否定依据**) + +`tools/probe/seg-census.mjs` → `local/seg-census-2026-10-29T09-39-09-561Z.jsonl` + +- 群窗口 46 条:`text 27, record 10, json 9, image 4, video 4, file 4, at 3, reply 3, face 2`;窗口内未出现 `poke, music, location, xml, node, forward, contact, dice, shake, miniapp, marketface`。 +- 私聊窗口 10 条:`text 8, json 2, face 1, image 1, reply 1, file 1`;窗口内未出现 `poke, music, location, at, record, video, xml, node, forward, contact, dice, shake, miniapp, marketface`。 + +纪律性说明:**「窗口内未出现」不等于「不支持」**,也不等于「事件流静默丢段」。已交叉核对的样本中,`record` / `file` 在 history 中存在(说明第 19 章事件流缺失属于事件侧问题、可回读补偿),而 `poke` / `location` / `music` 在 history 中同样不存在,仍需按第 19 章标记为待验证,不得改判。 + +### 25.8 本轮产物与未执行项 + +新增探针:`history-window-probe.mjs`、`history-page-alias-probe.mjs`、`history-window-recheck.mjs`、`seg-census.mjs`、`private-record-fwd-media.mjs`、`fwd-media-node-probe.mjs`(均默认 dry-run,写操作需 `--yes`)。 + +本轮**未执行**:`NAPCAT_WEBUI_PASSWORD` 相关的路由预检(第 23.3);HTTP 回调与反向 WS 的 NapCat 真实入站采集(用户决定跳过本机防火墙改动,`LINK-http-callback` / `LINK-reverse-ws` 保持 `untested`);`LINK-http-server` 保持 `blocked`。QQ 客户端侧的手动验证项本轮未新增,全部仍待人工。 diff --git a/docs/sampling-findings-19-25.md b/docs/sampling-findings-19-25.md new file mode 100644 index 0000000..16bae07 --- /dev/null +++ b/docs/sampling-findings-19-25.md @@ -0,0 +1,23 @@ +# 采样结论纠错索引(NapCat 能力采样) + +本文件不重复记录采样结论。全部实测结论的正式出处是 `docs/decision-baseline.md` 第 19–25 章,机器可读基线是 `docs/capability-baseline.json`(门禁:`node tools/probe/capability-check.mjs`)。 + +本文件只做一件事:登记**已被实测推翻的旧结论**,防止后续会话或后续版本把过期结论重新捡回来。 + +| 曾写下的结论 | 现状 | 推翻依据 | +| --- | --- | --- | +| 「`get_friend_msg_history` 在 `count>=10` 时恒返回 10 条、`get_group_msg_history` 在 `count>=50` 时恒返回 46 条 ⇒ 存在窗口硬上限」 | **作废**。`count` 确实生效,语义为 `min(count, 该会话可读总量)`;当时把「可读总量恰好等于返回条数」误判成接口上限。单次返回条数上限至今未测到 | `tools/probe/history-window-recheck.mjs`,第 25.1 章,GC-015 | +| 「record 段整体不可用」 | **作废**。AMR 载荷可用(base64 内联 / 新鲜 CDN 直链),失败的是 silk 与本地路径两种载荷形态。定性从「功能损坏」改为「本环境缺 silk 解码/转码链」 | 第 21 章,`MSG-record` | +| 「`get_forward_msg` 失败可能是消息已过期」 | **排除**。对本连接刚发出的 `seq=3124/3125` 立即调用仍 `1200`,属接口能力缺口 | 第 25.5 章 | +| 「合并转发内部结构一律不可还原」 | **需限定作用域**。`node.content` 传 JSON 字符串时 `news` 内保留完整段结构,传段数组时降级为占位文本。自发可控、他人转发不可控,故发送侧仍必须用段数组,读回侧仍禁止依赖 `news` | 第 25.4 章,GC-012 | +| 「HTTP 回调受阻是因为 NapCat 宿主机防火墙」 | **归因错对象**。本链路 TCP 由 NapCat 主动发起,受阻应查 NapCat→本机路由与本机防火墙入站规则;实测本机对 `node.exe` 在公用网络下阻止入站 | 第 23、24 章,GC-013、GC-014 | +| 「HTTP Server 与 HTTP 回调同为入站链路,故预期同样不可达」 | **作废**。三条入站链路的连接发起方不同,排查位置不同,不可互相外推 | GC-013 | +| 「`record` / `file` 属静默丢段」 | **改判**。二者在 history 可回读,属**事件通道缺失**,可用回读补偿;只有 `location`(以及 `poke` 的**消息段形态**)两侧均无,才是真正的静默丢弃。注意 `poke` 换用 `send_poke` 接口可用,其 history 回读仍为 `untested`,不得与消息段形态混为一谈 | 第 19 章、第 25.7 章 | +| 「`news[].text` 能被 `JSON.parse` 说明结构可还原」 | **作废**。能 parse 的那两条恰恰是发送形态用错(content 传成字符串)造成的字面文本假象 | GC-012 | + +采样纪律(历次踩坑总结,后续采样必须遵守): + +1. 「返回条数 = N」不得直接写成「上限是 N」,必须先证明 N 不随数据量增长。 +2. 「窗口内未出现某类型」不得写成「不支持」或「静默丢弃」,必须与事件通道交叉核对。 +3. 任何「接口不可用」的结论,都要用刚产生的最新鲜样本复测一次,排除时效因素。 +4. 负向结论必须给出可复跑的探针与 `local/` 证据文件,且探针默认 dry-run、写操作需 `--yes`。 diff --git a/tools/probe/fwd-media-node-probe.mjs b/tools/probe/fwd-media-node-probe.mjs new file mode 100644 index 0000000..46be061 --- /dev/null +++ b/tools/probe/fwd-media-node-probe.mjs @@ -0,0 +1,137 @@ +// 合并转发内**非文本节点**的降级形态(默认 dry-run,--yes 才发送)。 +// +// 上一版把 text 段和 node 段混在一起发,被 NapCat 拒绝: +// retcode=1400「转发消息不能和普通消息混在一起发送,转发需要保证message只有type为node的元素」 +// 这条报错本身是有价值的能力约束(已单独记录),但媒体节点的降级形态仍未采到, +// 本版严格只传 node 段。 +// +// 观察点:meta.detail.news 里 image / record / at 节点变成什么。 +// 已有结论是 news 形如「昵称: 纯文本」,但全部样本都是文本节点,媒体节点未测。 + +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 SELF = Number(process.env.PROBE_SELF || 3575608514); +const DO_WRITE = process.argv.includes('--yes'); +if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); } + +const fs = await import('node:fs'); +const path = await import('node:path'); +fs.mkdirSync('local', { recursive: true }); +const OUT = path.join('local', `fwd-media-node-${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(); +const events = []; +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') { if (o.meta_event_type === 'lifecycle') authed = true; return; } + events.push({ t: Date.now(), data: o }); +}; +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) process.exit(2); + +const api = (action, params, ms = 45000) => new Promise((resolve) => { + const echo = `fm-${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 sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const rec = (o) => { fs.appendFileSync(OUT, JSON.stringify(o) + '\n'); return o; }; + +// 取真实媒体载荷(CDN 直链含时效 rkey,现取现用) +const h = await api('get_group_msg_history', { group_id: GROUP, count: 200 }); +const allSegs = (h?.data?.messages ?? []).flatMap((m) => m.message ?? []); +const img = allSegs.find((s) => s.type === 'image'); +const rec1 = allSegs.find((s) => s.type === 'record' && String(s.data?.file ?? '').endsWith('.amr')); +let amrB64 = null; +if (rec1?.data?.url) { + try { + const r = await fetch(rec1.data.url); + const b = Buffer.from(await r.arrayBuffer()); + if (r.ok && b.length > 6 && b.subarray(0, 5).toString('latin1') === '#!AMR') amrB64 = b.toString('base64'); + say(`amr 下载 HTTP=${r.status} ${b.length}B magic=${b.subarray(0, 5).toString('hex')}`); + } catch (e) { say('amr 下载失败 ' + e.message); } +} +say(`素材: image=${img ? '有' : '无'} record(amr)=${amrB64 ? '有' : '无'}`); + +const node = (nick, content, useString) => ({ + type: 'node', + data: { type: 'node', user_id: String(SELF), nickname: nick, + content: useString ? JSON.stringify(content) : content }, +}); + +const CASES = [ + { id: 'fwd_media_str', desc: '纯 node 段(content 为 JSON 字符串),节点内含 image/record/at', + msgs: () => [ + node('雪珂', [{ type: 'text', data: { text: 'FWDIMG-文本对照' } }], true), + node('雪珂', [{ type: 'image', data: { file: img?.data?.file, url: img?.data?.url } }], true), + node('小王', [{ type: 'at', data: { qq: String(FRIEND) } }, { type: 'text', data: { text: 'FWDAT-带at' } }], true), + ...(amrB64 ? [node('雪珂', [{ type: 'record', data: { file: 'base64://' + amrB64 } }], true)] : []), + ] }, + { id: 'fwd_media_arr', desc: '纯 node 段(content 为段数组),同上', + msgs: () => [ + node('雪珂', [{ type: 'text', data: { text: 'FWDIMG2-文本对照' } }], false), + node('雪珂', [{ type: 'image', data: { file: img?.data?.file, url: img?.data?.url } }], false), + node('小王', [{ type: 'at', data: { qq: String(FRIEND) } }, { type: 'text', data: { text: 'FWDAT2-带at' } }], false), + ...(amrB64 ? [node('雪珂', [{ type: 'record', data: { file: 'base64://' + amrB64 } }], false)] : []), + ] }, +]; + +if (!DO_WRITE) { + say('DRYRUN 计划(message 只含 node 段,避免 1400):'); + for (const c of CASES) say(` ${c.id.padEnd(15)} ${c.desc}`); + process.exit(0); +} + +const rows = []; +for (const c of CASES) { + const message = c.msgs(); + const t0 = Date.now(); + const r = await api('send_group_msg', { group_id: GROUP, message }); + await sleep(7000); + const mid = Number(r?.data?.message_id); + const ev = events.find((e) => e.t >= t0 && Number(e.data.message_id) === mid); + const js = (ev?.data?.message ?? []).find((s) => s.type === 'json'); + let d = {}; + try { d = JSON.parse(js?.data?.data)?.meta?.detail ?? {}; } catch {} + const row = { + kind: 'result', 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, + app: (() => { try { return JSON.parse(js?.data?.data)?.app; } catch { return null; } })(), + tsum: d.tsum ?? null, news: d.news ?? null, summary: d.summary ?? null, + resid: d.resid ?? null, uniseq: d.uniseq ?? null, forward_id: d.forward_id ?? null, + }; + rows.push(rec(row)); + say(`\n[${c.id}] retcode=${row.retcode} ${row.message.slice(0, 90)}`); + say(` segs=${row.event_segs} seq=${row.event_seq} app=${row.app} tsum=${row.tsum}`); + if (row.news) for (const n of row.news) say(` news: ${JSON.stringify(n)}`); + if (row.summary) say(` summary: ${JSON.stringify(row.summary)}`); + if (row.resid || row.uniseq) say(` resid=${row.resid} uniseq=${row.uniseq} forward_id=${row.forward_id}`); + await sleep(1000); +} + +say('\n===== 定性 ====='); +for (const r of rows.filter((x) => x.retcode === 0 && Array.isArray(x.news))) { + const flat = r.news.map((n) => (typeof n === 'string' ? n : n?.text ?? JSON.stringify(n))); + const mediaHint = flat.some((t) => /CQ:|https?:\/\/|\.png|\.amr|file_id|\[图片\]|\[语音\]|\[动画表情\]/i.test(t)); + say(` ${r.id}: news ${flat.length} 条,${mediaHint ? '含媒体线索' : '**无任何媒体线索,image/record/at 节点被压成纯文本或整体丢弃**'}`); + for (const t of flat) say(` ${t}`); +} +const rejected = rows.filter((x) => x.retcode !== 0); +for (const r of rejected) say(` ${r.id}: retcode=${r.retcode} ${r.message.slice(0, 120)}`); +say('\n证据: ' + OUT); +try { ws.close(); } catch {} +process.exit(0); diff --git a/tools/probe/history-page-alias-probe.mjs b/tools/probe/history-page-alias-probe.mjs new file mode 100644 index 0000000..f23d5a0 --- /dev/null +++ b/tools/probe/history-page-alias-probe.mjs @@ -0,0 +1,115 @@ +// 私聊 history 分页参数**别名穷举**(纯只读)。 +// +// 上一轮实测:get_friend_msg_history 无论 count 传多大都只回 10 条,且 start_id/end_id +// (数字与字符串两种形态、边界取窗口内最旧一条)返回结果与第一页完全相同。 +// 在把「私聊历史不可翻页」写进设计之前,必须先排除另一种解释: +// NapCat 用的是另一套参数名。若存在可用别名,补拉策略完全不同。 +// +// 判据:返回窗口内出现比基线最旧 real_seq **更小**的 real_seq ⇒ 该参数生效。 +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 GROUP = Number(process.env.PROBE_GROUP || 933280401); +if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); } + +const fs = await import('node:fs'); +const path = await import('node:path'); +fs.mkdirSync('local', { recursive: true }); +const OUT = path.join('local', `history-page-alias-${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) process.exit(2); + +const api = (action, params, ms = 20000) => new Promise((resolve) => { + const echo = `ha-${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)); + +// 基线:先拿第一页,记录窗口内最旧 real_seq / message_id +const base = await api('get_friend_msg_history', { user_id: FRIEND, count: 10 }); +const m0 = base?.data?.messages ?? []; +if (!m0.length) { console.error('私聊无历史数据,无法判定'); process.exit(3); } +const oldest = m0[0]; +say(`基线: ${m0.length} 条 seq ${m0[0].real_seq}..${m0[m0.length - 1].real_seq} 最旧 mid=${oldest.message_id} seq=${oldest.real_seq}`); +rec({ kind: 'baseline', action: 'get_friend_msg_history', count: 10, returned: m0.length, oldest_seq: oldest.real_seq, oldest_mid: oldest.message_id }); + +const CANDIDATES = [ + ['start_id', oldest.message_id], + ['end_id', oldest.message_id], + ['message_id', oldest.message_id], + ['msg_id', oldest.message_id], + ['start_seq', Number(oldest.real_seq)], + ['end_seq', Number(oldest.real_seq)], + ['seq', Number(oldest.real_seq)], + ['offset', 10], + ['page', 2], + ['index', Number(oldest.real_seq)], + ['from_seq', Number(oldest.real_seq)], + ['to_seq', Number(oldest.real_seq)], +]; + +say('\n===== 私聊参数别名穷举(判据:是否翻出更旧的 real_seq)====='); +let anyWorked = false; +for (const [k, v] of CANDIDATES) { + const r = await api('get_friend_msg_history', { user_id: FRIEND, count: 10, [k]: v }); + const m = r?.data?.messages ?? []; + const oldestNew = m.length ? Number(m[0].real_seq) : NaN; + const pushedBack = m.length > 0 && oldestNew < Number(oldest.real_seq); + if (pushedBack) anyWorked = true; + rec({ + kind: 'alias', action: 'get_friend_msg_history', param: k, value: v, + retcode: r.__timeout ? 'TIMEOUT' : 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, message: String(r.message ?? ''), + }); + say(` ${k.padEnd(11)}=${String(v).padEnd(12)} -> ${String(m.length).padStart(2)} 条 seq ${m.length ? m[0].real_seq + '..' + m[m.length - 1].real_seq : '-'}${pushedBack ? ' [OK] 翻到更旧!' : ''} ${String(r.message ?? '').slice(0, 30)}`); + await sleep(250); +} +say('\n===== 群侧对照(同一批别名,群历史条数多,若某别名生效更容易看出)====='); +const gBase = await api('get_group_msg_history', { group_id: GROUP, count: 40 }); +const g0 = gBase?.data?.messages ?? []; +const gOldest = g0[0]; +say(`群基线: ${g0.length} 条 seq ${g0[0].real_seq}..${g0[g0.length - 1].real_seq} 最旧 mid=${gOldest.message_id}`); +rec({ kind: 'baseline', action: 'get_group_msg_history', returned: g0.length, oldest_seq: gOldest.real_seq, oldest_mid: gOldest.message_id }); +for (const [k] of CANDIDATES) { + const v = /seq|index|offset|page/.test(k) ? Number(gOldest.real_seq) : gOldest.message_id; + const r = await api('get_group_msg_history', { group_id: GROUP, count: 40, [k]: v }); + const m = r?.data?.messages ?? []; + const pushedBack = m.length > 0 && Number(m[0].real_seq) < Number(gOldest.real_seq); + const fewer = m.length < g0.length; + rec({ + kind: 'alias', action: 'get_group_msg_history', param: k, value: v, + retcode: r.__timeout ? 'TIMEOUT' : 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, changed_shape: !!fewer, message: String(r.message ?? ''), + }); + say(` ${k.padEnd(11)}=${String(v).padEnd(12)} -> ${String(m.length).padStart(2)} 条 seq ${m.length ? m[0].real_seq + '..' + m[m.length - 1].real_seq : '-'}${pushedBack ? ' [OK] 翻到更旧!' : (fewer ? ' [~] 条数变化,参数部分生效' : '')}`); + await sleep(250); +} + +say('\n===== 定性 ====='); +// 注意:不得在此断言「窗口固定为 N 条」。count 语义已由 history-window-recheck.mjs 测得为 +// min(count, 该会话可读总量),返回条数等于可读总量≠存在接口硬上限(第 25.1 章的纠错教训)。 +say(' 私聊: ' + (anyWorked ? '存在可用分页参数,见上表 [OK] 行' : '12 个候选参数名**全部无法翻到更旧消息** ⇒ 本版本分页参数无效(可读总量见 count 扫描,勿与接口上限混淆)')); +say(`\n证据: ${OUT}`); +try { ws.close(); } catch {} +process.exit(0); diff --git a/tools/probe/history-window-probe.mjs b/tools/probe/history-window-probe.mjs new file mode 100644 index 0000000..0626063 --- /dev/null +++ b/tools/probe/history-window-probe.mjs @@ -0,0 +1,150 @@ +// 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); diff --git a/tools/probe/history-window-recheck.mjs b/tools/probe/history-window-recheck.mjs new file mode 100644 index 0000000..eb77497 --- /dev/null +++ b/tools/probe/history-window-recheck.mjs @@ -0,0 +1,133 @@ +// history 读回窗口**结论修正**用(纯只读,零副作用)。 +// +// 上一轮结论「私聊上限 10 条且不可翻页」已被本轮实测推翻: +// 09:35 count=20 → 10 条(seq 1231..1240) +// 09:44 count=200 → 14 条(seq 1231..1244),且 count=10 → 1235..1244、count=13 → 1232..1244 +// ⇒ count 生效、取「最近 min(count, 可读总量) 条」;当时的 10 条是**该会话可读总量**,不是接口上限。 +// +// 本脚本要确定两件对 QLinker 补拉策略至关重要的事: +// 1) 可读起点(群 3076 / 私聊 1231)是「接口硬窗口」还是「NapCat 本地缓存起点」。 +// 若是缓存起点,则 history 不能用于长期补拉,QLinker 必须自身持久化每一条事件。 +// 2) 上一轮「start_id/end_id 无效」是否也是误判 —— 当时边界贴着可读起点, +// 即使参数生效也翻不出更旧消息。必须用**窗口中部**的 id 做对照实验。 +// +// 对照实验设计:群取 count=10(最新 10 条,末尾远早于可读起点), +// 再用该页最旧一条的 message_id 当边界请求下一页。 +// 若返回更旧的 seq ⇒ 分页参数有效,上一轮结论作废;若仍返回同一页 ⇒ 参数确实无效。 + +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-recheck-${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) process.exit(2); + +const api = (action, params, ms = 30000) => new Promise((resolve) => { + const echo = `rc-${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 brief = (r) => { + const m = r?.data?.messages ?? []; + return { n: m.length, first: m.length ? String(m[0].real_seq) : null, + last: m.length ? String(m[m.length - 1].real_seq) : null, firstMid: m.length ? m[0].message_id : null }; +}; + +say('\n===== 1) count 语义复核(群,窗口足够大)====='); +for (const count of [10, 20, 30, 40, 50, 100, 200]) { + const r = await api('get_group_msg_history', { group_id: GROUP, count }); + const b = brief(r); + rec({ kind: 'result', id: `group:count=${count}`, action: 'get_group_msg_history', + retcode: r.retcode, count_param: count, returned: b.n, first_seq: b.first, last_seq: b.last }); + say(` count=${String(count).padStart(3)} -> ${String(b.n).padStart(3)} 条 seq ${b.first}..${b.last}`); +} +say('\n===== 2) count 语义复核(私聊)====='); +for (const count of [5, 10, 13, 14, 15, 50, 200]) { + const r = await api('get_friend_msg_history', { user_id: FRIEND, count }); + const b = brief(r); + rec({ kind: 'result', id: `private:count=${count}`, action: 'get_friend_msg_history', + retcode: r.retcode, count_param: count, returned: b.n, first_seq: b.first, last_seq: b.last }); + say(` count=${String(count).padStart(3)} -> ${String(b.n).padStart(3)} 条 seq ${b.first}..${b.last}`); +} + +// ===== 3) 分页对照实验:边界取窗口**中部**而非贴着可读起点 ===== +say('\n===== 3) 分页对照实验(群,边界取窗口中部)====='); +const p1 = await api('get_group_msg_history', { group_id: GROUP, count: 10 }); +const b1 = brief(p1); +say(` 第 1 页: ${b1.n} 条 seq ${b1.first}..${b1.last}(最旧 mid=${b1.firstMid})`); +rec({ kind: 'baseline', action: 'get_group_msg_history', page: 1, returned: b1.n, + first_seq: b1.first, last_seq: b1.last, first_mid: b1.firstMid }); +for (const pk of ['start_id', 'end_id', 'message_id', 'msg_id']) { + const r = await api('get_group_msg_history', { group_id: GROUP, count: 10, [pk]: b1.firstMid }); + const b = brief(r); + const pushedBack = b.n > 0 && Number(b.first) < Number(b1.first); + const identical = b.first === b1.first && b.last === b1.last; + rec({ kind: 'result', id: `group:page2:${pk}`, action: 'get_group_msg_history', + retcode: r.retcode, returned: b.n, first_seq: b.first, last_seq: b.last, + pushed_back: !!pushedBack, identical_to_page1: !!identical }); + say(` ${pk.padEnd(10)}=${b1.firstMid} -> ${b.n} 条 seq ${b.first}..${b.last}${pushedBack ? ' [OK] 翻到更旧,分页参数有效' : (identical ? ' [=] 与第 1 页相同' : '')}`); + await sleep(300); +} + +// 两页连翻:若上一页参数有效,这里应能连续往回走 +say('\n===== 4) 连续翻页(用第 1 页最旧 id 往回,看能否连续推进)====='); +let cur = b1, hit = null; +for (const pk of ['start_id', 'end_id']) { + let seq = [`${cur.first}..${cur.last}`], mid = cur.firstMid, advanced = 0; + for (let i = 0; i < 4; i++) { + const r = await api('get_group_msg_history', { group_id: GROUP, count: 10, [pk]: mid }); + const b = brief(r); + if (!b.n || Number(b.first) >= Number(cur.first)) { seq.push('停止'); break; } + advanced++; cur = b; mid = b.firstMid; seq.push(`${b.first}..${b.last}`); + } + rec({ kind: 'result', id: `group:multi:${pk}`, action: 'get_group_msg_history', + advanced_pages: advanced, trace: seq.join(' | ') }); + say(` ${pk.padEnd(10)} 推进 ${advanced} 页: ${seq.join(' -> ')}`); + if (advanced > 0 && !hit) hit = pk; +} + +// ===== 5) 可读起点是否为硬窗口:用超出可读范围的旧 id 当边界 ===== +say('\n===== 5) 可读起点性质(私聊起点 1231 / 群起点见上)====='); +const pmin = await api('get_friend_msg_history', { user_id: FRIEND, count: 200 }); +const bp = brief(pmin); +say(` 私聊全窗口: ${bp.n} 条 seq ${bp.first}..${bp.last}`); +say(` → 起点固定为 ${bp.first}。若该 seq 之前确无数据(更早消息不可读),`); +say(` 则 history 只能读到 NapCat 本地保留的一段,不能作为长期补拉来源。`); +rec({ kind: 'window', action: 'get_friend_msg_history', total: bp.n, oldest_seq: bp.first, newest_seq: bp.last }); +const gmin = await api('get_group_msg_history', { group_id: GROUP, count: 200 }); +const bg = brief(gmin); +say(` 群全窗口: ${bg.n} 条 seq ${bg.first}..${bg.last}`); +rec({ kind: 'window', action: 'get_group_msg_history', total: bg.n, oldest_seq: bg.first, newest_seq: bg.last }); + +say('\n===== 定性 ====='); +say(hit + ? ` 分页参数**有效**(${hit} 可连续往回翻页)→ 上一轮「不可翻页」结论作废,需按本结果重写。` + : ' 窗口中部边界仍无法翻页 → 「history 不支持翻页」在本版本成立(但 count 生效,上限结论仍需按第 1/2 节修正)。'); +say(' count 语义:返回**最近** min(count, 该会话可读总量) 条(实测 count 增大时 newest 不变、oldest 前移)。'); +say('\n结果 -> ' + OUT); +try { ws.close(); } catch {} +process.exit(0); diff --git a/tools/probe/private-record-fwd-media.mjs b/tools/probe/private-record-fwd-media.mjs new file mode 100644 index 0000000..b73d99f --- /dev/null +++ b/tools/probe/private-record-fwd-media.mjs @@ -0,0 +1,188 @@ +// 两项待定性的定点补采(默认 dry-run,--yes 才产生发送副作用): +// +// A) 私聊 record 支持度。此前 record 的可用载荷只在**群**里验证过(send_group_msg), +// 能力目录里 MSG-record 的私聊支持度一直留空。不得由「群可用」外推「私聊可用」。 +// 三证据:API retcode + 自发事件回推段 + get_friend_msg_history 回读段。 +// +// B) 合并转发(com.tencent.multimsg)内的**非文本节点**会退化成什么。 +// 上一轮证明 news 是「昵称: 纯文本」,但用例全是文本节点,无法判断媒体节点是否 +// 连同内容一起被压成文本。补一条含 image + record + at 的转发,看 news 形态。 +// +// ⚠️ 已知约束:get_friend_msg_history 单次上限 10 条且不可翻页(本轮实测)。 +// 因此私聊发送数量必须严格控制,且回读必须在同一轮内完成,否则证据被挤出窗口即失效。 + +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 SELF = Number(process.env.PROBE_SELF || 3575608514); +const DO_WRITE = process.argv.includes('--yes'); +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 stamp = new Date().toISOString().replace(/[:.]/g, '-'); +const OUT = path.join(OUT_DIR, `pr-fwd-${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('未收到 lifecycle,中止。'); process.exit(2); } + +const api = (action, params, ms = 45000) => new Promise((resolve) => { + const echo = `pf-${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 sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const rec = (o) => { fs.appendFileSync(OUT, JSON.stringify(o) + '\n'); return o; }; + +// ---- 取真实 amr 载荷(CDN 直链含时效 rkey,必须现取现用)---- +const h = await api('get_group_msg_history', { group_id: GROUP, count: 200 }); +let amr = 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')) { amr = { seq: m.real_seq, ...s.data }; break; } +} +let amrB64 = null, dl = '-'; +if (amr?.url) { + try { + const r = await fetch(amr.url); + const buf = Buffer.from(await r.arrayBuffer()); + dl = `HTTP ${r.status} ${buf.byteLength}B magic=${buf.subarray(0, 4).toString('hex')}`; + if (r.ok && buf.byteLength) amrB64 = buf.toString('base64'); + } catch (e) { dl = 'ERR ' + e.message; } +} +say(amr ? `取到群内 amr 段 seq=${amr.seq} 下载=${dl}` : '未取到 amr 段,私聊 record 用例将跳过'); + +// ---- A) 私聊 record ---- +const P_CASES = []; +if (amrB64) P_CASES.push({ id: 'p_rec_b64', desc: '私聊 record file=base64://amr', + data: () => ({ file: 'base64://' + amrB64 }) }); +if (amr?.url) P_CASES.push({ id: 'p_rec_cdn', desc: '私聊 record file=CDN 直链', + data: () => ({ file: amr.url }) }); +if (amr?.path) P_CASES.push({ id: 'p_rec_path', desc: '私聊 record file=宿主机本地路径', + data: () => ({ file: amr.path }) }); + +say(`\n===== A) 私聊 record(模式=${DO_WRITE ? '真实发送' : 'DRY-RUN'})=====`); +const pRows = []; +for (const c of P_CASES) { + if (!DO_WRITE) { say(` ${c.id.padEnd(12)} [计划] ${c.desc}`); continue; } + const t0 = Date.now(); + const r = await api('send_private_msg', { user_id: FRIEND, message: [ + { type: 'record', data: c.data() }, { type: 'text', data: { text: `[QLpr:${c.id}]` } }] }); + await sleep(6000); + const mid = Number(r?.data?.message_id); + const ev = events.find((e) => e.el >= t0 && Number(e.data.message_id) === mid); + const row = { kind: 'result', id: c.id, scope: 'private', action: 'send_private_msg', + 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_post_type: ev?.data?.post_type ?? null, event_seq: ev?.data?.real_seq ?? null }; + pRows.push(rec(row)); + say(` ${c.id.padEnd(12)} retcode=${String(row.retcode).padEnd(6)} 事件=${String(row.event_segs).padEnd(12)} ${row.message.slice(0, 50)}`); +} + +// ---- B) 合并转发含媒体节点 ---- +say('\n===== B) 合并转发内媒体节点的降级形态 ====='); +const imgSeg = (h?.data?.messages ?? []).flatMap((m) => m.message ?? []).find((s) => s.type === 'image'); +const vidSeg = (h?.data?.messages ?? []).flatMap((m) => m.message ?? []).find((s) => s.type === 'video'); +const node = (nickname, content) => ({ type: 'node', data: { type: 'node', user_id: String(SELF), nickname, content } }); +const fwdContent = [ + { type: 'text', data: { text: 'QLfwdMedia-文本' } }, + imgSeg ? { type: 'image', data: { file: imgSeg.data.file, url: imgSeg.data.url } } : null, + amrB64 ? { type: 'record', data: { file: 'base64://' + amrB64 } } : null, + { type: 'at', data: { qq: String(FRIEND) } }, +].filter(Boolean); + +const F_CASES = [ + { id: 'fwd_media_nodes', desc: '并列 node 段,节点内含 image/record/at', params: () => ({ + group_id: GROUP, message: [ + node('雪珂', fwdContent), + { type: 'text', data: { text: '[QLf:fwd_media_nodes]' } }] }) }, + { id: 'fwd_media_flat', desc: '直接把 image/record/at 并列在外层(非 node 包裹)', params: () => ({ + group_id: GROUP, message: [...fwdContent, { type: 'text', data: { text: '[QLf:fwd_media_flat]' } }] }) }, +]; +const fRows = []; +for (const c of F_CASES) { + if (!DO_WRITE) { say(` ${c.id.padEnd(17)} [计划] ${c.desc}`); continue; } + const t0 = Date.now(); + const r = await api('send_group_msg', c.params()); + await sleep(6000); + const mid = Number(r?.data?.message_id); + const ev = events.find((e) => e.el >= t0 && Number(e.data.message_id) === mid); + const js = (ev?.data?.message ?? []).find((s) => s.type === 'json'); + let detail = {}; + try { detail = JSON.parse(js?.data?.data)?.meta?.detail ?? {}; } catch {} + const row = { kind: 'result', id: c.id, scope: 'group', action: 'send_group_msg', 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, tsum: detail.tsum ?? null, + news: JSON.stringify(detail.news ?? ''), resid: detail.resid ?? null, uniseq: detail.uniseq ?? null }; + fRows.push(rec(row)); + say(` ${c.id.padEnd(17)} retcode=${String(row.retcode).padEnd(6)} seq=${row.event_seq ?? '-'} tsum=${row.tsum ?? '-'} news=${row.news.slice(0, 200)}`); +} + +// ---- 三证据回读(必须在同轮完成:私聊窗口仅 10 条)---- +if (DO_WRITE && (pRows.length || fRows.length)) { + await sleep(3000); + say('\n===== 第三证据:history 回读 ====='); + const ph = await api('get_friend_msg_history', { user_id: FRIEND, count: 200 }); + const pmsgs = ph?.data?.messages ?? []; + say(` 私聊窗口 ${pmsgs.length} 条 seq ${pmsgs.length ? pmsgs[0].real_seq + '..' + pmsgs[pmsgs.length - 1].real_seq : '-'}`); + const seen = new Set(); + for (const m of pmsgs) { + const txt = (m.message ?? []).map((s) => s.data?.text ?? '').join(''); + const mm = txt.match(/\[QLpr:([A-Za-z0-9_]+)\]/); + if (!mm || seen.has(mm[1])) continue; + seen.add(mm[1]); + const segs = (m.message ?? []).map((s) => s.type).join('+'); + rec({ kind: 'history', id: mm[1], history_segs: segs, history_seq: String(m.real_seq) }); + const row = pRows.find((x) => x.id === mm[1]); if (row) row.history_segs = segs; + say(` ${mm[1].padEnd(12)} seq=${m.real_seq} 段=${segs}`); + } + for (const r of pRows) if (r.retcode === 0 && !r.history_segs) say(` [!] ${r.id} retcode=0 但未回读到,可能已挤出 10 条窗口`); + + const gh = await api('get_group_msg_history', { group_id: GROUP, count: 200 }); + const gseen = new Set(); + for (const m of gh?.data?.messages ?? []) { + const txt = (m.message ?? []).map((s) => s.data?.text ?? '').join(''); + const mm = txt.match(/\[QLf:([A-Za-z0-9_]+)\]/); + if (!mm || gseen.has(mm[1])) continue; + gseen.add(mm[1]); + const segs = (m.message ?? []).map((s) => s.type).join('+'); + rec({ kind: 'history', id: mm[1], history_segs: segs, history_seq: String(m.real_seq) }); + const row = fRows.find((x) => x.id === mm[1]); if (row) row.history_segs = segs; + say(` ${mm[1].padEnd(17)} seq=${m.real_seq} 段=${segs}`); + } +} + +say('\n===== 定性 ====='); +const pOk = pRows.filter((r) => r.retcode === 0 && String(r.history_segs ?? r.event_segs).includes('record')); +say(' 私聊 record: ' + (pOk.length ? `可用(${pOk.map((r) => r.id).join(', ')}),MSG-record 的私聊支持度可写「可用」` + : (pRows.length ? '全部失败,MSG-record 私聊应标「群可用、私聊不可用」,不得写「record 可用」' : 'DRY-RUN 未实发,不下结论'))); +const fOk = fRows.filter((r) => r.retcode === 0 && r.news); +for (const r of fOk) { + const newsHasMedia = /图片|视频|语音|\[CQ:|image|record|video/.test(r.news); + say(` ${r.id}: news ${newsHasMedia ? '含媒体标记,媒体节点未完全丢失' : '为纯文本,媒体节点被压成文本或丢弃'} → ${r.news.slice(0, 220)}`); +} +say('\n结果 -> ' + OUT); +try { ws.close(); } catch {} +process.exit(0); diff --git a/tools/probe/seg-census.mjs b/tools/probe/seg-census.mjs new file mode 100644 index 0000000..adca9b2 --- /dev/null +++ b/tools/probe/seg-census.mjs @@ -0,0 +1,107 @@ +// 段类型普查(纯只读):把群/私聊 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);