Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(memory): capture ordinary attachments on Discord, Telegram, Lark and WeChat (#1476)
rkrkrkkc8d0927c1a10
diff --git a/core/memory/attachments.py b/core/memory/attachments.pyindex f6ff38e09..8e751da64 100644--- a/core/memory/attachments.py+++ b/core/memory/attachments.py@@ -39,7 +39,9 @@ if TYPE_CHECKING:MAX_PINNED_ATTACHMENTS = 8MAX_PINNED_ATTACHMENT_BYTES = 25 * 1024 * 1024MAX_PINNED_BUNDLE_BYTES = 100 * 1024 * 1024-IM_ATTACHMENT_CAPTURE_PLATFORMS = frozenset({"slack"})+IM_ATTACHMENT_CAPTURE_PLATFORMS = frozenset(+ {"slack", "discord", "telegram", "lark", "wechat"}+)_COPY_CHUNK_BYTES = 1024 * 1024_MAX_ATTACHMENT_NAME_BYTES = 512diff --git a/docs/MEMORY.md b/docs/MEMORY.mdindex d22a27d24..6a9d78cdd 100644--- a/docs/MEMORY.md+++ b/docs/MEMORY.md@@ -14,6 +14,27 @@ Avibe Memory distills eligible Workbench and private-IM messages into aper-user profile, episodes, and facts. Open **Settings > Memory** to inspect itsProcessing Record, current profile, search results, and settings.+## IM attachment capture++Memory can extract supported attachments from bound one-to-one conversations on+Slack, Discord, Telegram, Lark, and WeChat. Capture becomes available only when+Memory is enabled and the Multimodal LLM endpoint under **Settings > Memory** is+fully configured. It does not change the files delivered to the Agent.++Only direct, ordinary files shared by a human are eligible. Bot, system,+forwarded, edited, quoted, rich, and unrecognized native message shapes are+excluded. Avibe then validates each eligible file against one shared format and+content policy. Supported formats are plain text, Markdown, CSV/TSV, VTT, PDF,+bitmap images, audio, HTML, and EML. Unsupported or malformed files are skipped+independently, so eligible text and valid siblings can still be captured.++Each turn is limited to 8 captured attachments, 25 MiB per attachment, and+100 MiB in total. Admitted files are copied into private Avibe storage until the+durable Memory delivery settles. Their extracted content can be sent to the+configured multimodal provider, so configure that endpoint according to your+data-handling requirements. Clearing Memory Data removes retained local+attachment bundles but cannot remove copies already accepted by a provider.+## Processed episode listing`vibe memory list` reads only valid, active processed episodes for the currentdiff --git a/docs/MEMORY_ZH.md b/docs/MEMORY_ZH.mdindex b8180a79d..83fec425f 100644--- a/docs/MEMORY_ZH.md+++ b/docs/MEMORY_ZH.md@@ -3,6 +3,22 @@Avibe 记忆会把符合条件的 Workbench 和私聊消息提炼为按用户隔离的画像、事件与事实。在**设置 > 记忆**中可以查看状态、当前画像、搜索结果、设置和处理日志。+## IM 附件捕获++记忆可以从 Slack、Discord、Telegram、飞书/Lark 和微信已绑定的一对一会话中提取受支持+的附件。仅当记忆已启用,并且在**设置 > 记忆**中完整配置多模态 LLM 端点后,此能力才+可用;它不会改变发送给 Agent 的文件。++只有人类直接分享的普通文件才符合条件。机器人、系统、转发、编辑、引用、富内容和无法+识别的原生消息形状都会被排除。随后,Avibe 使用同一套格式与内容策略检查每个符合条件+的文件。支持纯文本、Markdown、CSV/TSV、VTT、PDF、位图图片、音频、HTML 和 EML。+不支持或格式异常的文件会被单独跳过,符合条件的文本和其它有效附件仍可进入捕获。++每轮最多捕获 8 个附件,单个附件最大 25 MiB,总计最大 100 MiB。通过准入的文件会复制+到 Avibe 私有存储,并保留到持久化记忆投递完成。提取后的内容可能发送给已配置的多模态+提供方,因此请按数据处理要求配置该端点。清理记忆数据会删除本机仍保留的附件包,但+无法删除提供方已经接收的副本。+## 已处理事件列表`vibe memory list` 只读取当前范围内用户和项目的有效、活跃、已处理事件,不包含画像、diff --git a/docs/plans/memory-im-attachments-1425.md b/docs/plans/memory-im-attachments-1425.mdindex 5d86e855e..6f6a1dea3 100644--- a/docs/plans/memory-im-attachments-1425.md+++ b/docs/plans/memory-im-attachments-1425.md@@ -382,7 +382,16 @@ The canonical capability is `memory_im_attachment_capture` under- `MEMORY-IM-ATTACH-003`: absent multimodal configuration captures eligible textonly and creates no attachment provider/call-log activity; and- `MEMORY-IM-ATTACH-004`: count, per-file, total-size, unsupported-type, and partial- download failures preserve valid siblings and leave no temp or bundle leak.+ download failures preserve valid siblings and leave no temp or bundle leak;+- `MEMORY-IM-ATTACH-005`: a native human Discord file share reaches attachment+ admission while rich, bot, webhook, sticker, forwarded, and snapshot shapes+ remain closed;+- `MEMORY-IM-ATTACH-006`: Telegram document, largest-photo, voice, and audio+ shapes reach admission independently, including separate album messages;+- `MEMORY-IM-ATTACH-007`: Lark file and image messages with non-empty native keys+ reach admission while `media` and malformed events remain closed; and+- `MEMORY-IM-ATTACH-008`: direct WeChat image, voice, file, and video items reach+ admission while reference and malformed media items remain closed.The closed-loop harness uses a stub platform client, a real test-owned bundle path,and local fake OpenAI-compatible providers. It must not use live credentials,@@ -413,9 +422,24 @@ next slice.## Residual manual checksHermetic tests prove the product contracts without live platform credentials.-After all five slices merge, the orchestrator's integration pass should verify one-eligible image and one rejected file on every configured IM platform in the local-Incus regression environment, preserving accumulated product state.+After all five slices merge, the orchestrator's integration pass should run the+following matrix in the local Incus regression environment while preserving+accumulated product state:++- Slack: one eligible image and one rejected file;+- Discord: one ordinary upload and captured fixtures for ordinary-upload embeds,+ authored embeds, components, stickers, webhooks, forwards, and snapshots. The+ repository has no fixture proving whether an ordinary upload receives an embed,+ so PR5 conservatively rejects every embed-bearing message until this check;+- Telegram: document, largest photo variant, voice, audio, separate messages in+ one album, and non-published video, animation, and sticker shapes;+- Lark: file, image, malformed/empty native keys, and a captured real `media`+ event for a later admission decision. Runtime tracing confirms the adapter sends+ the literal platform name `lark`; the separate `IM_PLATFORMS` set still carrying+ both `lark` and `feishu` is a future namespace-cleanup item; and+- WeChat: direct image, voice, file, and video items plus quoted/reference and+ source-identity cases. Video must reach the shared modality policy and produce+ its existing skip accounting rather than being prefiltered in the adapter.The final PR4 invariant audit also found five pre-existing paths outside thisslice's implementation files. The two bounded-wait spans are tracked by #1470;diff --git a/modules/im/discord.py b/modules/im/discord.pyindex 1be9629ae..fa762e988 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -18,7 +18,7 @@ from .base import (InlineButton,FileAttachment,)-from .message_facts import is_ordinary_discord_text+from .message_facts import is_ordinary_discord_attachment, is_ordinary_discord_textfrom .download_target import open_download_targetfrom config.v2_config import DiscordConfigfrom .formatters import DiscordFormatter@@ -1114,6 +1114,7 @@ class DiscordBot(BaseIMClient):platform_specific={"platform": "discord", "message": message, "is_dm": is_dm},files=files,is_ordinary_text=is_ordinary_discord_text(message, files),+ is_ordinary_attachment=is_ordinary_discord_attachment(message, files),)if self.on_message_callback:diff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex ed6d0732a..aabe0295b 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -20,7 +20,7 @@ from .base import (MessageContext,)from .formatters import FeishuFormatter-from .message_facts import is_ordinary_feishu_text+from .message_facts import is_ordinary_feishu_attachment, is_ordinary_feishu_textfrom .download_target import open_download_targetfrom config.v2_config import LarkConfigfrom vibe.i18n import get_supported_languages, t as i18n_t@@ -1764,6 +1764,12 @@ class FeishuBot(BaseIMClient):file_attachments,shared_text=shared_text,),+ is_ordinary_attachment=is_ordinary_feishu_attachment(+ event_data,+ msg_content,+ file_attachments,+ shared_text=shared_text,+ ),)# Handle commands (messages starting with /)diff --git a/modules/im/message_facts.py b/modules/im/message_facts.pyindex a7edf0806..b89f26288 100644--- a/modules/im/message_facts.py+++ b/modules/im/message_facts.py@@ -150,6 +150,36 @@ def is_ordinary_discord_text(message: Any, files: Optional[list[FileAttachment]])+def is_ordinary_discord_attachment(+ message: Any,+ files: Optional[list[FileAttachment]],+) -> bool:+ """Classify a direct human Discord upload from native message facts."""++ try:+ is_system = message.is_system() if callable(getattr(message, "is_system", None)) else False+ except Exception:+ return False+ flags = getattr(message, "flags", None)+ # The repository has no fixture proving whether ordinary uploads receive an+ # automatic embed. Keep that unverified shape closed until the Incus matrix.+ has_unverified_attachment_embeds = bool(getattr(message, "embeds", None))+ return bool(+ files+ and getattr(message, "attachments", None)+ and getattr(getattr(message, "author", None), "bot", None) is False+ and getattr(message, "edited_at", None) is None+ and not has_unverified_attachment_embeds+ and not getattr(message, "components", None)+ and not getattr(message, "stickers", None)+ and not getattr(message, "sticker_items", None)+ and getattr(message, "webhook_id", None) is None+ and not bool(getattr(flags, "forwarded", False))+ and not getattr(message, "message_snapshots", None)+ and not is_system+ )++def is_ordinary_telegram_text(message: dict[str, Any], files: list[FileAttachment]) -> bool:sender = message.get("from") or {}return not any(@@ -166,6 +196,46 @@ def is_ordinary_telegram_text(message: dict[str, Any], files: list[FileAttachmen)+def is_ordinary_telegram_attachment(+ message: dict[str, Any],+ files: list[FileAttachment],+) -> bool:+ """Classify one direct Telegram file-bearing message without album grouping."""++ sender = message.get("from") or {}+ native_shapes = tuple(+ value+ for value in (+ message.get("document"),+ message.get("photo"),+ message.get("voice"),+ message.get("audio"),+ )+ if value+ )+ return bool(+ files+ and len(native_shapes) == 1+ and sender.get("is_bot") is False+ and not any(+ (+ message.get("edit_date"),+ message.get("forward_origin"),+ message.get("forward_from"),+ message.get("sender_chat"),+ message.get("via_bot"),+ message.get("video"),+ message.get("animation"),+ message.get("sticker"),+ message.get("video_note"),+ message.get("is_system"),+ message.get("system"),+ message.get("type") in {"system", "system_message"},+ )+ )+ )++def is_ordinary_feishu_text(event: dict[str, Any],files: Optional[list[FileAttachment]],@@ -183,6 +253,32 @@ def is_ordinary_feishu_text()+def is_ordinary_feishu_attachment(+ event: dict[str, Any],+ content: dict[str, Any],+ files: Optional[list[FileAttachment]],+ *,+ shared_text: Optional[str],+) -> bool:+ """Classify a direct human Feishu/Lark file or image message."""++ sender = event.get("sender") or {}+ message = event.get("message") or {}+ message_type = message.get("message_type")+ native_key = content.get("file_key") if message_type == "file" else None+ if message_type == "image":+ native_key = content.get("image_key")+ return bool(+ sender.get("sender_type") == "user"+ and message_type in {"file", "image"}+ and isinstance(native_key, str)+ and native_key.strip()+ and files+ and not shared_text+ and not any(message.get(key) for key in ("edited", "forwarded"))+ )++def is_ordinary_workbench_text(payload: object, quick_reply_for: object) -> bool:"""Classify a Workbench submit the same way the IM adapters classify events.@@ -215,3 +311,39 @@ def is_ordinary_wechat_text(msg: dict[str, Any], files: Optional[list[FileAttachand not filesand not any(msg.get(key) for key in ("is_system", "system", "edited", "forwarded")))+++def is_ordinary_wechat_attachment(+ msg: dict[str, Any],+ files: Optional[list[FileAttachment]],+) -> bool:+ """Classify direct iLink media from the original item-list shape."""++ items = msg.get("item_list")+ if not isinstance(items, list) or not items or not files:+ return False+ media_fields = {+ 2: "image_item",+ 3: "voice_item",+ 4: "file_item",+ 5: "video_item",+ }+ has_direct_media = False+ for item in items:+ if not isinstance(item, dict) or item.get("ref_msg"):+ return False+ item_type = item.get("type")+ if item_type in (1, "TEXT", "text"):+ continue+ media_field = media_fields.get(item_type)+ if media_field is None:+ return False+ item_data = item.get(media_field)+ media = item_data.get("media") if isinstance(item_data, dict) else None+ query = media.get("encrypt_query_param") if isinstance(media, dict) else None+ if not isinstance(query, str) or not query.strip():+ return False+ has_direct_media = True+ return has_direct_media and not any(+ msg.get(key) for key in ("is_system", "system", "edited", "forwarded")+ )diff --git a/modules/im/telegram.py b/modules/im/telegram.pyindex 10faff24c..774d98424 100644--- a/modules/im/telegram.py+++ b/modules/im/telegram.py@@ -28,7 +28,7 @@ from .base import (InlineKeyboard,)from .formatters import TelegramFormatter-from .message_facts import is_ordinary_telegram_text+from .message_facts import is_ordinary_telegram_attachment, is_ordinary_telegram_textfrom . import telegram_apilogger = logging.getLogger(__name__)@@ -761,6 +761,7 @@ class TelegramBot(BaseIMClient):message_id=str(message.get("message_id")),files=files,is_ordinary_text=is_ordinary_telegram_text(message, files),+ is_ordinary_attachment=is_ordinary_telegram_attachment(message, files),platform="telegram",platform_specific={"is_dm": chat.get("type") == "private",diff --git a/modules/im/wechat.py b/modules/im/wechat.pyindex 07eb564c6..eeb26eb16 100644--- a/modules/im/wechat.py+++ b/modules/im/wechat.py@@ -33,7 +33,10 @@ from vibe.proxy import resolve_proxyfrom modules.im import wechat_api as _wechat_api_modfrom modules.im import wechat_cdn as _wechat_cdn_modfrom modules.im.formatters.wechat_formatter import WeChatFormatter-from modules.im.message_facts import is_ordinary_wechat_text+from modules.im.message_facts import (+ is_ordinary_wechat_attachment,+ is_ordinary_wechat_text,+)logger = logging.getLogger(__name__)@@ -1398,6 +1401,7 @@ class WeChatBot(BaseIMClient):# Handle media attachmentsawait self._process_media_items(msg, context)context.is_ordinary_text = is_ordinary_wechat_text(msg, context.files)+ context.is_ordinary_attachment = is_ordinary_wechat_attachment(msg, context.files)# Authorization checkauth_result = self.check_authorization(diff --git a/tests/scenarios/memory_im_attachment_capture/catalog.yaml b/tests/scenarios/memory_im_attachment_capture/catalog.yamlindex 517c45d09..b11fd438c 100644--- a/tests/scenarios/memory_im_attachment_capture/catalog.yaml+++ b/tests/scenarios/memory_im_attachment_capture/catalog.yaml@@ -48,3 +48,31 @@ scenarios:layer: scenariodelivery_slice: 4test: tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py::test_invalid_sibling_preserves_valid_attachment_and_leaves_no_memory_leak+ - id: MEMORY-IM-ATTACH-005+ name: Native Discord DM file shares reach Memory attachment admission+ status: covered+ kind: platform_contract+ layer: scenario+ delivery_slice: 5+ test: tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py::test_enabled_platform_attachment_fact_reaches_memory_admission+ - id: MEMORY-IM-ATTACH-006+ name: Native Telegram DM document, photo, voice, and audio shares reach Memory attachment admission+ status: covered+ kind: platform_contract+ layer: scenario+ delivery_slice: 5+ test: tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py::test_enabled_platform_attachment_fact_reaches_memory_admission+ - id: MEMORY-IM-ATTACH-007+ name: Native Lark DM file and image shares reach Memory attachment admission+ status: covered+ kind: platform_contract+ layer: scenario+ delivery_slice: 5+ test: tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py::test_enabled_platform_attachment_fact_reaches_memory_admission+ - id: MEMORY-IM-ATTACH-008+ name: Native WeChat DM image, voice, file, and video shares reach Memory attachment admission+ status: covered+ kind: platform_contract+ layer: scenario+ delivery_slice: 5+ test: tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py::test_enabled_platform_attachment_fact_reaches_memory_admissiondiff --git a/tests/scenarios/memory_im_attachment_capture/observations.yaml b/tests/scenarios/memory_im_attachment_capture/observations.yamlindex c13252627..8ed030a0d 100644--- a/tests/scenarios/memory_im_attachment_capture/observations.yaml+++ b/tests/scenarios/memory_im_attachment_capture/observations.yaml@@ -22,3 +22,14 @@ observations:observation: The existing Avibe sidecar already admits confined pinned file URIs for the exact memory add route, while current IM admission rejects file turns before Memory acquisition.evidence:avibe_commit: c21bf9268417c9d857ea275fe9f7e95023809311+ - id: MEMORY-IM-ATTACH-OBS-004+ scenarios:+ - MEMORY-IM-ATTACH-005+ - MEMORY-IM-ATTACH-007+ observation: >-+ The Lark adapter passes the literal platform name lark through its inbound+ context, while the repository has no fixture proving whether an ordinary+ Discord upload carries an automatic embed; Discord therefore remains+ fail-closed for embed-bearing messages pending the Incus matrix.+ evidence:+ avibe_commit: 063aebd29713615e63ec828da94c4c8b339b6647diff --git a/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_catalog.py b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_catalog.pyindex b98b4248c..f769e3278 100644--- a/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_catalog.py+++ b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_catalog.py@@ -61,6 +61,10 @@ def test_memory_im_attachment_catalog_is_indexed_and_locks_the_approved_contract("MEMORY-IM-ATTACH-002", "authorization", 4),("MEMORY-IM-ATTACH-003", "degradation", 4),("MEMORY-IM-ATTACH-004", "boundary", 4),+ ("MEMORY-IM-ATTACH-005", "platform_contract", 5),+ ("MEMORY-IM-ATTACH-006", "platform_contract", 5),+ ("MEMORY-IM-ATTACH-007", "platform_contract", 5),+ ("MEMORY-IM-ATTACH-008", "platform_contract", 5),],)def test_memory_im_attachment_covered_scenario_contract(@@ -68,7 +72,7 @@ def test_memory_im_attachment_covered_scenario_contract(kind: str,delivery_slice: int,) -> None:- """The four MEMORY-IM-ATTACH scenario IDs map to executable evidence."""+ """Every MEMORY-IM-ATTACH scenario ID maps to executable evidence."""catalog = _load(SCENARIO_ROOT / "catalog.yaml")rows = {row["id"]: row for row in catalog["scenarios"]}@@ -79,6 +83,10 @@ def test_memory_im_attachment_covered_scenario_contract("MEMORY-IM-ATTACH-002","MEMORY-IM-ATTACH-003","MEMORY-IM-ATTACH-004",+ "MEMORY-IM-ATTACH-005",+ "MEMORY-IM-ATTACH-006",+ "MEMORY-IM-ATTACH-007",+ "MEMORY-IM-ATTACH-008",}assert rows[scenario_id]["status"] == "covered"assert rows[scenario_id]["kind"] == kinddiff --git a/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.pyindex 1a042740e..ae5b4d66f 100644--- a/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py+++ b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py@@ -5,11 +5,20 @@ from __future__ import annotationsimport asyncioimport base64import json+from types import SimpleNamespaceimport pytestfrom core.caller_context import AVIBE_SESSION_ID_ENV+from core.memory.admission import CaptureAdmission, InboundTurnFactsfrom core.memory.types import RecallItems, RecallPolicy, memory_item_payload+from modules.im.base import FileAttachment+from modules.im.message_facts import (+ is_ordinary_discord_attachment,+ is_ordinary_feishu_attachment,+ is_ordinary_telegram_attachment,+ is_ordinary_wechat_attachment,+)from tests.scenario_harness.memory_im_attachments import (PNG_BYTES,PRINCIPAL,@@ -204,3 +213,111 @@ def test_invalid_sibling_preserves_valid_attachment_and_leaves_no_memory_leak(assert len(harness.provider.call_log) == 1assert harness.memory_bundle_entries == ()assert not tuple(harness.home.rglob("*.part"))+++class _ScenarioPrincipals:+ def principal_for_user_key(self, user_key: str) -> str:+ assert user_key.split(":", 1)[0] in {"discord", "telegram", "lark", "wechat"}+ return PRINCIPAL+++class _ScenarioBindings:+ def is_enabled_user(self, platform: str, user_id: str) -> bool:+ return platform in {"discord", "telegram", "lark", "wechat"} and user_id == "U1"+++def _platform_attachment_fact(platform: str, file: FileAttachment) -> bool:+ if platform == "discord":+ message = SimpleNamespace(+ author=SimpleNamespace(bot=False),+ edited_at=None,+ attachments=[object()],+ embeds=[],+ components=[],+ stickers=[],+ sticker_items=[],+ webhook_id=None,+ flags=SimpleNamespace(forwarded=False),+ message_snapshots=(),+ is_system=lambda: False,+ )+ return is_ordinary_discord_attachment(message, [file])+ if platform == "telegram":+ return is_ordinary_telegram_attachment(+ {+ "from": {"id": "U1", "is_bot": False},+ "document": {"file_id": "native-file", "file_name": file.name},+ },+ [file],+ )+ if platform == "lark":+ return is_ordinary_feishu_attachment(+ {+ "sender": {"sender_type": "user"},+ "message": {"message_type": "file"},+ },+ {"file_key": "native-file", "file_name": file.name},+ [file],+ shared_text=None,+ )+ return is_ordinary_wechat_attachment(+ {+ "from_user_id": "U1",+ "item_list": [+ {+ "type": 4,+ "file_item": {+ "file_name": file.name,+ "media": {"encrypt_query_param": "native-file"},+ },+ }+ ],+ },+ [file],+ )+++ ("scenario_id", "platform"),+ [+ pytest.param("MEMORY-IM-ATTACH-005", "discord", id="MEMORY-IM-ATTACH-005"),+ pytest.param("MEMORY-IM-ATTACH-006", "telegram", id="MEMORY-IM-ATTACH-006"),+ pytest.param("MEMORY-IM-ATTACH-007", "lark", id="MEMORY-IM-ATTACH-007"),+ pytest.param("MEMORY-IM-ATTACH-008", "wechat", id="MEMORY-IM-ATTACH-008"),+ ],+)+def test_enabled_platform_attachment_fact_reaches_memory_admission(+ scenario_id: str,+ platform: str,+) -> None:+ """Scenarios MEMORY-IM-ATTACH-005..008 cover each newly enabled adapter."""++ suffix_by_platform = {+ "discord": "005",+ "telegram": "006",+ "lark": "007",+ "wechat": "008",+ }+ assert scenario_id.endswith(suffix_by_platform[platform])+ file = FileAttachment(+ name="evidence.pdf",+ mimetype="application/pdf",+ url="native-file",+ )+ admission = CaptureAdmission(+ principals=_ScenarioPrincipals(),+ bindings=_ScenarioBindings(),+ )+ facts = InboundTurnFacts(+ platform=platform,+ user_id="U1",+ message_id="native-message",+ session_id="stable-session",+ files=[file],+ is_dm=True,+ is_ordinary_attachment=_platform_attachment_fact(platform, file),+ memory_enabled=True,+ )++ assert facts.is_ordinary_attachment is True+ assert admission.admits_attachment_turn(facts) is Truediff --git a/tests/test_discord_reply_anchor.py b/tests/test_discord_reply_anchor.pyindex e9ca78bb1..04d8bcf12 100644--- a/tests/test_discord_reply_anchor.py+++ b/tests/test_discord_reply_anchor.py@@ -182,6 +182,47 @@ class DiscordReplyAnchorTests(unittest.IsolatedAsyncioTestCase):self.assertTrue(bot.on_message_callback.await_args.args[0].is_ordinary_text)self.assertEqual(bot.on_message_callback.await_args.args[1], "scheduled follow-up context")+ async def test_native_file_message_publishes_ordinary_attachment_fact(self):+ bot = object.__new__(DiscordBot)+ bot.config = DiscordConfig(require_mention=False)+ bot._controller = None+ bot.client = SimpleNamespace(user=SimpleNamespace(id=42))+ bot.on_message_callback = AsyncMock()+ bot.sessions = None+ bot.settings_manager = None+ bot.check_authorization = lambda **kwargs: AuthResult(allowed=True, is_dm=False)+ bot.dispatch_text_command = AsyncMock(return_value=False)+ attachment = SimpleNamespace(+ filename="diagram.png",+ content_type="image/png",+ url="https://cdn.discord.test/diagram.png",+ size=123,+ )+ message = SimpleNamespace(+ author=SimpleNamespace(id=456, bot=False),+ content="remember this",+ channel=SimpleNamespace(id=123),+ guild=None,+ attachments=[attachment],+ mentions=[],+ id=888,+ edited_at=None,+ embeds=[],+ components=[],+ stickers=[],+ sticker_items=[],+ webhook_id=None,+ flags=SimpleNamespace(forwarded=False),+ message_snapshots=(),+ is_system=lambda: False,+ )++ await DiscordBot._on_message_event(bot, message)++ bot.on_message_callback.assert_awaited_once()+ context = bot.on_message_callback.await_args.args[0]+ self.assertIs(context.is_ordinary_attachment, True)+async def test_send_auth_denial_acknowledges_silent_interaction_denial(self):bot = object.__new__(DiscordBot)bot.build_auth_denial_text = lambda denial, channel_id=None: Nonediff --git a/tests/test_feishu_post_messages.py b/tests/test_feishu_post_messages.pyindex f27c7a883..8d162ae94 100644--- a/tests/test_feishu_post_messages.py+++ b/tests/test_feishu_post_messages.py@@ -132,6 +132,35 @@ class FeishuPostMessageTests(unittest.IsolatedAsyncioTestCase):assert context.files is not Noneself.assertEqual(len(context.files), 1)self.assertEqual(context.files[0].name, "img_123.image")+ self.assertIs(context.is_ordinary_attachment, False)++ async def test_native_file_message_publishes_lark_attachment_fact(self):+ bot = self._make_bot()+ bot.check_authorization = lambda **kwargs: AuthResult(allowed=True, is_dm=True)+ bot.dispatch_text_command = AsyncMock(return_value=False)+ bot.on_message_callback = AsyncMock()+ event_data = {+ "sender": {+ "sender_type": "user",+ "sender_id": {"open_id": "ou_user"},+ },+ "message": {+ "chat_id": "oc_chat",+ "chat_type": "p2p",+ "message_id": "om_file",+ "message_type": "file",+ "content": json.dumps(+ {"file_key": "file-key", "file_name": "report.pdf"}+ ),+ },+ }++ await bot._async_handle_message(event_data)++ bot.on_message_callback.assert_awaited_once()+ context = bot.on_message_callback.await_args.args[0]+ self.assertEqual(context.platform, "lark")+ self.assertIs(context.is_ordinary_attachment, True)async def test_active_thread_requires_fresh_mention_when_require_mention_enabled(self):bot = FeishuBot(LarkConfig(app_id="app-id", app_secret="app-secret", require_mention=True))diff --git a/tests/test_memory_admission.py b/tests/test_memory_admission.pyindex f5358d508..fc269bbcc 100644--- a/tests/test_memory_admission.py+++ b/tests/test_memory_admission.py@@ -320,7 +320,7 @@ def test_missing_multimodal_skips_attachment_only_turn() -> None:{"is_dm": False},{"is_ordinary_attachment": False},{"is_ordinary_attachment": None},- {"platform": "discord", "is_ordinary_attachment": True},+ {"platform": "email", "is_ordinary_attachment": True},],)def test_denied_attachment_turn_never_reads_the_lease(diff --git a/tests/test_memory_slice3.py b/tests/test_memory_slice3.pyindex b78fccd26..175c14085 100644--- a/tests/test_memory_slice3.py+++ b/tests/test_memory_slice3.py@@ -33,11 +33,15 @@ from core.memory.runtime import MemoryRuntimefrom core.memory.store import MemoryStorefrom modules.im.base import FileAttachment, MessageContextfrom modules.im.message_facts import (+ is_ordinary_discord_attachment,is_ordinary_discord_text,+ is_ordinary_feishu_attachment,is_ordinary_feishu_text,is_ordinary_slack_attachment,is_ordinary_slack_text,+ is_ordinary_telegram_attachment,is_ordinary_telegram_text,+ is_ordinary_wechat_attachment,is_ordinary_wechat_text,)@@ -1508,6 +1512,164 @@ def test_im_adapters_normalize_native_ordinary_text_facts() -> None:assert is_ordinary_wechat_text({"item_list": [{"type": 1, "ref_msg": {"title": "quoted"}}]}, None) is False+def test_im_adapters_normalize_native_ordinary_attachment_facts() -> None:+ """MEMORY-IM-ATTACH-005..008: adapters publish only native ordinary shares."""++ discord_file = FileAttachment(+ name="diagram.png",+ mimetype="image/png",+ url="https://cdn.discord.test/diagram.png",+ )+ discord_message = SimpleNamespace(+ author=SimpleNamespace(bot=False),+ edited_at=None,+ attachments=[object()],+ embeds=[],+ components=[],+ stickers=[],+ sticker_items=[],+ webhook_id=None,+ flags=SimpleNamespace(forwarded=False),+ message_snapshots=(),+ is_system=lambda: False,+ )+ assert is_ordinary_discord_attachment(discord_message, [discord_file]) is True+ for field, value in (+ ("embeds", [object()]),+ ("components", [object()]),+ ("sticker_items", [object()]),+ ("webhook_id", "webhook-1"),+ ("message_snapshots", [object()]),+ ):+ setattr(discord_message, field, value)+ assert is_ordinary_discord_attachment(discord_message, [discord_file]) is False+ setattr(discord_message, field, None)+ discord_message.author.bot = True+ assert is_ordinary_discord_attachment(discord_message, [discord_file]) is False++ telegram_file = FileAttachment(+ name="telegram-file.bin",+ mimetype="application/octet-stream",+ url="native-file",+ )+ for native_field, native_value in (+ ("document", {"file_id": "document"}),+ ("photo", [{"file_id": "small"}, {"file_id": "large"}]),+ ("voice", {"file_id": "voice"}),+ ("audio", {"file_id": "audio"}),+ ):+ telegram_message = {+ "from": {"id": 42, "is_bot": False},+ "media_group_id": "album-1",+ native_field: native_value,+ }+ assert is_ordinary_telegram_attachment(telegram_message, [telegram_file]) is True+ for rejected_field in ("video", "animation", "sticker"):+ telegram_message = {+ "from": {"id": 42, "is_bot": False},+ "document": {"file_id": "document"},+ rejected_field: {"file_id": "decorated"},+ }+ assert is_ordinary_telegram_attachment(telegram_message, [telegram_file]) is False+ telegram_message = {+ "from": {"id": 42, "is_bot": False},+ "document": {"file_id": "document"},+ "forward_origin": {"type": "user"},+ }+ assert is_ordinary_telegram_attachment(telegram_message, [telegram_file]) is False++ feishu_file = FileAttachment(+ name="report.pdf",+ mimetype="application/octet-stream",+ url="https://open.feishu.test/report.pdf",+ )+ feishu_event = {+ "sender": {"sender_type": "user"},+ "message": {"message_type": "file"},+ }+ assert (+ is_ordinary_feishu_attachment(+ feishu_event,+ {"file_key": "file-key", "file_name": "report.pdf"},+ [feishu_file],+ shared_text=None,+ )+ is True+ )+ assert (+ is_ordinary_feishu_attachment(+ feishu_event,+ {"file_key": ""},+ [feishu_file],+ shared_text=None,+ )+ is False+ )+ feishu_event["message"]["message_type"] = "image"+ assert (+ is_ordinary_feishu_attachment(+ feishu_event,+ {"image_key": "image-key"},+ [feishu_file],+ shared_text=None,+ )+ is True+ )+ feishu_event["message"]["message_type"] = "media"+ assert (+ is_ordinary_feishu_attachment(+ feishu_event,+ {"file_key": "media-key"},+ [feishu_file],+ shared_text=None,+ )+ is False+ )++ wechat_files = [+ FileAttachment(name="voice.silk", mimetype="audio/silk", url="voice-query"),+ FileAttachment(name="video.mp4", mimetype="video/mp4", url="video-query"),+ ]+ wechat_message = {+ "from_user_id": "user-1",+ "item_list": [+ {"type": 1, "text_item": {"text": "remember these"}},+ {+ "type": 3,+ "voice_item": {"media": {"encrypt_query_param": "voice-query"}},+ },+ {+ "type": 5,+ "video_item": {"media": {"encrypt_query_param": "video-query"}},+ },+ ],+ }+ assert is_ordinary_wechat_attachment(wechat_message, wechat_files) is True+ wechat_message["item_list"][0]["ref_msg"] = {"title": "forwarded"}+ assert is_ordinary_wechat_attachment(wechat_message, wechat_files) is False+ for item_type, media_field in (+ (2, "image_item"),+ (3, "voice_item"),+ (4, "file_item"),+ (5, "video_item"),+ ):+ direct_message = {+ "item_list": [+ {+ "type": item_type,+ media_field: {+ "media": {"encrypt_query_param": "native-media"}+ },+ }+ ]+ }+ assert is_ordinary_wechat_attachment(direct_message, wechat_files) is True+ direct_message["item_list"][0][media_field]["media"][+ "encrypt_query_param"+ ] = ""+ assert is_ordinary_wechat_attachment(direct_message, wechat_files) is False++def _slack_dm_event(**overrides) -> dict:"""Return a real-shaped Slack ``message`` event for a DM typed in a client.diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.pyindex ad3cb8992..9ef8024b8 100644--- a/tests/test_telegram_bot.py+++ b/tests/test_telegram_bot.py@@ -210,6 +210,27 @@ def test_extract_files_includes_voice_and_audio_messages() -> None:]+def test_photo_context_publishes_ordinary_attachment_fact_from_largest_photo() -> None:+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))+ context = bot._build_message_context(+ {+ "message_id": 79,+ "chat": {"id": 42, "type": "private"},+ "from": {"id": 42, "is_bot": False},+ "media_group_id": "album-1",+ "photo": [+ {"file_id": "small", "file_size": 10},+ {"file_id": "large", "file_size": 42},+ ],+ }+ )++ assert context is not None+ assert context.is_ordinary_attachment is True+ assert context.files is not None+ assert [file.url for file in context.files] == ["large"]++def test_plain_group_sessions_are_channel_scoped() -> None:bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))diff --git a/tests/test_ui_memory_routes.py b/tests/test_ui_memory_routes.pyindex 850a4f01f..3fba4ca07 100644--- a/tests/test_ui_memory_routes.py+++ b/tests/test_ui_memory_routes.py@@ -67,7 +67,12 @@ def test_memory_rebuild_result_preserves_closed_preflight_diagnostic() -> None:("enabled_platforms", "expected"),[(["slack"], True),- (["discord"], False),+ (["discord"], True),+ (["telegram"], True),+ (["lark"], True),+ (["wechat"], True),+ (["feishu"], False),+ (["email"], False),(["discord", "slack"], True),([], False),],diff --git a/tests/test_wechat_bot.py b/tests/test_wechat_bot.pyindex 48b26bab5..1c8f0b7aa 100644--- a/tests/test_wechat_bot.py+++ b/tests/test_wechat_bot.py@@ -470,6 +470,37 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):context = bot.on_message_callback.await_args.args[0] # type: ignore[union-attr]self.assertFalse(context.is_ordinary_text)+ async def test_direct_voice_and_video_publish_ordinary_attachment_fact(self):+ bot = self._make_bot()+ bot.check_authorization = lambda **kwargs: AuthResult(allowed=True, is_dm=True)+ bot.dispatch_text_command = AsyncMock(return_value=False)+ bot.on_message_callback = AsyncMock()+ message = {+ "message_id": "mid-media",+ "from_user_id": "user-1",+ "item_list": [+ {+ "type": 3,+ "voice_item": {+ "media": {"encrypt_query_param": "voice-query"}+ },+ },+ {+ "type": 5,+ "video_item": {+ "media": {"encrypt_query_param": "video-query"}+ },+ },+ ],+ }++ await bot._process_inbound_message(message)+ await asyncio.gather(*tuple(bot._message_callback_tasks))++ context = bot.on_message_callback.await_args.args[0] # type: ignore[union-attr]+ self.assertIs(context.is_ordinary_attachment, True)+ self.assertEqual([file.mimetype for file in context.files or []], ["audio/silk", "video/mp4"])+async def test_process_inbound_message_sends_pending_bind_menu_hint_once(self):SettingsStore.reset_instance()store = SettingsStore.get_instance()