diagnose-dual-channels.mjs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. /** 双渠道诊断通信:先落盘意图;send 仅一次,恢复默认只读。 */
  2. import fs from 'node:fs';
  3. import path from 'node:path';
  4. import { createHash, randomUUID } from 'node:crypto';
  5. import { createRequire } from 'node:module';
  6. import { fileURLToPath } from 'node:url';
  7. import { beijingTime, recordProgress as recordProjectProgress } from './lib/project-recovery.mjs';
  8. import { atomicDiagnosticWrite, withDiagnosticLock } from './lib/dual-channel-diagnostic-state.mjs';
  9. const sha = s => createHash('sha256').update(s).digest('hex');
  10. const prompt = `【双渠道只读取证 dual-channel-20261201】
  11. 用户授权:请向主容器询问企微新容器开通规范与当前 App/Matrix 新容器开通规范,分析为什么目前只能二选一,形成双渠道都可用的最优方案。
  12. 本次只分析定位:禁止创建/启动/停止/重建/重启容器,禁止修改配置、插件、云函数、凭据、数据库;不要自行给企微或业务 App 发送测试消息;不要提交、推送、部署。只回复本房间。不要展示密钥完整值。
  13. 请基于当前真实读取结果回答,无法访问就明确写出,不要依据历史记忆宣称已核实。
  14. 1. 读取你当前企微开通 SOP(life-init-standard / life-ops-hardened 等)及 App/Matrix 开通 SOP、实际执行脚本/默认模板。列出镜像版本/镜像摘要、Hermes 版本或源码 commit、技能/脚本路径;官方上游仓库地址也请提供。
  15. 2. 只读查看一个实际同时配置企微和 Matrix 的现有容器(优先 agent-node-u19170119836,先核对身份,AGENT_ID 和物理名可能不同)及一个 App 新开通容器。分别给出渠道 enabled、进程/连接状态、配置来源优先级(config.yaml/.env/docker env/s6 env)、插件清单、hooks 名称和顺序。标明当前时间及证据原始行,凭据只报哈希/存在性。
  16. 3. 对照官方安装版本源码,说明是否同一 gateway 能同时注册 wecom 和 matrix,按 source.platform/chat_id/thread_id 如何隔离 session/adapter。是否存在渠道二选一、session key 冲突、全局输出钩子污染、适配器 monkey patch、共享环境变量或全局线程状态。
  17. 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 的实际实现。
  18. 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 多实例抢连接。每点给文件路径/函数/少量原始行。
  19. 6. 请提出最小改动建议:同一容器保持两个官方 adapter,公共产物上传 S3 一次;Matrix 用 HTTPS 附件事件+thread+结束 reaction;企微按自身 adapter 原生发送规范消费同一产物;入站来源决定回原渠道,默认不双发、不跨渠道泄露对话。说明是否真的需要两个进程,避免未经证据就拆容器。
  20. 7. 给出可隔离验证的测试矩阵(企微单独、Matrix单独、双开交错、同名文件/并发/失败/重启持久化),本轮只给计划,不执行真实消息测试。
  21. 请分清【本次实读证据】【代码推断】【尚未验证】,不要以过去的成功当作本次结果。若无法访问宿主,只读检查本机并说清边界。回复尽量聚焦,先结论后证据。`;
  22. export async function runDiagnostic(options = {}) {
  23. const root = options.root || path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
  24. const dir = path.join(root, 'test-results/dual-channel-20261201');
  25. const stateFile = path.join(dir, 'state.json');
  26. const taskFile = path.join(root, 'docs/00-tracking/active-task.json');
  27. const command = options.command || 'read';
  28. const write = atomicDiagnosticWrite;
  29. const recordProgress = options.recordProgress || recordProjectProgress;
  30. const print = options.print || console.log;
  31. return withDiagnosticLock(dir, async () => {
  32. try {
  33. if (command === 'init') {
  34. if (fs.existsSync(stateFile)) throw Error('账本已存在;请 read,禁止覆盖或重发');
  35. fs.mkdirSync(dir, { recursive: true });
  36. fs.mkdirSync(path.join(root, '.local-backup/dual-channel-20261201'), { recursive: true });
  37. const previous = JSON.parse(fs.readFileSync(taskFile, 'utf8'));
  38. write(path.join(dir, 'active-task.before.json'), previous);
  39. write(path.join(dir, 'checkpoint.before.md'), fs.readFileSync(path.join(root, 'docs/00-tracking/接续检查点.md'), 'utf8'));
  40. write(path.join(dir, 'master-question.md'), prompt);
  41. write(stateFile, { version: 1, run: 'dual-channel-20261201', startedAt: beijingTime(), actions: {}, checks: [], acceptance: [
  42. { name: '本地开通与输出链路取证', status: 'in_progress' },
  43. { name: '主容器只读问询与回读', status: 'pending' },
  44. { name: '双渠道方案与测试计划', status: 'pending' },
  45. { name: '双渠道真实业务验收', status: 'not_run_plan_only' }
  46. ], recovery: { currentStep: '只读梳理企微与Matrix开通配置和输出钩子', nextSteps: ['主容器只读取证', '本地隔离复现', '形成方案与验收计划'] } });
  47. 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 };
  48. task.localWorkstreams = [...(previous.localWorkstreams || []), { id: 'dual-channel-20261201', goal: task.goal, status: 'investigating', ledger: task.ledger, report: task.report }];
  49. write(taskFile, task);
  50. recordProgress(root, '用户当前授权启动企微/Matrix双渠道诊断(/plan),既有工作流保留在active-task.previousTask与本轮active-task.before.json;已读检查点/CLAUDE/工作树/相关diff并运行project:resume。Docker命令不可用、原业务账本缺失,未重放任何旧动作。证据test-results/dual-channel-20261201;主容器问询目标与原文已落盘master-question.md,尚未发送。不修改业务源码或线上配置。');
  51. print('本轮账本、问询目标及当前任务已落盘;未发送。');
  52. } else {
  53. if (!fs.existsSync(stateFile)) throw Error('先显式 init 建立诊断账本');
  54. const state = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
  55. const master = options.client || createRequire(import.meta.url)('./master-channel.cjs');
  56. const request = master.request || (async (suffix, init = {}) => {
  57. 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' } });
  58. const data = await res.json();
  59. if (!res.ok) throw Object.assign(Error('Matrix HTTP ' + res.status + ' ' + (data.errcode || '')), { httpStatus: res.status, errcode: data.errcode });
  60. return data;
  61. });
  62. if (command === 'send') {
  63. if (state.actions.send?.attempted || state.actions.room?.attempted) throw Error('已有动作意图或回执;只读 read 核实,禁止盲重发');
  64. const me = await request('/account/whoami');
  65. if (me.user_id !== master.USER_MXID) throw Error('通信账号身份与配置不一致');
  66. state.actions.room = { attempted: true, attemptedAt: beijingTime(), target: { name: 'dual-channel-20261201-readonly', invite: master.MASTER_MXID }, mode: 'diagnostic_room_only' };
  67. write(stateFile, state);
  68. recordProgress(root, '准备向主容器@bnqaoxqhe8:fmode.cn发送一次只读双渠道问询;通信账号whoami已匹配。仅创建诊断房间并发master-question.md,不创建业务容器、不修改线上配置。房间创建目标已先落盘state.actions.room;中断先只读查房间及事件,不盲重试。');
  69. const room = await request('/createRoom', { method: 'POST', body: JSON.stringify({ ...state.actions.room.target, invite: [master.MASTER_MXID], preset: 'private_chat', is_direct: true }) });
  70. if (!room.room_id) throw Error('房间响应无room_id;保留未知态,先只读核实');
  71. state.actions.room.roomId = room.room_id;
  72. state.actions.room.confirmedAt = beijingTime();
  73. write(stateFile, state);
  74. const content = fs.readFileSync(path.join(dir, 'master-question.md'), 'utf8');
  75. 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() };
  76. write(stateFile, state);
  77. 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] } }) });
  78. if (!receipt.event_id) throw Error('发送响应无event_id;保留未知态,先只读核实');
  79. state.actions.send.eventId = receipt.event_id;
  80. state.actions.send.confirmedAt = beijingTime();
  81. write(path.join(dir, 'send-receipt.json'), { roomId: room.room_id, ...receipt, at: beijingTime(), promptSha256: sha(content) });
  82. write(stateFile, state);
  83. recordProgress(root, '已向主容器发送一次只读诊断问询,Matrix事件回执已落盘test-results/dual-channel-20261201/send-receipt.json。尚未收到回复,后续只读read查结果;未执行真实双渠道消息测试。');
  84. print(JSON.stringify({ sent: true, roomId: room.room_id, eventId: receipt.event_id }));
  85. } else if (command === 'followup') {
  86. if (state.actions.followup?.attempted) throw Error('补充问询已有意图;只读查回执,禁止重发');
  87. const roomId = state.actions.room?.roomId;
  88. if (!roomId) throw Error('无原诊断房间,不创建新房间');
  89. const content = `补充本地实际代码/离线证据(同一只读诊断,不执行改动):
  90. 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私有补丁。
  91. 2. 本地离线已复现:plugin-deliverable-inject对matrix和wecom都删除不在本轮pushed的普通参考URL(无成果时也删);远程MEDIA URL被删,本地MEDIA路径仍保留。不是所有MEDIA都被剥掉。
  92. 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隔离。
  93. 4. App新上报快照_fmode_channel_snapshot目前只返回matrix/matrixConfig,并整段提交channels,企微字段可能被覆盖(尚待服务端merge语义实读,不将推断当事实)。
  94. 请优先核对这些点在你实际现网模板/容器里是否相同,并补充:你自身此刻wecom与matrix是否在同一个gateway进程都connected?如宿主不可达不要持续试探,明确证据边界,给出本机源码路径/关键行与诊断结论即可。`;
  95. write(path.join(dir, 'master-followup.md'), content);
  96. state.actions.followup = { attempted: true, attemptedAt: beijingTime(), roomId, target: master.MASTER_MXID, txnId: 'dual-channel-followup-' + sha(content).slice(0, 24), promptSha256: sha(content) };
  97. write(stateFile, state);
  98. recordProgress(root, '已先落盘同房间补充问询目标master-followup.md与state.actions.followup:纠正Matrix当前采用m.text+S3卡片的前提,提交本地离线复现证据,请主容器核对本机双渠道状态;只问询,不授权改动或真实业务消息测试。');
  99. 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] } }) });
  100. if (!receipt.event_id) throw Error('补充发送回执不明,先只读核实');
  101. state.actions.followup.eventId = receipt.event_id;
  102. state.actions.followup.confirmedAt = beijingTime();
  103. write(stateFile, state);
  104. write(path.join(dir, 'followup-receipt.json'), { ...receipt, roomId, at: beijingTime() });
  105. recordProgress(root, '主容器同房间补充诊断问询已取得事件回执,证据test-results/dual-channel-20261201/followup-receipt.json;等待回读,不重复发送。');
  106. print(JSON.stringify({ sentFollowup: true, eventId: receipt.event_id }));
  107. } else if (command === 'read') {
  108. const roomId = state.actions.room?.roomId;
  109. if (!roomId) { print(JSON.stringify({ actions: state.actions, note: '无已确认房间;不创建或重试' })); return; }
  110. const members = await request('/rooms/' + encodeURIComponent(roomId) + '/joined_members');
  111. const events = [];
  112. let from = '';
  113. let startEventFound = false;
  114. let historyEnded = false;
  115. let pages = 0;
  116. for (let page = 0; page < 6; page++) {
  117. const data = await request('/rooms/' + encodeURIComponent(roomId) + '/messages?dir=b&limit=100' + (from ? '&from=' + encodeURIComponent(from) : ''));
  118. pages++;
  119. events.push(...(data.chunk || []));
  120. startEventFound = events.some(e => e.event_id === state.actions.send?.eventId);
  121. historyEnded = !data.end || data.end === from || !(data.chunk || []).length;
  122. if (startEventFound || historyEnded) break;
  123. from = data.end;
  124. }
  125. const coverage = { complete: startEventFound, truncated: !startEventFound && !historyEnded,
  126. startEventFound, historyEnded, nextToken: !startEventFound && !historyEnded ? from : null, pages };
  127. const observedAt = beijingTime();
  128. const snapshot = { observedAt, roomId, masterJoined: !!members.joined?.[master.MASTER_MXID], coverage, events };
  129. const observations = path.join(dir, 'observations');
  130. fs.mkdirSync(observations, { recursive: true });
  131. write(path.join(observations, new Date().toISOString().replace(/[:.]/g, '-') + '-' + randomUUID() + '.json'), snapshot);
  132. const previousEvidence = path.join(dir, 'master-events.json');
  133. const retained = fs.existsSync(previousEvidence) ? JSON.parse(fs.readFileSync(previousEvidence, 'utf8')).events || [] : [];
  134. const combined = new Map(retained.filter(e => e.event_id).map(e => [e.event_id, e]));
  135. for (const event of events) if (event.event_id) combined.set(event.event_id, event);
  136. const allEvents = [...combined.values()].sort((a,b) => a.origin_server_ts - b.origin_server_ts);
  137. const replies = allEvents.filter(e => e.sender === master.MASTER_MXID && e.origin_server_ts >= (state.actions.send?.since || 0));
  138. write(previousEvidence, { ...snapshot, events: allEvents, evidenceMode: 'accumulated_by_event_id' });
  139. 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 || '' }));
  140. write(path.join(dir, 'master-replies.md'), texts.map(e => '事件:' + e.eventId + '\n\n' + e.body).join('\n\n---\n\n'));
  141. const previousIds = new Set(state.replyEventIds || []);
  142. const freshTexts = texts.filter(x => !previousIds.has(x.eventId));
  143. state.observedAt = beijingTime();
  144. state.masterJoined = !!members.joined?.[master.MASTER_MXID];
  145. state.replyEventIds = texts.map(x => x.eventId);
  146. state.lastReadCoverage = coverage;
  147. const targets = new Set([state.actions.send?.eventId, state.actions.followup?.eventId].filter(Boolean));
  148. state.completionReactions = replies.filter(e => e.type === 'm.reaction' &&
  149. targets.has(e.content?.['m.relates_to']?.event_id) &&
  150. ['✅', '❌'].includes(e.content?.['m.relates_to']?.key)).map(e => ({
  151. eventId: e.event_id, targetEventId: e.content['m.relates_to'].event_id,
  152. key: e.content['m.relates_to'].key, at: e.origin_server_ts }));
  153. write(stateFile, state);
  154. print(JSON.stringify({ masterJoined: state.masterJoined, messages: texts.length, coverage,
  155. completionReactions: state.completionReactions,
  156. newReplies: freshTexts.map(x => ({ ...x, body: x.body.slice(-18000) })) }));
  157. } else throw Error('用法:node scripts/diagnose-dual-channels.mjs [init|send|followup|read]');
  158. }
  159. } catch (error) {
  160. if (fs.existsSync(stateFile)) {
  161. const latest = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
  162. latest.failures = [...(latest.failures || []), { stage: 'diagnostic_' + command,
  163. at: beijingTime(), error: String(error.message), httpStatus: error.httpStatus,
  164. status: command === 'read' ? 'observation_failed_previous_evidence_retained' : 'stopped_verify_before_retry' }];
  165. write(stateFile, latest);
  166. }
  167. throw error;
  168. }
  169. });
  170. }
  171. if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  172. await runDiagnostic({ command: process.argv[2] || 'read' });
  173. }