"""离线复现当前双渠道风险;通过表示成功复现现状,不代表业务验收通过。""" from __future__ import annotations from dataclasses import dataclass import ast import importlib.util import json import os from pathlib import Path import tempfile import time from unittest.mock import patch ROOT = Path(__file__).resolve().parents[1] RUNTIME = ROOT / 'cloud/onboarding/runtime' def load(name: str, path: Path, package: bool = False): import sys spec = importlib.util.spec_from_file_location( name, path, submodule_search_locations=[str(path.parent)] if package else None) module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) return module def main(): results = [] def record(name, kind, observed, evidence): results.append({'name': name, 'kind': kind, 'observed': observed, 'evidence': evidence}) installer = load('dual_probe_install', ROOT / 'cloud/onboarding/install.py') original = {'platforms': {'wecom': {'enabled': True, 'extra': {'bot_id': 'fixture-bot'}}, 'matrix': {'enabled': False}}, 'plugins': {'enabled': ['existing']}} merged = installer.merge_config(original, {'plugins': ['bridge'], 'hooks': {}}) assert merged['platforms']['wecom'] == original['platforms']['wecom'] assert original['plugins']['enabled'] == ['existing'] record('installer_preserves_wecom', 'working_contract', True, 'merge_config增量保留企微且不修改原对象') assert merged['platforms']['matrix']['enabled'] is False record('installer_preserves_explicit_matrix_disabled', 'configuration_gate', True, '已有matrix.enabled=false时仅追加typing_indicator;实际生效仍取决于安装版config_env优先级') inject = load('dual_probe_inject', RUNTIME / 'plugins/plugin-deliverable-inject/__init__.py', True) inject._load_state = lambda sid: {} inject._current_turn_id = lambda sid: 'fixture-turn' reference = 'https://work.weixin.qq.com/api/doc/90000/90136/91770' with patch.dict(os.environ, {'PLUGIN_DELIVERABLE_INJECT_DISABLE': '0', 'PLUGIN_FMODE_STRIP_MEDIA_DISABLE': '0'}): for platform in ('matrix', 'wecom'): text = '参考官方文档:' + reference transformed = inject._on_transform_llm_output(text, 'fixture-session', 'fixture-turn', platform=platform) assert reference not in transformed record(platform + '_ordinary_reference_url_removed', 'reproduced_defect', transformed, '无成果台账时普通参考链接被全局白名单删除,platform kwargs被忽略') media = inject._on_transform_llm_output('交付图片\nMEDIA:https://s3.fmode.cn/fixture/picture.png', 'fixture-session', 'fixture-turn', platform=platform) assert 'MEDIA:' not in media and 'https://' not in media record(platform + '_remote_media_anchor_removed', 'reproduced_behavior', media, '无本轮pushed时远程MEDIA锚点与URL均被剥除;需实际adapter确认终端后果') local = inject._on_transform_llm_output('交付文件\nMEDIA:/opt/data/work/output.pdf', 'fixture-session', 'fixture-turn', platform=platform) assert local is None or 'MEDIA:/opt/data/work/output.pdf' in local record(platform + '_local_media_anchor_preserved', 'working_contract', True, '本地MEDIA标记仍保留,不能把所有附件问题归因于全量剥除') outbound = load('dual_probe_outbound', RUNTIME / 'plugins/plugin-matrix-outbound-s3/__init__.py') with tempfile.TemporaryDirectory(prefix='fmode-dual-contract-') as tmp: directory = Path(tmp) a, b = directory / 'session-a/report.pdf', directory / 'session-b/report.pdf' a.parent.mkdir() b.parent.mkdir() a.write_bytes(b'AAAA') b.write_bytes(b'BBBB') now = time.time() for name, file, url, timestamp in [('a', a, 'https://s3.fmode.cn/fixture/a.pdf', now - 2), ('b', b, 'https://s3.fmode.cn/fixture/b.pdf', now - 1)]: (directory / (name + '.json')).write_text(json.dumps({'pushed': [ {'path': str(file), 'url': url, 'ts': timestamp, 'turn_id': 'turn-' + name}]})) outbound._STATE_DIR = str(directory) outbound._INDEX_CACHE = {'sig': None, 'map': {}} actual = outbound._preuploaded_lookup(str(a), 4, wait=False) assert actual == 'https://s3.fmode.cn/fixture/b.pdf' record('same_name_same_size_cross_session_url', 'reproduced_defect', actual, '请求session-a/report.pdf却选中较新的session-b同名同大小文件;没有session/turn/hash约束') merge = load('dual_probe_media_merge', RUNTIME / 'plugins/plugin-media-text-merge/__init__.py') merge._log = lambda message: None merge._arm_timer = lambda chat_id, gateway: None @dataclass class Source: platform: str chat_id: str thread_id: str chat_type: str = 'dm' @dataclass class Event: source: Source text: str media_urls: list media_types: list with patch.dict(os.environ, {'MEDIA_TEXT_MERGE_SECONDS': '2.5'}): for label, second_platform in [('matrix_cross_thread', 'matrix'), ('same_chat_id_cross_platform', 'wecom')]: merge._PENDING.clear() first = Event(Source('matrix', 'same-chat', 'thread-a'), 'A', ['https://s3.fmode.cn/fixture/a.png'], ['image/png']) second = Event(Source(second_platform, 'same-chat', 'thread-b'), 'B', [], []) assert merge._on_pre_gateway_dispatch(first)['action'] == 'skip' assert merge._on_pre_gateway_dispatch(second)['action'] == 'skip' combined = merge._merged_event(merge._PENDING['same-chat']) assert combined.source.thread_id == 'thread-a' and 'B' in combined.text record(label + '_buffer_collision', 'reproduced_defect', {'keptPlatform': combined.source.platform, 'keptThread': combined.source.thread_id, 'mergedText': combined.text}, '缓冲键只有chat_id;同房间不同thread会合并,跨平台相同chat_id也会合并') merge._PENDING.clear() hook_file = RUNTIME / 'scripts/fmode-deliverable-hook.py' hook_tree = ast.parse(hook_file.read_text(encoding='utf-8')) import re pure = {'os': os, 're': re, 'log': lambda message: None} names = {'_scrub_fake_urls', '_scrub_local_paths'} functions = [n for n in hook_tree.body if isinstance(n, ast.FunctionDef) and n.name in names] assert len(functions) == 2 exec(compile(ast.Module(body=functions, type_ignores=[]), str(hook_file), 'exec'), pure) cleaned = pure['_scrub_fake_urls']('参考文档:https://work.weixin.qq.com/fixture', set()) assert 'https://' not in cleaned record('shell_hook_reference_url_removed', 'reproduced_defect', cleaned, 'shell输出钩子纯函数也删除普通URL;完整调度是否采纳其输出仍须验证部署版hook返回语义') cleaned = pure['_scrub_local_paths']('交付文件\nMEDIA:/opt/data/work/output.pdf') assert 'MEDIA:' not in cleaned record('shell_hook_local_media_anchor_removed', 'reproduced_defect', cleaned, 'shell清洗函数删除本地MEDIA行;Python注入插件保留标记不代表整条链路保留') transform = next(n for n in hook_tree.body if isinstance(n, ast.FunctionDef) and n.name == 'handle_transform_llm_output') dedup = next(n for n in transform.body if isinstance(n, ast.If) and isinstance(n.test, ast.Name) and n.test.id == 'todo') with tempfile.TemporaryDirectory(prefix='fmode-dual-preupload-') as tmp: a, b = Path(tmp) / 'a/report.pdf', Path(tmp) / 'b/report.pdf' a.parent.mkdir() b.parent.mkdir() a.write_bytes(b'AAAA') b.write_bytes(b'BBBB') os.utime(a, (100, 100)) os.utime(b, (200, 200)) namespace = {'os': os, 'log': lambda message: None, 'todo': [{'path': str(a), 'turn_id': 'same-turn'}, {'path': str(b), 'turn_id': 'same-turn'}]} exec(compile(ast.Module(body=[dedup], type_ignores=[]), str(hook_file), 'exec'), namespace) assert len(namespace['todo']) == 1 and namespace['todo'][0]['path'] == str(b) record('preupload_same_turn_different_content_dropped', 'reproduced_defect', {'inputFiles': 2, 'retainedFiles': len(namespace['todo'])}, '直接执行上传前现有AST去重分支:同轮不同目录/同名同大小但内容不同,只保留较新文件') reporter_file = RUNTIME / 'plugins/plugin-active-reporter/__init__.py' tree = ast.parse(reporter_file.read_text(encoding='utf-8')) function = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == '_fmode_channel_snapshot') namespace = {} exec(compile(ast.Module(body=[function], type_ignores=[]), str(reporter_file), 'exec'), namespace) with tempfile.TemporaryDirectory(prefix='fmode-dual-reporter-') as tmp: (Path(tmp) / 'gateway_state.json').write_text(json.dumps({'platforms': { 'matrix': {'state': 'connected'}, 'wecom': {'state': 'connected'}}})) with patch.dict(os.environ, {'HERMES_HOME': tmp, 'MATRIX_USER_ID': '@fixture:invalid'}): snapshot = namespace['_fmode_channel_snapshot']() assert snapshot['matrix'] is True and 'wecom' not in snapshot record('reporter_omits_connected_wecom', 'reproduced_defect', snapshot, '输入双渠道connected,输出只有matrix/matrixConfig;本地云函数agent.set(field,value)整字段赋值,线上部署版本待比对') result = {'scope': 'local_offline_existing_source_only', 'meaning': '通过表示复现断言成立,不代表修复或线上验收', 'networkRequests': 0, 'productionChanges': 0, 'observations': results} output = ROOT / 'test-results/dual-channel-20261201/local-contract-probe.json' output.parent.mkdir(parents=True, exist_ok=True) output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') print(json.dumps({'observations': len(results), 'evidence': str(output.relative_to(ROOT)), 'defectsReproduced': sum(x['kind'] == 'reproduced_defect' for x in results)}, ensure_ascii=False)) if __name__ == '__main__': main()