/** 双渠道诊断通信:先落盘意图;send 仅一次,恢复默认只读。 */ import fs from 'node:fs'; import path from 'node:path'; import { createHash, randomUUID } from 'node:crypto'; import { createRequire } from 'node:module'; import { fileURLToPath } from 'node:url'; import { beijingTime, recordProgress as recordProjectProgress } from './lib/project-recovery.mjs'; import { atomicDiagnosticWrite, withDiagnosticLock } from './lib/dual-channel-diagnostic-state.mjs'; const sha = s => createHash('sha256').update(s).digest('hex'); const prompt = `【双渠道只读取证 dual-channel-20261201】 用户授权:请向主容器询问企微新容器开通规范与当前 App/Matrix 新容器开通规范,分析为什么目前只能二选一,形成双渠道都可用的最优方案。 本次只分析定位:禁止创建/启动/停止/重建/重启容器,禁止修改配置、插件、云函数、凭据、数据库;不要自行给企微或业务 App 发送测试消息;不要提交、推送、部署。只回复本房间。不要展示密钥完整值。 请基于当前真实读取结果回答,无法访问就明确写出,不要依据历史记忆宣称已核实。 1. 读取你当前企微开通 SOP(life-init-standard / life-ops-hardened 等)及 App/Matrix 开通 SOP、实际执行脚本/默认模板。列出镜像版本/镜像摘要、Hermes 版本或源码 commit、技能/脚本路径;官方上游仓库地址也请提供。 2. 只读查看一个实际同时配置企微和 Matrix 的现有容器(优先 agent-node-u19170119836,先核对身份,AGENT_ID 和物理名可能不同)及一个 App 新开通容器。分别给出渠道 enabled、进程/连接状态、配置来源优先级(config.yaml/.env/docker env/s6 env)、插件清单、hooks 名称和顺序。标明当前时间及证据原始行,凭据只报哈希/存在性。 3. 对照官方安装版本源码,说明是否同一 gateway 能同时注册 wecom 和 matrix,按 source.platform/chat_id/thread_id 如何隔离 session/adapter。是否存在渠道二选一、session key 冲突、全局输出钩子污染、适配器 monkey patch、共享环境变量或全局线程状态。 4. 企微通道实际使用什么官方组件(智能机器人长连接/自建应用等)、实际 send_text/send_file/send_image 链路及格式、文件大小/异步主动发送限制,结论必须区分安装源码与官方文档,不能猜数字。Matrix 则核对 m.room.message 的 m.text/m.file/m.image,url=https S3,info,m.relates_to=m.thread,✅/❌ reaction 的实际实现。 5. 本地源码发现:旧 scripts/onboard-user.mjs 克隆模板时删除 platforms.wecom(目的是避免共享 bot 凭据);新 cloud/onboarding/install.py 的 merge_config 是增量保留平台;全局 transform_llm_output 指向 fmode-deliverable-hook.py。请比对当前宿主模板与实际容器:有没有把所有渠道 MEDIA 行统一剥除/改成 S3 URL、上报后重复上传或按文件名复用旧链接、从 config 覆盖整个 platforms、botid 多实例抢连接。每点给文件路径/函数/少量原始行。 6. 请提出最小改动建议:同一容器保持两个官方 adapter,公共产物上传 S3 一次;Matrix 用 HTTPS 附件事件+thread+结束 reaction;企微按自身 adapter 原生发送规范消费同一产物;入站来源决定回原渠道,默认不双发、不跨渠道泄露对话。说明是否真的需要两个进程,避免未经证据就拆容器。 7. 给出可隔离验证的测试矩阵(企微单独、Matrix单独、双开交错、同名文件/并发/失败/重启持久化),本轮只给计划,不执行真实消息测试。 请分清【本次实读证据】【代码推断】【尚未验证】,不要以过去的成功当作本次结果。若无法访问宿主,只读检查本机并说清边界。回复尽量聚焦,先结论后证据。`; export async function runDiagnostic(options = {}) { const root = options.root || path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const dir = path.join(root, 'test-results/dual-channel-20261201'); const stateFile = path.join(dir, 'state.json'); const taskFile = path.join(root, 'docs/00-tracking/active-task.json'); const command = options.command || 'read'; const write = atomicDiagnosticWrite; const recordProgress = options.recordProgress || recordProjectProgress; const print = options.print || console.log; return withDiagnosticLock(dir, async () => { try { if (command === 'init') { if (fs.existsSync(stateFile)) throw Error('账本已存在;请 read,禁止覆盖或重发'); fs.mkdirSync(dir, { recursive: true }); fs.mkdirSync(path.join(root, '.local-backup/dual-channel-20261201'), { recursive: true }); const previous = JSON.parse(fs.readFileSync(taskFile, 'utf8')); write(path.join(dir, 'active-task.before.json'), previous); write(path.join(dir, 'checkpoint.before.md'), fs.readFileSync(path.join(root, 'docs/00-tracking/接续检查点.md'), 'utf8')); write(path.join(dir, 'master-question.md'), prompt); write(stateFile, { version: 1, run: 'dual-channel-20261201', startedAt: beijingTime(), actions: {}, checks: [], acceptance: [ { name: '本地开通与输出链路取证', status: 'in_progress' }, { name: '主容器只读问询与回读', status: 'pending' }, { name: '双渠道方案与测试计划', status: 'pending' }, { name: '双渠道真实业务验收', status: 'not_run_plan_only' } ], recovery: { currentStep: '只读梳理企微与Matrix开通配置和输出钩子', nextSteps: ['主容器只读取证', '本地隔离复现', '形成方案与验收计划'] } }); const task = { ...previous, goal: '企微与Matrix双渠道并存问题:只读取证、主容器交互分析与优化测试方案', ledger: 'test-results/dual-channel-20261201/state.json', privateDirectory: '.local-backup/dual-channel-20261201', report: 'docs/02-design/plans/2026-12-01-企微与Matrix双渠道并存诊断方案.md', previousTask: previous }; task.localWorkstreams = [...(previous.localWorkstreams || []), { id: 'dual-channel-20261201', goal: task.goal, status: 'investigating', ledger: task.ledger, report: task.report }]; write(taskFile, task); recordProgress(root, '用户当前授权启动企微/Matrix双渠道诊断(/plan),既有工作流保留在active-task.previousTask与本轮active-task.before.json;已读检查点/CLAUDE/工作树/相关diff并运行project:resume。Docker命令不可用、原业务账本缺失,未重放任何旧动作。证据test-results/dual-channel-20261201;主容器问询目标与原文已落盘master-question.md,尚未发送。不修改业务源码或线上配置。'); print('本轮账本、问询目标及当前任务已落盘;未发送。'); } else { if (!fs.existsSync(stateFile)) throw Error('先显式 init 建立诊断账本'); const state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); const master = options.client || createRequire(import.meta.url)('./master-channel.cjs'); const request = master.request || (async (suffix, init = {}) => { const res = await fetch(master.MX + '/_matrix/client/v3' + suffix, { ...init, signal: AbortSignal.timeout(25000), headers: { Authorization: 'Bearer ' + master.USER_ACCESS_TOKEN, 'Content-Type': 'application/json' } }); const data = await res.json(); if (!res.ok) throw Object.assign(Error('Matrix HTTP ' + res.status + ' ' + (data.errcode || '')), { httpStatus: res.status, errcode: data.errcode }); return data; }); if (command === 'send') { if (state.actions.send?.attempted || state.actions.room?.attempted) throw Error('已有动作意图或回执;只读 read 核实,禁止盲重发'); const me = await request('/account/whoami'); if (me.user_id !== master.USER_MXID) throw Error('通信账号身份与配置不一致'); state.actions.room = { attempted: true, attemptedAt: beijingTime(), target: { name: 'dual-channel-20261201-readonly', invite: master.MASTER_MXID }, mode: 'diagnostic_room_only' }; write(stateFile, state); recordProgress(root, '准备向主容器@bnqaoxqhe8:fmode.cn发送一次只读双渠道问询;通信账号whoami已匹配。仅创建诊断房间并发master-question.md,不创建业务容器、不修改线上配置。房间创建目标已先落盘state.actions.room;中断先只读查房间及事件,不盲重试。'); const room = await request('/createRoom', { method: 'POST', body: JSON.stringify({ ...state.actions.room.target, invite: [master.MASTER_MXID], preset: 'private_chat', is_direct: true }) }); if (!room.room_id) throw Error('房间响应无room_id;保留未知态,先只读核实'); state.actions.room.roomId = room.room_id; state.actions.room.confirmedAt = beijingTime(); write(stateFile, state); const content = fs.readFileSync(path.join(dir, 'master-question.md'), 'utf8'); state.actions.send = { attempted: true, attemptedAt: beijingTime(), target: master.MASTER_MXID, roomId: room.room_id, txnId: 'dual-channel-20261201-' + sha(content).slice(0, 24), promptSha256: sha(content), since: Date.now() }; write(stateFile, state); const receipt = await request('/rooms/' + encodeURIComponent(room.room_id) + '/send/m.room.message/' + state.actions.send.txnId, { method: 'PUT', body: JSON.stringify({ msgtype: 'm.text', body: content, 'm.mentions': { user_ids: [master.MASTER_MXID] } }) }); if (!receipt.event_id) throw Error('发送响应无event_id;保留未知态,先只读核实'); state.actions.send.eventId = receipt.event_id; state.actions.send.confirmedAt = beijingTime(); write(path.join(dir, 'send-receipt.json'), { roomId: room.room_id, ...receipt, at: beijingTime(), promptSha256: sha(content) }); write(stateFile, state); recordProgress(root, '已向主容器发送一次只读诊断问询,Matrix事件回执已落盘test-results/dual-channel-20261201/send-receipt.json。尚未收到回复,后续只读read查结果;未执行真实双渠道消息测试。'); print(JSON.stringify({ sent: true, roomId: room.room_id, eventId: receipt.event_id })); } else if (command === 'followup') { if (state.actions.followup?.attempted) throw Error('补充问询已有意图;只读查回执,禁止重发'); const roomId = state.actions.room?.roomId; if (!roomId) throw Error('无原诊断房间,不创建新房间'); const content = `补充本地实际代码/离线证据(同一只读诊断,不执行改动): 1. 我已读到App当前src/app/core/matrix-client.service.ts::sendFileByUrl实际发送m.text,body=文件名+S3链接,附com.fmode.file_card/com.fmode.cloud_url及m.thread;早期m.file说明仍残留注释。请据此更正前一问的假设:Matrix推荐继续统一m.text+S3+卡片,不倒退成m.file HTTPS私有补丁。 2. 本地离线已复现:plugin-deliverable-inject对matrix和wecom都删除不在本轮pushed的普通参考URL(无成果时也删);远程MEDIA URL被删,本地MEDIA路径仍保留。不是所有MEDIA都被剥掉。 3. plugin-matrix-outbound-s3::_preuploaded_lookup只按basename+size从全部session台账取最新URL;session-a/report.pdf会拿到session-b同名同大小的URL。plugin-media-text-merge::_PENDING仅按chat_id,Matrix同房间不同thread会合并;没有platform隔离。 4. App新上报快照_fmode_channel_snapshot目前只返回matrix/matrixConfig,并整段提交channels,企微字段可能被覆盖(尚待服务端merge语义实读,不将推断当事实)。 请优先核对这些点在你实际现网模板/容器里是否相同,并补充:你自身此刻wecom与matrix是否在同一个gateway进程都connected?如宿主不可达不要持续试探,明确证据边界,给出本机源码路径/关键行与诊断结论即可。`; write(path.join(dir, 'master-followup.md'), content); state.actions.followup = { attempted: true, attemptedAt: beijingTime(), roomId, target: master.MASTER_MXID, txnId: 'dual-channel-followup-' + sha(content).slice(0, 24), promptSha256: sha(content) }; write(stateFile, state); recordProgress(root, '已先落盘同房间补充问询目标master-followup.md与state.actions.followup:纠正Matrix当前采用m.text+S3卡片的前提,提交本地离线复现证据,请主容器核对本机双渠道状态;只问询,不授权改动或真实业务消息测试。'); const receipt = await request('/rooms/' + encodeURIComponent(roomId) + '/send/m.room.message/' + state.actions.followup.txnId, { method: 'PUT', body: JSON.stringify({ msgtype: 'm.text', body: content, 'm.mentions': { user_ids: [master.MASTER_MXID] } }) }); if (!receipt.event_id) throw Error('补充发送回执不明,先只读核实'); state.actions.followup.eventId = receipt.event_id; state.actions.followup.confirmedAt = beijingTime(); write(stateFile, state); write(path.join(dir, 'followup-receipt.json'), { ...receipt, roomId, at: beijingTime() }); recordProgress(root, '主容器同房间补充诊断问询已取得事件回执,证据test-results/dual-channel-20261201/followup-receipt.json;等待回读,不重复发送。'); print(JSON.stringify({ sentFollowup: true, eventId: receipt.event_id })); } else if (command === 'read') { const roomId = state.actions.room?.roomId; if (!roomId) { print(JSON.stringify({ actions: state.actions, note: '无已确认房间;不创建或重试' })); return; } const members = await request('/rooms/' + encodeURIComponent(roomId) + '/joined_members'); const events = []; let from = ''; let startEventFound = false; let historyEnded = false; let pages = 0; for (let page = 0; page < 6; page++) { const data = await request('/rooms/' + encodeURIComponent(roomId) + '/messages?dir=b&limit=100' + (from ? '&from=' + encodeURIComponent(from) : '')); pages++; events.push(...(data.chunk || [])); startEventFound = events.some(e => e.event_id === state.actions.send?.eventId); historyEnded = !data.end || data.end === from || !(data.chunk || []).length; if (startEventFound || historyEnded) break; from = data.end; } const coverage = { complete: startEventFound, truncated: !startEventFound && !historyEnded, startEventFound, historyEnded, nextToken: !startEventFound && !historyEnded ? from : null, pages }; const observedAt = beijingTime(); const snapshot = { observedAt, roomId, masterJoined: !!members.joined?.[master.MASTER_MXID], coverage, events }; const observations = path.join(dir, 'observations'); fs.mkdirSync(observations, { recursive: true }); write(path.join(observations, new Date().toISOString().replace(/[:.]/g, '-') + '-' + randomUUID() + '.json'), snapshot); const previousEvidence = path.join(dir, 'master-events.json'); const retained = fs.existsSync(previousEvidence) ? JSON.parse(fs.readFileSync(previousEvidence, 'utf8')).events || [] : []; const combined = new Map(retained.filter(e => e.event_id).map(e => [e.event_id, e])); for (const event of events) if (event.event_id) combined.set(event.event_id, event); const allEvents = [...combined.values()].sort((a,b) => a.origin_server_ts - b.origin_server_ts); const replies = allEvents.filter(e => e.sender === master.MASTER_MXID && e.origin_server_ts >= (state.actions.send?.since || 0)); write(previousEvidence, { ...snapshot, events: allEvents, evidenceMode: 'accumulated_by_event_id' }); const texts = replies.filter(e => e.type === 'm.room.message').map(e => ({ eventId: e.event_id, at: e.origin_server_ts, body: e.content?.body || '' })); write(path.join(dir, 'master-replies.md'), texts.map(e => '事件:' + e.eventId + '\n\n' + e.body).join('\n\n---\n\n')); const previousIds = new Set(state.replyEventIds || []); const freshTexts = texts.filter(x => !previousIds.has(x.eventId)); state.observedAt = beijingTime(); state.masterJoined = !!members.joined?.[master.MASTER_MXID]; state.replyEventIds = texts.map(x => x.eventId); state.lastReadCoverage = coverage; const targets = new Set([state.actions.send?.eventId, state.actions.followup?.eventId].filter(Boolean)); state.completionReactions = replies.filter(e => e.type === 'm.reaction' && targets.has(e.content?.['m.relates_to']?.event_id) && ['✅', '❌'].includes(e.content?.['m.relates_to']?.key)).map(e => ({ eventId: e.event_id, targetEventId: e.content['m.relates_to'].event_id, key: e.content['m.relates_to'].key, at: e.origin_server_ts })); write(stateFile, state); print(JSON.stringify({ masterJoined: state.masterJoined, messages: texts.length, coverage, completionReactions: state.completionReactions, newReplies: freshTexts.map(x => ({ ...x, body: x.body.slice(-18000) })) })); } else throw Error('用法:node scripts/diagnose-dual-channels.mjs [init|send|followup|read]'); } } catch (error) { if (fs.existsSync(stateFile)) { const latest = JSON.parse(fs.readFileSync(stateFile, 'utf8')); latest.failures = [...(latest.failures || []), { stage: 'diagnostic_' + command, at: beijingTime(), error: String(error.message), httpStatus: error.httpStatus, status: command === 'read' ? 'observation_failed_previous_evidence_retained' : 'stopped_verify_before_retry' }]; write(stateFile, latest); } throw error; } }); } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { await runDiagnostic({ command: process.argv[2] || 'read' }); }