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 Slack attachments (#1466)
rkrkrkk063aebd29713
diff --git a/core/controller.py b/core/controller.pyindex 1cfc7fb6f..9666c3e16 100644--- a/core/controller.py+++ b/core/controller.py@@ -8,7 +8,7 @@ import threadingimport timefrom collections.abc import Awaitable, Callablefrom copy import deepcopy-from dataclasses import replace+from dataclasses import dataclass, replacefrom pathlib import Pathfrom typing import Optional, Dict, Any, TypeVarfrom config import paths@@ -50,10 +50,16 @@ from core.show_git import ShowGitCheckpointServicefrom core.update_checker import UpdateCheckerfrom core.watches import ManagedWatchServicefrom core.vibe_agents import VibeAgent, VibeAgentStore-from core.memory import CaptureReceipt, CaptureRequest, CaptureSkipped-from core.memory.admission import CaptureAdmission, InboundTurnFacts+from core.memory import CaptureAccepted, CaptureReceipt, CaptureRequest, CaptureSkipped+import core.memory.admission as memory_admission+from core.memory.admission import (+ WORKBENCH_PLATFORM,+ CaptureAdmission,+ InboundTurnFacts,+)from core.memory.blocking import run_blockingfrom core.memory.operation_lock import MemoryOperationBusy, MemoryOperationLease+from core.memory_telemetry import log_attachment_capturefrom vibe.i18n import get_supported_languages, t as i18n_tlogger = logging.getLogger(__name__)@@ -62,6 +68,24 @@ _RUNTIME_WORK_SHUTDOWN_GRACE_SECONDS = 10.0_MemorySessionLifecycleResult = TypeVar("_MemorySessionLifecycleResult")+@dataclass+class _MemoryAttachmentCaptureReservation:+ """Single-owner bridge from SessionTurn registration to Memory execution."""++ module: object+ token: object+ config_generation: int | None+ active: bool = True++ def release(self) -> None:+ if not self.active:+ return+ self.active = False+ cancel = getattr(self.module, "cancel_capture_reservation", None)+ if callable(cancel):+ cancel(self.token)++class _SettingsUserBindings:"""Answer Memory's binding question from the per-platform settings stores."""@@ -1858,6 +1882,9 @@ class Controller:*,text: object = None,session_id: object = None,+ attachment_lease: object = None,+ attachment_capture_status: object = None,+ attachment_config_generation: object = None,include_workdir: bool = True,) -> InboundTurnFacts:payload = context.platform_specific if isinstance(context.platform_specific, dict) else {}@@ -1877,6 +1904,10 @@ class Controller:files=getattr(context, "files", None),is_dm=payload.get("is_dm") is True,is_ordinary_text=context.is_ordinary_text,+ is_ordinary_attachment=context.is_ordinary_attachment,+ attachment_lease=attachment_lease,+ attachment_capture_status=attachment_capture_status,+ attachment_config_generation=attachment_config_generation,memory_enabled=bool(getattr(getattr(getattr(self, "config", None), "memory", None), "enabled", False)),@@ -1887,6 +1918,63 @@ class Controller:self._memory_turn_facts(context, include_workdir=False))+ def reserve_memory_attachment_capture(+ self,+ context: MessageContext,+ session_id: str,+ ) -> object | None:+ """Register exact-session capture order using local facts only."""++ admission = self._memory_admission()+ facts = self._memory_turn_facts(+ context,+ text="",+ session_id=session_id,+ include_workdir=False,+ )+ if not admission.admits_attachment_turn(facts):+ return None+ runtime = getattr(self, "memory_runtime", None)+ module = getattr(runtime, "module", None)+ reserve = getattr(module, "reserve_capture_admission", None)+ principal_id = admission.principal_for(facts)+ project_id = admission.project_for(facts)+ if (+ not callable(reserve)+ or not isinstance(principal_id, str)+ or not isinstance(project_id, str)+ ):+ return None+ read_generation = getattr(+ runtime,+ "attachment_capture_config_generation",+ None,+ )+ generation = None+ try:+ observed_generation = read_generation() if callable(read_generation) else None+ except Exception:+ observed_generation = None+ if (+ not isinstance(observed_generation, bool)+ and isinstance(observed_generation, int)+ and observed_generation >= 0+ ):+ generation = observed_generation+ try:+ token = reserve(+ principal_id=principal_id,+ project_id=project_id,+ session_id=session_id,+ )+ except Exception:+ return None+ return _MemoryAttachmentCaptureReservation(+ module=module,+ token=token,+ config_generation=generation,+ )+def memory_principal_for_context(self, context: MessageContext) -> Optional[str]:return self._memory_admission().principal_for(self._memory_turn_facts(context, include_workdir=False)@@ -2280,6 +2368,12 @@ class Controller:context: MessageContext,text: str,session_id: str,+ *,+ attachment_lease: object = None,+ attachment_reservation: object = None,+ attachment_config_generation: int | None = None,+ attachment_text_only: bool = False,+ admission_ready: asyncio.Event | None = None,) -> Awaitable[None]:"""Submit one eligible attributed human turn after session resolution.@@ -2292,6 +2386,11 @@ class Controller:context,text,session_id,+ attachment_lease=attachment_lease,+ attachment_reservation=attachment_reservation,+ attachment_config_generation=attachment_config_generation,+ attachment_text_only=attachment_text_only,+ admission_ready=admission_ready,observed_runtime=getattr(self, "memory_runtime", None),)@@ -2301,14 +2400,162 @@ class Controller:text: str,session_id: str,*,+ attachment_lease: object = None,+ attachment_reservation: object = None,+ attachment_config_generation: int | None = None,+ attachment_text_only: bool = False,+ admission_ready: asyncio.Event | None = None,observed_runtime: object,) -> None:- facts = self._memory_turn_facts(context, text=text, session_id=session_id)- request = self._memory_admission().decide(facts)+ reservation = (+ attachment_reservation+ if isinstance(+ attachment_reservation,+ _MemoryAttachmentCaptureReservation,+ )+ else None+ )+ if reservation is not None:+ attachment_config_generation = reservation.config_generation+ admission = self._memory_admission()+ facts = self._memory_turn_facts(+ context,+ text=text,+ session_id=session_id,+ attachment_lease=attachment_lease,+ attachment_config_generation=attachment_config_generation,+ )+ try:+ if admission.admits_attachment_turn(facts):+ if reservation is None:+ await self._capture_user_memory_decided(+ admission,+ self._memory_attachment_unavailable(facts),+ attachment_lease=None,+ observed_runtime=observed_runtime,+ )+ return+ principal_id = admission.principal_for(facts)+ project_id = admission.project_for(facts)+ module = getattr(observed_runtime, "module", None)+ acquire_admission = getattr(module, "capture_admission", None)+ if (+ isinstance(principal_id, str)+ and isinstance(project_id, str)+ and callable(acquire_admission)+ and (reservation is None or reservation.module is module)+ ):+ async with acquire_admission(+ principal_id=principal_id,+ project_id=project_id,+ session_id=session_id,+ reservation=(+ reservation.token if reservation is not None else None+ ),+ ) as held_admission:+ if admission_ready is not None:+ admission_ready.set()+ await self._capture_user_memory_decided(+ admission,+ (+ self._memory_attachment_unavailable(facts)+ if attachment_text_only+ else facts+ ),+ attachment_lease=(+ None if attachment_text_only else attachment_lease+ ),+ observed_runtime=observed_runtime,+ held_admission=held_admission,+ )+ return+ if admission_ready is not None:+ admission_ready.set()+ await self._capture_user_memory_decided(+ admission,+ facts,+ attachment_lease=attachment_lease,+ observed_runtime=observed_runtime,+ )+ finally:+ if reservation is not None:+ reservation.release()+ if admission_ready is not None:+ admission_ready.set()++ @staticmethod+ def _memory_attachment_unavailable(+ facts: InboundTurnFacts,+ ) -> InboundTurnFacts:+ """Finalize an unavailable attachment set while preserving its caption."""++ return replace(+ facts,+ attachment_lease=None,+ attachment_capture_status="unavailable",+ attachment_config_generation=None,+ )++ async def _capture_user_memory_decided(+ self,+ admission: CaptureAdmission,+ facts: InboundTurnFacts,+ *,+ attachment_lease: object,+ observed_runtime: object,+ held_admission: object = None,+ ) -> None:+ platform = CaptureAdmission.platform_of(facts)+ if admission.admits_attachment_turn(facts):+ status = facts.attachment_capture_status+ attachment_selection = None+ if status not in {"ready", "not_configured", "unavailable"}:+ status = "not_configured"+ if (+ platform == WORKBENCH_PLATFORM+ or facts.attachment_config_generation is not None+ ):+ status = "unavailable"+ read_status = getattr(+ observed_runtime,+ "attachment_capture_status",+ None,+ )+ if callable(read_status):+ try:+ observed_status = await read_status()+ except Exception:+ observed_status = "unavailable"+ if observed_status in {+ "ready",+ "not_configured",+ "unavailable",+ }:+ status = observed_status+ if status == "ready" and platform != WORKBENCH_PLATFORM:+ try:+ attachment_selection = await run_blocking(+ memory_admission.select_memory_attachments,+ facts.attachment_lease,+ )+ except Exception as error:+ logger.warning(+ "memory_attachment_selection_failed "+ "platform=%s count=%d error_type=%s",+ platform,+ len(facts.files or ()),+ type(error).__name__,+ )+ status = "unavailable"+ facts = replace(+ facts,+ attachment_capture_status=status,+ attachment_selection=attachment_selection,+ )+ request = admission.decide(facts)if not isinstance(request, CaptureRequest):return- platform = CaptureAdmission.platform_of(facts)started_at = time.monotonic()try:if self._memory_factory_reset_pending(observed_runtime) or observed_runtime is None:@@ -2325,7 +2572,44 @@ class Controller:or not runtime.available):return- await runtime.module.capture(request)+ if request.attachments and platform != WORKBENCH_PLATFORM:+ read_generation = getattr(+ runtime,+ "attachment_capture_config_generation",+ None,+ )+ current_generation = (+ read_generation() if callable(read_generation) else None+ )+ if (+ isinstance(current_generation, bool)+ or current_generation != request.attachment_config_generation+ ):+ request = replace(+ request,+ attachments=(),+ attachment_config_generation=None,+ )+ if not request.text.strip():+ return+ capture_options = {}+ if held_admission is not None:+ capture_options["admission"] = held_admission+ if request.attachments and attachment_lease is not None:+ capture_options["source_lease"] = attachment_lease+ result = await runtime.module.capture(+ request,+ **capture_options,+ )+ if platform != WORKBENCH_PLATFORM and isinstance(facts.files, (list, tuple)):+ total = len(facts.files)+ if total:+ captured = (+ result.captured_attachment_count+ if isinstance(result, CaptureAccepted)+ else 0+ )+ log_attachment_capture(platform, total, captured)logger.info("Memory capture platform=%s latency_ms=%d",platform,@@ -2940,13 +3224,22 @@ class Controller:"Memory factory reset",timeout=None,)- async def _drain_memory_capture_tasks() -> None:+ async def _cancel_memory_capture_tasks() -> None:handler = getattr(self, "message_handler", None)- drain = getattr(handler, "drain_memory_capture_tasks", None)- if callable(drain):- await drain()-- _stop_loop_coroutine(_drain_memory_capture_tasks(), "Memory capture tasks")+ quiesce = getattr(handler, "quiesce_memory_capture_tasks", None)+ if callable(quiesce):+ quiesce()+ cancel = getattr(handler, "cancel_memory_capture_tasks", None)+ if callable(cancel):+ await cancel()++ # Close registration and sweep the resulting closed task set in one+ # event-loop turn. This does not depend on platform shutdown ordering.+ _stop_loop_coroutine(+ _cancel_memory_capture_tasks(),+ "Memory capture tasks",+ timeout=None,+ )memory_runtime = getattr(self, "memory_runtime", None)if memory_runtime is not None:_stop_loop_coroutine(memory_runtime.close(), "Memory runtime")diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex c8b547cde..e6c63576c 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -49,6 +49,10 @@ def _target_agent_variant(value: Any, backend: Optional[str], agent_name: Optionreturn None if variant in sentinel_values else variant+class _MemoryCaptureRegistrationClosed(Exception):+ """Internal signal that shutdown closed attachment capture registration."""++class MessageHandler(BaseHandler):"""Handles message routing and Claude communication"""@@ -62,6 +66,7 @@ class MessageHandler(BaseHandler):self.session_handler = None # Will be set after creationself.receiver_tasks = controller.receiver_tasksself._memory_capture_tasks: set[asyncio.Task[Any]] = set()+ self._memory_capture_registration_open = Truedef set_session_handler(self, session_handler):"""Set reference to session handler"""@@ -72,6 +77,7 @@ class MessageHandler(BaseHandler):task: asyncio.Task[Any],*,lifecycle_admission: Any = None,+ attachment_lease: Any = None,) -> None:"""Retain a best-effort capture until asyncio reports its completion."""@@ -85,6 +91,9 @@ class MessageHandler(BaseHandler):except Exception:logger.warning("Memory capture task failed", exc_info=True)finally:+ release_attachment = getattr(attachment_lease, "release", None)+ if callable(release_attachment):+ release_attachment()release = getattr(lifecycle_admission, "release", None)if callable(release):release()@@ -107,6 +116,25 @@ class MessageHandler(BaseHandler):return Nonereturn await acquire(session_id)+ def _memory_session_lifecycle_epoch(self, session_id: str) -> int:+ manager = getattr(self.controller, "session_turns", None)+ read_epoch = getattr(manager, "session_lifecycle_epoch", None)+ if not callable(read_epoch):+ return 0+ epoch = read_epoch(session_id)+ return epoch if isinstance(epoch, int) and not isinstance(epoch, bool) else 0++ def _memory_session_lifecycle_epoch_matches(+ self,+ session_id: str,+ expected_epoch: int,+ ) -> bool:+ manager = getattr(self.controller, "session_turns", None)+ matches = getattr(manager, "session_lifecycle_epoch_matches", None)+ if callable(matches):+ return bool(matches(session_id, expected_epoch))+ return self._memory_session_lifecycle_epoch(session_id) == expected_epoch+async def drain_memory_capture_tasks(self) -> None:"""Settle captures accepted before controller shutdown closes Memory."""@@ -115,6 +143,21 @@ class MessageHandler(BaseHandler):await asyncio.gather(*tasks, return_exceptions=True)self._memory_capture_tasks.difference_update(tasks)+ async def cancel_memory_capture_tasks(self) -> None:+ """Cancel and join captures before the controller event loop closes."""++ while self._memory_capture_tasks:+ tasks = tuple(self._memory_capture_tasks)+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)+ self._memory_capture_tasks.difference_update(tasks)++ def quiesce_memory_capture_tasks(self) -> None:+ """Close the loop-owned registration gate before shutdown sweeps tasks."""++ self._memory_capture_registration_open = False+async def handle_user_message(self, context: MessageContext, message: str):"""Process regular human-originated messages and route to configured agent."""await self._handle_turn(context, message, source=self.TURN_SOURCE_HUMAN)@@ -294,6 +337,12 @@ class MessageHandler(BaseHandler):mirror_harness_inbound(context, message)base_session_id, working_path, composite_key = self.session_handler.get_session_info(context, source=source)+ memory_session_id = base_session_id+ memory_session_pre_epoch = (+ self._memory_session_lifecycle_epoch(memory_session_id)+ if is_human and context.files+ else None+ )payload = dict(context.platform_specific or {})payload["turn_source"] = sourcepayload["turn_base_session_id"] = base_session_id@@ -302,26 +351,29 @@ class MessageHandler(BaseHandler):)context.platform_specific = payload- # Memory capture is deliberately outside the agent turn. Native IM- # dedup has already claimed this message and the stable base session- # is now known, so the controller can make one best-effort capture- # decision without delaying dispatch.- if is_human:+ # Text-only turns keep the original early capture path. Attachment+ # turns defer only until the shared materializer has produced a+ # descriptor-backed lease.+ if is_human and not context.files:capture_memory = getattr(self.controller, "capture_user_memory", None)if callable(capture_memory):turn_lifecycle_admission = await self._acquire_memory_capture_admission(- base_session_id,+ memory_session_id,turn_lifecycle_admission,)- capture_task = asyncio.create_task(- capture_memory(context, control_message, base_session_id),- name="memory-capture",- )- self._track_memory_capture_task(- capture_task,- lifecycle_admission=turn_lifecycle_admission,- )- turn_lifecycle_admission = None+ if self._memory_capture_registration_open:+ capture_task = asyncio.create_task(+ capture_memory(context, control_message, memory_session_id),+ name="memory-capture",+ )+ self._track_memory_capture_task(+ capture_task,+ lifecycle_admission=turn_lifecycle_admission,+ )+ turn_lifecycle_admission = None+ elif turn_lifecycle_admission is not None:+ turn_lifecycle_admission.release()+ turn_lifecycle_admission = Nonereply_anchor_base_session_id = payload.get("reply_anchor_base_session_id")if reply_anchor_base_session_id and reply_anchor_base_session_id != base_session_id:@@ -723,6 +775,123 @@ class MessageHandler(BaseHandler):len(processed_files),)+ # Memory capture remains best effort and outside the Agent turn, but+ # file turns start only after the one shared download has produced an+ # immutable lease. Authorization precedes retaining a Memory consumer.+ if is_human and context.files:+ capture_memory = getattr(self.controller, "capture_user_memory", None)+ if callable(capture_memory):+ memory_attachment_lease = None+ memory_capture_reservation = None+ attachment_text_only = False+ capture_task = None+ try:+ turn_lifecycle_admission = await self._acquire_memory_capture_admission(+ memory_session_id,+ turn_lifecycle_admission,+ )+ if not self._memory_capture_registration_open:+ raise _MemoryCaptureRegistrationClosed+ stale_attachment_capture = bool(+ memory_session_pre_epoch is not None+ and not self._memory_session_lifecycle_epoch_matches(+ memory_session_id,+ memory_session_pre_epoch,+ )+ )+ reserve_attachment = getattr(+ self.controller,+ "reserve_memory_attachment_capture",+ None,+ )+ memory_capture_reservation = (+ reserve_attachment(context, memory_session_id)+ if callable(reserve_attachment)+ and not stale_attachment_capture+ else None+ )+ attachment_config_generation = getattr(+ memory_capture_reservation,+ "config_generation",+ None,+ )+ if (+ not isinstance(attachment_config_generation, bool)+ and isinstance(attachment_config_generation, int)+ and attachment_config_generation >= 0+ and attachment_lease is not None+ ):+ try:+ memory_attachment_lease = attachment_lease.retain()+ except Exception as error:+ attachment_text_only = True+ logger.warning(+ "Memory attachment lease could not be retained; "+ "capturing text only error_type=%s",+ type(error).__name__,+ )+ capture_options = {+ "attachment_reservation": memory_capture_reservation,+ "attachment_config_generation": attachment_config_generation,+ }+ if memory_attachment_lease is not None:+ capture_options["attachment_lease"] = memory_attachment_lease+ if attachment_text_only:+ capture_options["attachment_text_only"] = True+ capture = capture_memory(+ context,+ control_message,+ memory_session_id,+ **capture_options,+ )+ capture_task = asyncio.create_task(+ capture,+ name="memory-capture",+ )+ except _MemoryCaptureRegistrationClosed:+ release_admission = getattr(+ turn_lifecycle_admission,+ "release",+ None,+ )+ if callable(release_admission):+ release_admission()+ turn_lifecycle_admission = None+ except BaseException as error:+ if capture_task is not None:+ capture_task.cancel()+ if memory_attachment_lease is not None:+ memory_attachment_lease.release()+ release_reservation = getattr(+ memory_capture_reservation,+ "release",+ None,+ )+ if callable(release_reservation):+ release_reservation()+ release_admission = getattr(+ turn_lifecycle_admission,+ "release",+ None,+ )+ if callable(release_admission):+ release_admission()+ turn_lifecycle_admission = None+ if not isinstance(error, Exception):+ raise+ logger.warning(+ "Memory capture task could not be scheduled",+ exc_info=True,+ )+ else:+ self._track_memory_capture_task(+ capture_task,+ attachment_lease=memory_attachment_lease,+ )+ if turn_lifecycle_admission is not None:+ turn_lifecycle_admission.release()+ turn_lifecycle_admission = None+if durable_ingress_enabled and not durable_delivery_owned:assert durable_dispatch_text is not Noneadmitted = await self._admit_human_delivery(diff --git a/core/memory/admission.py b/core/memory/admission.pyindex 1d614bc83..d3a90a9f3 100644--- a/core/memory/admission.py+++ b/core/memory/admission.py@@ -18,13 +18,21 @@ that raises is never an authorization grant.from __future__ import annotationsfrom dataclasses import dataclass+import loggingimport timefrom typing import Protocolfrom core.memory.attachments import workbench_capture_attachments+from core.memory.im_attachments import (+ IM_ATTACHMENT_CAPTURE_PLATFORMS,+ select_memory_attachments,+)from core.memory.types import CaptureAttachment, CaptureRequest, CaptureSkipped+logger = logging.getLogger(__name__)++WORKBENCH_PLATFORM = "avibe"IM_PLATFORMS = frozenset({"slack", "discord", "telegram", "lark", "feishu", "wechat"})ADMISSIBLE_PLATFORMS = IM_PLATFORMS | {WORKBENCH_PLATFORM}@@ -64,6 +72,11 @@ class InboundTurnFacts:files: object = Noneis_dm: bool = Falseis_ordinary_text: bool | None = None+ is_ordinary_attachment: bool | None = None+ attachment_lease: object = None+ attachment_capture_status: object = None+ attachment_config_generation: object = None+ attachment_selection: object = Nonememory_enabled: bool = False@@ -126,6 +139,20 @@ class CaptureAdmission:# failure into an implicit authorization grant.return False+ def admits_attachment_turn(self, facts: InboundTurnFacts) -> bool:+ """Authorize retaining an already-materialized IM lease for Memory."""++ platform = self.platform_of(facts)+ return bool(+ _asserted_true(facts.memory_enabled)+ and platform in IM_ATTACHMENT_CAPTURE_PLATFORMS+ and _nonempty_str(facts.message_id)+ and _nonempty_str(facts.session_id)+ and _asserted_true(facts.is_ordinary_attachment)+ and _has_native_files(facts.files)+ and self.admits(facts)+ )+def decide(self, facts: InboundTurnFacts) -> CaptureRequest | CaptureSkipped:"""Turn one classified turn into the capture it earns, or a skip."""@@ -144,18 +171,51 @@ class CaptureAdmission:project_id = self.project_for(facts)if project_id is None:return CaptureSkipped(reason="memory_invalid_input")+ if not isinstance(facts.text, str):+ return CaptureSkipped(reason="memory_invalid_input")workbench = platform == WORKBENCH_PLATFORM+ config_generation: int | None = None# Converted before the text check so an attachment-only turn is judged# on the uploads Memory can actually carry: a turn whose every upload# was filtered out would otherwise be enqueued with no text and no# attachment, giving the provider nothing to extract.- attachments = workbench_capture_attachments(facts.files) if workbench else ()- if not _is_ordinary_human_text(facts, attachments=attachments):- return CaptureSkipped(reason="memory_invalid_input")- if not workbench and bool(facts.files):- # IM attachments are out of scope; no provider-side download- # pipeline is exposed for them.- return CaptureSkipped(reason="memory_invalid_input")+ if workbench:+ attachments = workbench_capture_attachments(facts.files)+ if not _is_ordinary_human_text(facts, attachments=attachments):+ return CaptureSkipped(reason="memory_invalid_input")+ else:+ native_files = _native_file_count(facts.files)+ if native_files is None:+ return CaptureSkipped(reason="memory_invalid_input")+ attachments: tuple[CaptureAttachment, ...] = ()+ if native_files:+ if not self.admits_attachment_turn(facts):+ return CaptureSkipped(reason="memory_invalid_input")+ status = facts.attachment_capture_status+ config_generation = _attachment_config_generation(+ facts.attachment_config_generation+ )+ if status == "ready" and config_generation is not None:+ try:+ selection = facts.attachment_selection+ if selection is None:+ # Production IM callers precompute selection off the+ # event loop. This fallback serves direct callers only.+ selection = select_memory_attachments(facts.attachment_lease) # type: ignore[arg-type]+ except Exception as error:+ logger.warning(+ "memory_attachment_selection_failed "+ "platform=%s count=%d error_type=%s",+ platform,+ native_files,+ type(error).__name__,+ )+ else:+ attachments = selection.attachments+ if not facts.text.strip() and not attachments:+ return CaptureSkipped(reason="memory_invalid_input")+ elif not _asserted_true(facts.is_ordinary_text) or not facts.text.strip():+ return CaptureSkipped(reason="memory_invalid_input")source_prefix = "workbench" if workbench else f"im:{platform}"return CaptureRequest(@@ -167,6 +227,7 @@ class CaptureAdmission:text=facts.text,occurred_at_ms=int(time.time() * 1000),attachments=attachments,+ attachment_config_generation=config_generation,)@@ -187,6 +248,25 @@ def _asserted_true(value: object) -> bool:return value is True+def _attachment_config_generation(value: object) -> int | None:+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:+ return None+ return value+++def _native_file_count(value: object) -> int | None:+ if value is None:+ return 0+ if not isinstance(value, (list, tuple)):+ return None+ return len(value)+++def _has_native_files(value: object) -> bool:+ count = _native_file_count(value)+ return count is not None and count > 0++def _attributed_user_id(facts: InboundTurnFacts) -> str | None:"""Return the user this turn is attributed to, or None for a fallback id.diff --git a/core/memory/attachments.py b/core/memory/attachments.pyindex 072cd1b77..f6ff38e09 100644--- a/core/memory/attachments.py+++ b/core/memory/attachments.py@@ -39,8 +39,7 @@ if TYPE_CHECKING:MAX_PINNED_ATTACHMENTS = 8MAX_PINNED_ATTACHMENT_BYTES = 25 * 1024 * 1024MAX_PINNED_BUNDLE_BYTES = 100 * 1024 * 1024-# Delivery gate: PR4 flips this only after the IM admission/materialization path lands.-IM_ATTACHMENT_CAPTURE_AVAILABLE = False+IM_ATTACHMENT_CAPTURE_PLATFORMS = frozenset({"slack"})_COPY_CHUNK_BYTES = 1024 * 1024_MAX_ATTACHMENT_NAME_BYTES = 512diff --git a/core/memory/im_attachments.py b/core/memory/im_attachments.pyindex a56eff2df..a25068c04 100644--- a/core/memory/im_attachments.py+++ b/core/memory/im_attachments.py@@ -12,6 +12,7 @@ from core.handlers.inbound_attachments import (open_leased_attachment_record,)from core.memory.attachments import (+ IM_ATTACHMENT_CAPTURE_PLATFORMS,MAX_PINNED_ATTACHMENTS,MAX_PINNED_ATTACHMENT_BYTES,MAX_PINNED_BUNDLE_BYTES,@@ -22,12 +23,12 @@ from core.memory.types import CaptureAttachmentAttachmentSkipReason = Literal["count_limit",+ "download_failed","file_too_large","bundle_too_large","unsupported_type",]-@dataclass(frozen=True, slots=True)class MemoryAttachmentSelection:attachments: tuple[CaptureAttachment, ...]diff --git a/core/memory/module.py b/core/memory/module.pyindex 313d56d5f..54e8c4722 100644--- a/core/memory/module.py+++ b/core/memory/module.py@@ -11,10 +11,11 @@ import unicodedataimport weakreffrom collections.abc import Awaitable, Callablefrom contextlib import asynccontextmanager+from dataclasses import replacefrom datetime import date, datetime, timezonefrom pathlib import Pathfrom time import monotonic-from typing import Any, AsyncIterator, Literal, TypeVar+from typing import TYPE_CHECKING, Any, AsyncIterator, Literal, TypeVarfrom config import pathsfrom core.memory.blocking import run_blocking@@ -66,6 +67,9 @@ from core.memory.types import ()from core.memory.worker import MemoryWorker, ProcessingEvent+if TYPE_CHECKING:+ from core.handlers.inbound_attachments import InboundAttachmentLease+MAX_CAPTURE_TEXT_BYTES = 32 * 1024MAX_CAPTURE_IDENTIFIER_BYTES = 1024@@ -84,6 +88,56 @@ PROVIDER_READ_TIMEOUT_SECONDS = 20.0CLEAR_DRAIN_TIMEOUT_SECONDS = 5.0+class _HeldCaptureAdmission:+ """One active claim on an exact-session capture fence."""++ def __init__(+ self,+ module: "MemoryModule",+ lock: asyncio.Lock,+ key: tuple[str, str, str],+ ) -> None:+ self.module = module+ self.lock = lock+ self.key = key+ self.active = True+++class _CaptureReservation:+ """One O(1) FIFO registration for exact-session capture work."""++ def __init__(+ self,+ module: "MemoryModule",+ key: tuple[str, str, str],+ predecessor: asyncio.Future[None] | None,+ ) -> None:+ self.module = module+ self.key = key+ self.predecessor = predecessor+ self.completion = asyncio.get_running_loop().create_future()+ self.active = True++ async def wait_for_turn(self) -> None:+ if self.predecessor is not None:+ await asyncio.shield(self.predecessor)++ def complete(self) -> None:+ if not self.active:+ return+ self.active = False+ if self.predecessor is None or self.predecessor.done():+ self._resolve_completion()+ return+ self.predecessor.add_done_callback(+ lambda _predecessor: self._resolve_completion()+ )++ def _resolve_completion(self) -> None:+ if not self.completion.done():+ self.completion.set_result(None)++logger = logging.getLogger(__name__)_SessionLifecycleResult = TypeVar("_SessionLifecycleResult")@@ -140,6 +194,9 @@ class MemoryModule:self._capture_admission_locks: weakref.WeakValueDictionary[tuple[str, str, str], asyncio.Lock] = weakref.WeakValueDictionary()+ self._capture_reservation_tails: dict[+ tuple[str, str, str], _CaptureReservation+ ] = {}self._invalid_capture_admission_lock = asyncio.Lock()self._clear_active = Falseself._retired = False@@ -283,6 +340,11 @@ class MemoryModule:timeout = _positive_timeout(deadline_seconds)loop = asyncio.get_running_loop()deadline = loop.time() + timeout+ barrier = self.reserve_capture_admission(+ principal_id=principal_id,+ project_id=project_id,+ session_id=raw_session_id,+ )admission_lock = self._capture_admission_lock(principal_id=principal_id,project_id=project_id,@@ -290,7 +352,11 @@ class MemoryModule:)acquired = Falsetry:- await asyncio.wait_for(admission_lock.acquire(), timeout=timeout)+ await self._wait_for_capture_reservation(barrier, deadline)+ await asyncio.wait_for(+ admission_lock.acquire(),+ timeout=max(deadline - loop.time(), 0.001),+ )acquired = Truereturn await self._final_flush_under_admission(principal_id=principal_id,@@ -303,6 +369,7 @@ class MemoryModule:finally:if acquired:admission_lock.release()+ self.cancel_capture_reservation(barrier)async def run_session_lifecycle(self,@@ -320,19 +387,29 @@ class MemoryModule:timeout = _positive_timeout(deadline_seconds)loop = asyncio.get_running_loop()deadline = loop.time() + timeout+ barrier = self.reserve_capture_admission(+ principal_id=principal_id,+ project_id=project_id,+ session_id=raw_session_id,+ )admission_lock = self._capture_admission_lock(principal_id=principal_id,project_id=project_id,session_id=raw_session_id,)+ acquired = Falsetry:- await asyncio.wait_for(admission_lock.acquire(), timeout=timeout)- except asyncio.TimeoutError as error:- raise MemorySessionLifecycleBusyError(- "memory capture admission did not quiesce before the deadline"- ) from error-- try:+ try:+ await self._wait_for_capture_reservation(barrier, deadline)+ await asyncio.wait_for(+ admission_lock.acquire(),+ timeout=max(deadline - loop.time(), 0.001),+ )+ acquired = True+ except asyncio.TimeoutError as error:+ raise MemorySessionLifecycleBusyError(+ "memory capture admission did not quiesce before the deadline"+ ) from errorawait self._final_flush_under_admission(principal_id=principal_id,project_id=project_id,@@ -341,7 +418,9 @@ class MemoryModule:)return await operation()finally:- admission_lock.release()+ if acquired:+ admission_lock.release()+ self.cancel_capture_reservation(barrier)async def run_session_scopes_lifecycle(self,@@ -372,6 +451,14 @@ class MemoryModule:timeout = _positive_timeout(deadline_seconds)loop = asyncio.get_running_loop()deadline = loop.time() + timeout+ barriers = [+ self.reserve_capture_admission(+ principal_id=principal_id,+ project_id=project_id,+ session_id=raw_session_id,+ )+ for principal_id, project_id in canonical_scopes+ ]locks = [self._capture_admission_lock(principal_id=principal_id,@@ -382,32 +469,27 @@ class MemoryModule:]acquired: list[asyncio.Lock] = []try:- for admission_lock in locks:- remaining = deadline - loop.time()- if remaining <= 0:- raise asyncio.TimeoutError- await asyncio.wait_for(admission_lock.acquire(), timeout=remaining)- acquired.append(admission_lock)- except asyncio.TimeoutError as error:- for admission_lock in reversed(acquired):- admission_lock.release()- raise MemorySessionLifecycleBusyError(- "memory capture admission did not quiesce before the deadline"- ) from error- except asyncio.CancelledError:- for admission_lock in reversed(acquired):- admission_lock.release()- raise-- try:+ try:+ for barrier in barriers:+ await self._wait_for_capture_reservation(barrier, deadline)+ for admission_lock in locks:+ remaining = deadline - loop.time()+ if remaining <= 0:+ raise asyncio.TimeoutError+ await asyncio.wait_for(admission_lock.acquire(), timeout=remaining)+ acquired.append(admission_lock)+ except asyncio.TimeoutError as error:+ raise MemorySessionLifecycleBusyError(+ "memory capture admission did not quiesce before the deadline"+ ) from errorflush_succeeded = Truefor principal_id, project_id in canonical_scopes:flush_succeeded = (await self._final_flush_under_admission(- principal_id=principal_id,- project_id=project_id,- raw_session_id=raw_session_id,- deadline=deadline,+ principal_id=principal_id,+ project_id=project_id,+ raw_session_id=raw_session_id,+ deadline=deadline,)and flush_succeeded)@@ -418,6 +500,8 @@ class MemoryModule:finally:for admission_lock in reversed(acquired):admission_lock.release()+ for barrier in reversed(barriers):+ self.cancel_capture_reservation(barrier)async def _final_flush_under_admission(self,@@ -462,7 +546,13 @@ class MemoryModule:self._provider = providerself._worker.replace_provider(provider)- async def capture(self, request: CaptureRequest) -> CaptureReceipt:+ async def capture(+ self,+ request: CaptureRequest,+ *,+ source_lease: InboundAttachmentLease | None = None,+ admission: object = None,+ ) -> CaptureReceipt:"""Validate and persist one source capture without touching the provider."""if self._retired:@@ -472,53 +562,244 @@ class MemoryModule:if self._clear_active or self._is_maintenance_open():return CaptureSkipped(reason="memory_clear_failed")- admission_lock = (- self._capture_admission_lock(- principal_id=request.principal_id,- project_id=request.project_id,- session_id=request.session_id,+ admission_lock = self._capture_lock_for_request(request)+ if admission is None:+ key = self._capture_admission_key(+ principal_id=getattr(request, "principal_id", None),+ project_id=getattr(request, "project_id", None),+ session_id=getattr(request, "session_id", None),)- if isinstance(request, CaptureRequest)- else self._invalid_capture_admission_lock+ if key is not None:+ reservation = self.reserve_capture_admission(+ principal_id=key[0],+ project_id=key[1],+ session_id=key[2],+ )+ async with self.capture_admission(+ principal_id=key[0],+ project_id=key[1],+ session_id=key[2],+ reservation=reservation,+ ):+ return await self._capture_with_admission(+ request,+ source_lease=source_lease,+ )+ async with admission_lock:+ return await self._capture_with_admission(+ request,+ source_lease=source_lease,+ )+ if not self._owns_capture_admission(admission, request, admission_lock):+ return await self._skipped_with_missed("memory_invalid_input")+ return await self._capture_with_admission(+ request,+ source_lease=source_lease,)- async with admission_lock:- async with self._root_lifecycle_lock():- if self._retired:- return CaptureSkipped(reason="memory_operation_in_progress")- if not self._is_enabled():- return CaptureSkipped(reason="memory_disabled")- if self._clear_active or self._is_maintenance_open():- return CaptureSkipped(reason="memory_clear_failed")- if not isinstance(request, CaptureRequest):- return await self._skipped_with_missed("memory_invalid_input")- normalized_text = self._normalize_text(request.text)- validation_error = self._capture_validation_error(request, normalized_text)- if validation_error is not None:- return await self._skipped_with_missed(validation_error)+ @asynccontextmanager+ async def capture_admission(+ self,+ *,+ principal_id: str,+ project_id: str,+ session_id: str,+ reservation: object = None,+ ) -> AsyncIterator[_HeldCaptureAdmission]:+ """Acquire the exact-session fence before deferred capture work starts."""- try:- disk_free = int(await asyncio.to_thread(self._disk_free_bytes))- except Exception:- return await self._skipped_with_missed("memory_low_disk_space")- if disk_free < MIN_FREE_DISK_BYTES:- return await self._skipped_with_missed("memory_low_disk_space")- return await self._capture_under_root(request, normalized_text)+ key = (principal_id, project_id, session_id)+ lock = self._capture_admission_lock(+ principal_id=principal_id,+ project_id=project_id,+ session_id=session_id,+ )+ ticket = reservation if isinstance(reservation, _CaptureReservation) else None+ if reservation is not None and not self._owns_capture_reservation(ticket, key):+ self.cancel_capture_reservation(reservation)+ raise ValueError("invalid Memory capture reservation")+ acquired = False+ try:+ if ticket is not None:+ await ticket.wait_for_turn()+ await lock.acquire()+ acquired = True+ admission = _HeldCaptureAdmission(self, lock, key)+ yield admission+ finally:+ if acquired:+ admission.active = False+ lock.release()+ if ticket is not None:+ self.cancel_capture_reservation(ticket)++ def reserve_capture_admission(+ self,+ *,+ principal_id: str,+ project_id: str,+ session_id: str,+ ) -> object:+ """Register exact-session capture order without waiting for earlier work."""++ key = self._capture_admission_key(+ principal_id=principal_id,+ project_id=project_id,+ session_id=session_id,+ )+ if key is None:+ raise ValueError("invalid Memory capture reservation scope")+ tail = self._capture_reservation_tails.get(key)+ predecessor = tail.completion if tail is not None else None+ reservation = _CaptureReservation(self, key, predecessor)+ self._capture_reservation_tails[key] = reservation+ reservation.completion.add_done_callback(+ lambda _completion: self._retire_capture_reservation(key, reservation)+ )+ return reservation++ def cancel_capture_reservation(self, reservation: object) -> None:+ """Complete an owned reservation on cancellation or scheduling failure."""++ if isinstance(reservation, _CaptureReservation) and reservation.module is self:+ reservation.complete()++ async def _wait_for_capture_reservation(+ self,+ reservation: object,+ deadline: float,+ ) -> None:+ if not isinstance(reservation, _CaptureReservation):+ raise ValueError("invalid Memory capture reservation")+ if reservation.predecessor is None:+ return+ remaining = deadline - asyncio.get_running_loop().time()+ if remaining <= 0:+ raise asyncio.TimeoutError+ await asyncio.wait_for(+ asyncio.shield(reservation.predecessor),+ timeout=remaining,+ )++ def _retire_capture_reservation(+ self,+ key: tuple[str, str, str],+ reservation: _CaptureReservation,+ ) -> None:+ if self._capture_reservation_tails.get(key) is reservation:+ self._capture_reservation_tails.pop(key, None)++ def _owns_capture_reservation(+ self,+ reservation: _CaptureReservation | None,+ key: tuple[str, str, str],+ ) -> bool:+ return bool(+ reservation is not None+ and reservation.active+ and reservation.module is self+ and reservation.key == key+ )++ async def _capture_with_admission(+ self,+ request: CaptureRequest,+ *,+ source_lease: InboundAttachmentLease | None,+ ) -> CaptureReceipt:+ async with self._root_lifecycle_lock():+ if self._retired:+ return CaptureSkipped(reason="memory_operation_in_progress")+ if not self._is_enabled():+ return CaptureSkipped(reason="memory_disabled")+ if self._clear_active or self._is_maintenance_open():+ return CaptureSkipped(reason="memory_clear_failed")+ if not isinstance(request, CaptureRequest):+ return await self._skipped_with_missed("memory_invalid_input")++ normalized_text = self._normalize_text(request.text)+ validation_error = self._capture_validation_error(request, normalized_text)+ if validation_error is not None:+ return await self._skipped_with_missed(validation_error)++ try:+ disk_free = int(await asyncio.to_thread(self._disk_free_bytes))+ except Exception:+ return await self._skipped_with_missed("memory_low_disk_space")+ if disk_free < MIN_FREE_DISK_BYTES:+ return await self._skipped_with_missed("memory_low_disk_space")+ return await self._capture_under_root(+ request,+ normalized_text,+ source_lease=source_lease,+ )++ def _capture_lock_for_request(self, request: object) -> asyncio.Lock:+ if not isinstance(request, CaptureRequest):+ return self._invalid_capture_admission_lock+ return self._capture_admission_lock(+ principal_id=request.principal_id,+ project_id=request.project_id,+ session_id=request.session_id,+ )++ def _owns_capture_admission(+ self,+ admission: object,+ request: object,+ lock: asyncio.Lock,+ ) -> bool:+ return bool(+ isinstance(admission, _HeldCaptureAdmission)+ and admission.active+ and admission.module is self+ and admission.lock is lock+ and isinstance(request, CaptureRequest)+ and admission.key+ == (request.principal_id, request.project_id, request.session_id)+ )async def _capture_under_root(self,request: CaptureRequest,normalized_text: str,+ *,+ source_lease: InboundAttachmentLease | None,) -> CaptureReceipt:"""Pin and enqueue one validated capture under the provider-root fence."""pinned_bundle: PinnedBundle | None = None+ if request.attachments:+ try:+ if source_lease is None:+ pinned_bundle = await run_blocking(+ self._attachment_store.pin,+ request.attachments,+ )+ else:+ pinned_bundle = await run_blocking(+ self._attachment_store.pin,+ request.attachments,+ source_lease=source_lease,+ )+ except Exception as error:+ if normalized_text.strip():+ return await self._capture_under_root(+ replace(+ request,+ attachments=(),+ attachment_config_generation=None,+ ),+ normalized_text,+ source_lease=None,+ )+ if isinstance(error, AttachmentPinError):+ return await self._capture_pin_failure(error.error)+ if isinstance(error, UnicodeError):+ return await self._skipped_with_missed("memory_invalid_input")+ return OperationFailed(error="memory_store_unavailable")+try:- if request.attachments:- pinned_bundle = await run_blocking(- self._attachment_store.pin,- request.attachments,- )attachment_payload = (encode_pinned_bundle(pinned_bundle)if pinned_bundle is not None@@ -549,8 +830,6 @@ class MemoryModule:max_provider_timestamp_ms=MAX_PROVIDER_TIMESTAMP_MS,nonterminal_limit=MAX_NONTERMINAL_QUEUE_ROWS,)- except AttachmentPinError as error:- return await self._capture_pin_failure(error.error)except UnicodeError:if pinned_bundle is not None:await self._release_unadmitted_bundle(pinned_bundle.bundle_id)@@ -561,7 +840,13 @@ class MemoryModule:return OperationFailed(error="memory_store_unavailable")if result.outcome == "accepted":- return CaptureAccepted()+ return CaptureAccepted(+ captured_attachment_count=(+ len(pinned_bundle.attachments)+ if pinned_bundle is not None+ else 0+ )+ )if pinned_bundle is not None:await self._release_unadmitted_bundle(pinned_bundle.bundle_id)if result.outcome == "duplicate":@@ -1270,18 +1555,33 @@ class MemoryModule:) -> asyncio.Lock:"""Return the exact-session fence covering pin through queue commit."""- if not all(- isinstance(value, str)- for value in (principal_id, project_id, session_id)- ):+ key = self._capture_admission_key(+ principal_id=principal_id,+ project_id=project_id,+ session_id=session_id,+ )+ if key is None:return self._invalid_capture_admission_lock- key = (principal_id, project_id, session_id)lock = self._capture_admission_locks.get(key)if lock is None:lock = asyncio.Lock()self._capture_admission_locks[key] = lockreturn lock+ @staticmethod+ def _capture_admission_key(+ *,+ principal_id: object,+ project_id: object,+ session_id: object,+ ) -> tuple[str, str, str] | None:+ if not all(+ isinstance(value, str)+ for value in (principal_id, project_id, session_id)+ ):+ return None+ return principal_id, project_id, session_id+async def _store_call(self, method: Callable[..., Any], /, *args: Any, **kwargs: Any) -> Any:return await run_blocking(method, *args, **kwargs)diff --git a/core/memory/runtime.py b/core/memory/runtime.pyindex a2c1057b4..e167396cc 100644--- a/core/memory/runtime.py+++ b/core/memory/runtime.py@@ -36,7 +36,7 @@ from core.memory.artifact import (MemoryRuntimeActivationError,get_memory_artifact_manager,)-from core.memory.attachments import IM_ATTACHMENT_CAPTURE_AVAILABLE+from core.memory.attachments import IM_ATTACHMENT_CAPTURE_PLATFORMSfrom core.memory.blocking import run_blockingfrom core.memory.clear_intent import ClearSurfacefrom core.memory.confined_filesystem import required_no_follow_flag@@ -318,7 +318,13 @@ class _UnavailableMemoryModule:is the whole seam, not a stand-in for the complete ``MemoryModule`` interface."""- async def capture(self, _request: Any) -> OperationFailed:+ async def capture(+ self,+ _request: Any,+ *,+ source_lease: Any = None,+ ) -> OperationFailed:+ del source_leasereturn OperationFailed(error="memory_store_unavailable")@@ -1326,6 +1332,33 @@ class MemoryRuntime:}return payload+ async def attachment_capture_status(+ self,+ ) -> Literal["ready", "not_configured", "unavailable"]:+ """Return the same fresh readiness projection used by Memory status."""++ runtime = await self._processing_record.read_status()+ payload = _runtime_health_payload(runtime)+ return _attachment_capture_status(+ self._config,+ runtime.source.status,+ payload.get("health"),+ )++ def attachment_capture_config_generation(self) -> int | None:+ """Return the stable explicit opt-in generation without probing providers."""++ snapshot = self._processing_runtime_snapshot()+ multimodal = self._config.processing.multimodal+ if snapshot.transition_active or not self._config.enabled or multimodal is None:+ return None+ try:+ if not multimodal.complete():+ return None+ except Exception:+ return None+ return snapshot.generation+async def failure_log_payload(self,*,@@ -3683,7 +3716,7 @@ def _attachment_capture_status(if config.processing.multimodal is None:return "not_configured"- if not IM_ATTACHMENT_CAPTURE_AVAILABLE:+ if not IM_ATTACHMENT_CAPTURE_PLATFORMS:return "unavailable"if not config.enabled:return "unavailable"diff --git a/core/memory/types.py b/core/memory/types.pyindex 638e84d05..81939cb0f 100644--- a/core/memory/types.py+++ b/core/memory/types.py@@ -195,6 +195,7 @@ class CaptureRequest:text: stroccurred_at_ms: intattachments: tuple[CaptureAttachment, ...] = ()+ attachment_config_generation: int | None = Nonedef encode_capture_attachments(attachments: tuple[CaptureAttachment, ...]) -> str | None:@@ -246,6 +247,7 @@ def decode_capture_attachments(payload: str | None) -> tuple[CaptureAttachment,@dataclass(frozen=True)class CaptureAccepted:status: Literal["accepted"] = "accepted"+ captured_attachment_count: int = 0@dataclass(frozen=True)diff --git a/core/memory_telemetry.py b/core/memory_telemetry.pynew file mode 100644index 000000000..c479fcb7a--- /dev/null+++ b/core/memory_telemetry.py@@ -0,0 +1,31 @@+"""Scrub-safe Memory attachment telemetry.++This leaf stays above the eager ``core.memory`` package because importing that+package loads SQLite-backed modules and breaks native-session lightweight imports.+"""++from __future__ import annotations++import logging+++# Preserve the existing observability channel while keeping this helper free of+# admission and IM dependencies.+logger = logging.getLogger("core.memory.admission")+++def log_attachment_capture(+ platform: str,+ total: int,+ captured: int,+) -> None:+ """Record one finalized attachment set without native attachment detail."""++ dropped = total - captured+ logger.info(+ "memory_attachment_capture platform=%s total=%d captured=%d dropped=%d",+ platform,+ total,+ captured,+ dropped,+ )diff --git a/core/session_turns.py b/core/session_turns.pyindex edf33d138..b8727310c 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -628,6 +628,7 @@ class SessionTurnManager:self._deferred_restart_sessions: dict[str, set[str]] = {}self._queue_recovery_locks: dict[str, asyncio.Lock] = {}self._session_lifecycle_locks: dict[str, asyncio.Lock] = {}+ self._session_lifecycle_epochs: dict[str, int] = {}# Interruption reports owed to turns whose platform was not connected yet# when recovery ran, keyed by platform. See ``_report_lost_im_turn``.self._pending_lost_turn_reports: dict[str, list[tuple[str, str]]] = {}@@ -682,6 +683,22 @@ class SessionTurnManager:await lock.acquire()return TurnLifecycleAdmission(lock)+ def session_lifecycle_epoch(self, raw_session_id: str) -> int:+ """Return the local lifecycle generation for one canonical session."""++ if not isinstance(raw_session_id, str) or not raw_session_id:+ raise ValueError("session lifecycle epoch requires a session id")+ return self._session_lifecycle_epochs.get(raw_session_id, 0)++ def session_lifecycle_epoch_matches(+ self,+ raw_session_id: str,+ expected_epoch: int,+ ) -> bool:+ """Revalidate a pre-await lifecycle fact inside lifecycle admission."""++ return self.session_lifecycle_epoch(raw_session_id) == expected_epoch+async def run_session_lifecycle(self,raw_session_id: str,@@ -701,7 +718,10 @@ class SessionTurnManager:"turn capture admission did not quiesce before the deadline") from exctry:- return await operation()+ pre_epoch = self.session_lifecycle_epoch(raw_session_id)+ result = await operation()+ self._session_lifecycle_epochs[raw_session_id] = pre_epoch + 1+ return resultfinally:admission.release()diff --git a/docs/plans/memory-im-attachments-1425.md b/docs/plans/memory-im-attachments-1425.mdindex 0a79a1a41..5d86e855e 100644--- a/docs/plans/memory-im-attachments-1425.md+++ b/docs/plans/memory-im-attachments-1425.md@@ -24,7 +24,9 @@ redaction, and capture behavior.toggle.- A mixed turn degrades per attachment. Eligible text and every valid attachmentsurvive independently; one unsupported, oversized, or failed download never- rejects the turn.+ rejects the turn. If a selected attachment later fails descriptor/hash+ verification during durable pinning, the same capture is retried once as+ text-only; an attachment-only turn retains the closed pin failure.- The first release keeps the existing Avibe allowlist in`core/memory/modality.py`: bitmap images, PDF, supported audio, direct text,CSV, VTT, HTML, and EML. Office/iWork/ODF/RTF, SVG, and video remain excluded@@ -127,8 +129,8 @@ telemetry, or adapter exception text.Absent multimodal configuration or parser capability skips IM attachments beforepinning, enqueueing, or calling `/add`. Each rejected item degrades independently.-Avibe emits one scrub-safe `memory_attachment_capture_skipped` event per turn with-platform, count, and one closed reason only.+Avibe emits one scrub-safe `memory_attachment_capture` event per capture attempt+with platform, total, captured, and dropped counts only.Configured adds retain the existing retry and ambiguity semantics. DeterministicEverOS `UNSUPPORTED_FORMAT` and `CAPABILITY_UNAVAILABLE` attachment outcomes are@@ -172,8 +174,8 @@ add or call-log row.The settings API carries the optional Multimodal endpoint with the same write-only-keyand clear semantics as rerank. Either optional endpoint can be cleared while Memoryremains enabled; required LLM and embedding keys retain the enabled-state clear gate.-The visible card is gated until the Slack closed-loop slice lands. Status continues-to project EverOS+The Slack closed-loop slice flips the implementation stage gate and reveals the+visible card. Status continues to project EverOS`multimodal_llm`, `parser`, and `disabled_features` and adds a concise attachmentcapture availability line. Configuration remains UI-only; no CLI config flags areadded.@@ -236,6 +238,139 @@ gaps in the probe model rather than independent endpoint bugs.health reports `unavailable` even when cached capability values were previouslyhealthy.+### Slack activation contract++Delivery slice 4 makes Slack the reference platform. The settings availability+projection is derived from the intersection of the installation's enabled IM+platforms and `IM_ATTACHMENT_CAPTURE_PLATFORMS`; that allowlist remains closed to+Slack until slice 5 adds contract evidence for the other four adapters.++- Slack `message` and `app_mention` events publish a separate literal-true+ `is_ordinary_attachment` fact only for a native, human `file_share` shape with+ plain composer blocks. The fact does not reuse or weaken ordinary-text+ classification, and edited, forwarded, bot, rich, system, and shared shapes+ still fail closed.+- The message handler performs the existing shared Agent materialization first.+ It asks admission whether Memory may retain that materialized batch, then gives+ Memory an independent lease reference. A retain or scheduling failure is+ best-effort and cannot reject the Agent turn.+- The retained reference lives until the asynchronous Memory capture finishes.+ The Memory module pins through the descriptor-backed lease before enqueueing;+ the ordinary Agent consumer independently adopts its source files. This keeps+ one native download while preventing Agent cleanup or durable-delivery failure+ from racing the Memory pin.+- Capture reads current attachment readiness only after the closed DM admission+ gates pass. `not_configured` and `unavailable` retain eligible text but produce+ no attachment pin, provider attachment, or call-log row. Attachment-only turns+ with no surviving item are skipped.+- Per-attachment selection uses the closed format and limit table. A rejected+ sibling does not remove eligible text or valid siblings. Attachment telemetry+ reports only the attempt's total, captured, and dropped counts; it does not+ attribute reasons to individual files.+- The hermetic Slack scenario drives the shared materializer, admission, durable+ pin/outbox worker, fake EverOS add/flush, redacted multimodal call log, and+ `vibe memory search`. It proves a single adapter download and zero temp or+ Memory-bundle residue after successful processing.++### Capture call-site contract++Memory capture stays best effort and must not become part of user-visible Agent+dispatch latency. The call site therefore branches by turn shape instead of moving+all capture work to one late stage.++- Text-only human turns use the original early capture path immediately after the+ stable base session is resolved and before Agent routing. Attachment turns alone+ use the delayed path, and the only legal reason for that delay is waiting for the+ shared materializer to produce its immutable descriptor-backed lease.+- The canonical Memory session anchor is copied from `base_session_id` immediately+ after session resolution, before any subagent or routing-agent namespace can+ rewrite the Agent session id. Both the early capture and the delayed lifecycle+ fence/capture request receive that saved canonical value.+- **Cross-await revalidation invariant.** Any local fact resolved before an+ indeterminate await is revalidated inside the O(1), no-`await` atomic segment+ that consumes it; a mismatch fails closed, and no bounded waiter waits for the+ indeterminate span. Attachment turns snapshot the canonical session lifecycle+ epoch before materialization, then revalidate it while holding `SessionTurn`+ immediately before reservation. `/new` advances that local epoch only after its+ destructive operation succeeds and before releasing `SessionTurn`; a failed+ operation leaves the epoch unchanged. Therefore a reset never waits for a+ download, while an attachment that finishes after a successful reset is dropped+ as `stale_session` and eligible caption text is still captured independently.+- **Bounded-wait invariant.** No deadline-bound provider or subprocess read may+ occur in a span that blocks any bounded waiter. The bounded waiters here include+ both the user-visible Agent dispatch path and `/new`'s five-second lifecycle+ budget. Attachment eligibility must therefore be decided from local facts before+ any health read: platform and message shape, binding/config completeness, and the+ explicit multimodal configuration generation. Moving a remote read to a different+ call site does not satisfy this invariant if either bounded waiter still depends+ on its completion.+- Multimodal opt-in is an authoritative, generation-bound fact. The synchronous+ segment snapshots the stable Runtime configuration generation that proves an+ explicit endpoint and carries it on the immutable capture request. Immediately+ before enqueue, the replacement gate compares that generation with the current+ Runtime generation; absence or mismatch fails closed for attachments, including+ an opt-out or endpoint replacement that completed while readiness was being read.+ A missing IM generation projects `not_configured` immediately and retains eligible+ text without performing a live health read. Workbench alone keeps its one-cycle+ implicit compatibility path. Eligible text remains independently best effort, and+ that invariant must hold at every attachment-path failure or early return rather+ than only for failures with an existing closed classification.+- **Attachment capture logging (best-effort observability, not a ledger).**+ When a capture attempt reaches `MemoryModule.capture()` and returns a result,+ the controller emits one `memory_attachment_capture` record with+ `platform` / `total` / `captured` / `dropped`, where `captured` comes from+ `CaptureAccepted.captured_attachment_count` (the bundle actually enqueued;+ every other result type is zero) and `dropped = total - captured` is computed+ at that one site. This record set is deliberately **not** a complete census of+ turns: paths that terminate before a capture attempt is made — admission+ skips, runtime replacement, retirement, factory reset — emit nothing, by+ design. Do not add emission points to make it complete; completeness was tried+ and is what produced the cross-call-site accounting defects this section+ replaced. No per-attachment reason attribution is retained.+- **Reservation boundary.** While holding per-session `SessionTurn` lifecycle+ admission, the handler performs only an O(1), non-blocking, local registration of+ an exact-session Memory capture ticket. Registration records FIFO order but never+ waits for an earlier capture and never reads a provider or subprocess. Once the+ ticket and task ownership are established, the handler releases `SessionTurn`+ immediately and continues durable Agent admission.+- **Concurrent captures.** Tickets for the same canonical session execute in+ registration order. A background task waits for its predecessor only after+ `SessionTurn` has been released, then performs readiness, attachment selection,+ bundle pin/copy, and queue commit under the existing exact-session execution+ fence. Tickets for different canonical sessions have independent tails and remain+ concurrent. Order is represented by ticket data, never by holding the dispatch+ lock while slow work runs.+- **Lifecycle barrier.** `/new` first acquires `SessionTurn`, then registers a+ lifecycle barrier behind the current exact-session ticket tail and waits for that+ snapshot with the existing bounded lifecycle deadline. Holding `SessionTurn`+ prevents later turns from registering while the barrier drains, so every ticket+ before the reset is included and the wait converges; captures admitted after the+ reset queue behind the barrier. The reset and final flush therefore cannot pass an+ older registered capture, while Agent dispatch never waits for capture execution.+- **Single ownership, in process.** Before task tracking, the handler owns the+ reservation and any retained materializer lease. Successful scheduling transfers+ both to the background task; every exception, cancellation, or scheduling failure+ completes the reservation and releases the retained lease together. Once tracked,+ the task completes its ticket in `finally` and its done callback releases the+ lease. At shutdown, Controller closes the loop-owned capture-registration gate and+ then cancels and joins every tracked capture in the same event-loop coroutine,+ without the generic five-second cleanup cutoff. The handler rechecks the gate+ after any `SessionTurn` wait and immediately before the no-`await` reservation,+ retain, and task-registration segment. Once closed, that atomic segment cannot+ produce another reservation, lease, or task, so the sweep operates on a closed set+ and converges independently of every IM client's shutdown order. This+ process-local cleanup is best effort: no exit path may have two owners, but an+ abrupt process termination can bypass all callbacks.+- **Authoritative durable cleanup.** Startup recovery is the final correctness+ guarantee for every termination path, including crashes and `SIGKILL`.+ `MemoryCoordinator.recover_after_boot()` takes the database attachment-reference+ snapshot inside the admission fence and `_reconcile_attachments()` invokes the+ idempotent `AttachmentStore.reconcile(referenced, releasing)` operation. It removes+ all staging remnants and every bundle not referenced by the database. Therefore an+ attachment lease or bundle abandoned before queue adoption is bounded to the+ process lifetime plus the next Memory startup recovery, rather than permanently+ retained.+## Scenario contractThe canonical capability is `memory_im_attachment_capture` under@@ -258,15 +393,15 @@ running Avibe services, real user paths, or production state.1. Contract and scenario catalog, including the stale Workbench-copy and IMnon-goal corrections in `memory-plugin-system.md`.2. Optional multimodal config, child environment, preflight/redaction, UI, and- status. IM capture stays gated: `IM_ATTACHMENT_CAPTURE_AVAILABLE` remains false,- the settings response hides the card, and configured capture cannot report- `ready`; absent configuration retains the locked `not_configured` projection.+ status. IM capture stays gated: the platform allowlist remains empty, the+ settings response hides the card, and configured capture cannot report `ready`;+ absent configuration retains the locked `not_configured` projection.3. Shared leased materializer, bounded Telegram/WeChat acquisition, and pin-sourcegeneralization. IM capture stays gated.4. Attachment classification/admission and the Slack closed loop with call-log- proof. This slice flips `IM_ATTACHMENT_CAPTURE_AVAILABLE` only after the capture- path and its closed-loop evidence land, revealing the endpoint card and enabling- health-derived readiness without adding a user-facing toggle.+ proof. This slice adds Slack to the platform allowlist only after the capture path+ and its closed-loop evidence land, revealing the endpoint card when Slack is+ enabled and enabling health-derived readiness without a user-facing toggle.5. Discord, Telegram, Feishu/Lark, and WeChat enablement and contract tests, plusfinal user documentation and manual verification matrix.@@ -281,3 +416,14 @@ Hermetic tests prove the product contracts without live platform credentials.After all five slices merge, the orchestrator's integration pass should verify oneeligible image and one rejected file on every configured IM platform in the localIncus regression environment, preserving accumulated product state.++The final PR4 invariant audit also found five pre-existing paths outside this+slice's implementation files. The two bounded-wait spans are tracked by #1470;+the materializer-wide failure, post-enqueue bundle failure, and deterministic+provider attachment rejection paths are tracked by #1471. They remain outside+PR4 so its Slack activation does not expand into coordinator, provider, store, or+shared materializer changes.++A future observability improvement may add a non-identifying per-turn correlation+marker so operators can group multiple disjoint skip records from the same turn.+That marker is an operational convenience, not part of drop-accounting correctness.diff --git a/modules/im/base.py b/modules/im/base.pyindex 097450ce1..4b5a5b054 100644--- a/modules/im/base.py+++ b/modules/im/base.py@@ -47,6 +47,9 @@ class MessageContext:# Inbound adapters set this only after classifying their native event.# None is intentionally fail-closed for Memory capture and commands.is_ordinary_text: Optional[bool] = None+ # Attachment turns use a separate native-event classification so adding+ # files never widens the existing ordinary-text contract.+ is_ordinary_attachment: Optional[bool] = None@dataclassdiff --git a/modules/im/message_facts.py b/modules/im/message_facts.pyindex d23e9ebc5..a7edf0806 100644--- a/modules/im/message_facts.py+++ b/modules/im/message_facts.py@@ -102,6 +102,34 @@ def is_ordinary_slack_text(event: dict[str, Any], files: Optional[list[FileAttac)+def is_ordinary_slack_attachment(+ event: dict[str, Any],+ files: Optional[list[FileAttachment]],+) -> bool:+ """Classify a direct human Slack upload without weakening text admission."""++ native_files = event.get("files")+ return (+ bool(files)+ and isinstance(native_files, list)+ and bool(native_files)+ and event.get("subtype") in {None, "file_share"}+ and is_plain_slack_composer_blocks(event.get("blocks"))+ and not any(+ (+ event.get("attachments"),+ event.get("edited"),+ event.get("bot_id"),+ event.get("rich_text"),+ event.get("forwarded"),+ event.get("is_system"),+ event.get("system"),+ event.get("type") in {"system", "system_message"},+ )+ )+ )++def is_ordinary_discord_text(message: Any, files: Optional[list[FileAttachment]]) -> bool:try:is_system = message.is_system() if callable(getattr(message, "is_system", None)) else Falsediff --git a/modules/im/slack.py b/modules/im/slack.pyindex 01c28d7cd..649023493 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -21,7 +21,7 @@ from .base import (InlineButton,FileAttachment,)-from .message_facts import is_ordinary_slack_text+from .message_facts import is_ordinary_slack_attachment, is_ordinary_slack_textfrom .download_target import open_download_targetfrom config.v2_config import SlackConfigfrom core.auth import AuthResult@@ -2098,6 +2098,10 @@ class SlackBot(BaseIMClient):},files=file_attachments,is_ordinary_text=is_ordinary_slack_text(event, file_attachments) and not has_shared_content,+ is_ordinary_attachment=(+ is_ordinary_slack_attachment(event, file_attachments)+ and not has_shared_content+ ),)if handled_bot_mention_in_message_event and self.settings_manager and thread_id:@@ -2198,6 +2202,10 @@ class SlackBot(BaseIMClient):},files=file_attachments,is_ordinary_text=is_ordinary_slack_text(event, file_attachments) and not bool(shared_text),+ is_ordinary_attachment=(+ is_ordinary_slack_attachment(event, file_attachments)+ and not bool(shared_text)+ ),)# Mark thread as active only when the mention carries actionable content.diff --git a/tests/scenario_harness/memory_im_attachments.py b/tests/scenario_harness/memory_im_attachments.pynew file mode 100644index 000000000..f33fdea0d--- /dev/null+++ b/tests/scenario_harness/memory_im_attachments.py@@ -0,0 +1,283 @@+"""Hermetic Slack-to-Memory attachment capture scenario harness."""++from __future__ import annotations++import base64+import os+from dataclasses import dataclass, field+from pathlib import Path+from types import SimpleNamespace++from core.controller import Controller+from core.handlers.inbound_attachments import InboundAttachmentMaterializer+from core.memory.everos import FakeMemoryProvider, ProviderCapture+from core.memory.everos_insight.recorder import (+ ProviderCallInput,+ ProviderCallRow,+ normalize_provider_call,+)+from core.memory.module import MIN_FREE_DISK_BYTES, MemoryModule+from core.memory.store import MemoryStore+from core.memory.types import MemoryItem+from modules.im.base import FileAttachment, FileDownloadResult, MessageContext+from modules.im.message_facts import is_ordinary_slack_attachment, is_ordinary_slack_text+++PRINCIPAL = "u-11111111111111111111111111111111"+PROJECT = "default"+PNG_BYTES = base64.b64decode(+ "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAYElEQVR42u3QAQ0AAAwC"+ "IPuX1hzfIQLpcxEgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAA"+ "AQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQLuG0bQw7Ko2TvAAAAAAElFTkSuQmCC"+)+++class _SlackDownloader:+ def __init__(self, payloads: dict[str, bytes]) -> None:+ self.payloads = payloads+ self.calls: list[dict[str, object]] = []++ async def download_file_to_path(+ self,+ file_info,+ _target_path,+ *,+ max_bytes=None,+ target_fd=None,+ **_kwargs,+ ) -> FileDownloadResult:+ assert target_fd is not None+ payload = self.payloads[str(file_info["name"])]+ self.calls.append(+ {+ "name": file_info["name"],+ "max_bytes": max_bytes,+ }+ )+ os.write(target_fd, payload)+ return FileDownloadResult(True)+++class _UserStore:+ def __init__(self, *, bound: bool) -> None:+ self.bound = bound++ def maybe_reload(self) -> None:+ return None++ def get_user(self, _user_id: str, *, platform: str):+ assert platform == "slack"+ return SimpleNamespace(enabled=True) if self.bound else None+++class _SettingsManager:+ def __init__(self, *, bound: bool) -> None:+ self._store = _UserStore(bound=bound)++ def get_store(self) -> _UserStore:+ return self._store+++@dataclass+class _InspectableProvider(FakeMemoryProvider):+ observed_payloads: list[bytes] = field(default_factory=list)+ call_log: list[ProviderCallRow] = field(default_factory=list)++ async def add(self, capture: ProviderCapture):+ if capture.attachments:+ attachment = capture.attachments[0]+ source = Path(attachment.uri.removeprefix("file://"))+ payload = source.read_bytes()+ self.observed_payloads.append(payload)+ data_uri = "data:image/png;base64," + base64.b64encode(payload).decode("ascii")+ self.call_log.append(+ normalize_provider_call(+ ProviderCallInput(+ id=f"multimodal-{len(self.call_log) + 1}",+ started_at_ms=1_700_000_000_000,+ duration_ms=1,+ kind="multimodal_llm",+ stage="boundary",+ status="ok",+ request={+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": capture.text},+ {+ "type": "image_url",+ "image_url": {"url": data_uri},+ },+ ],+ }+ ]+ },+ response={"content": "attachment parsed"},+ ),+ exact_redaction_values=(attachment.uri,),+ )+ )+ self.search_items = (+ MemoryItem(+ kind="fact",+ text=f"Captured Slack attachment {attachment.name}",+ ),+ )+ return await super().add(capture)+++class _Runtime:+ def __init__(self, module: MemoryModule, *, attachment_status: str) -> None:+ self.module = module+ self.available = True+ self.retired = False+ self._attachment_status = attachment_status+ self._attachment_generation = (+ None if attachment_status == "not_configured" else 1+ )++ def principal_for_user_key(self, user_key: str) -> str:+ assert user_key == "slack:U1"+ return PRINCIPAL++ async def attachment_capture_status(self) -> str:+ return self._attachment_status++ def attachment_capture_config_generation(self) -> int | None:+ return self._attachment_generation+++class MemoryIMAttachmentScenarioHarness:+ """Drive the real shared materializer, admission, pin, outbox, and worker."""++ def __init__(+ self,+ root: Path,+ *,+ attachment_status: str = "ready",+ bound: bool = True,+ is_dm: bool = True,+ ) -> None:+ self.home = root / "avibe-home"+ self.home.mkdir(mode=0o700, parents=True)+ self.provider = _InspectableProvider()+ self.module = MemoryModule(+ MemoryStore(self.home / "state" / "memory.sqlite"),+ self.provider,+ enabled=True,+ disk_free_bytes=lambda: MIN_FREE_DISK_BYTES,+ effective_home=self.home,+ )+ self.runtime = _Runtime(self.module, attachment_status=attachment_status)+ self.controller = Controller.__new__(Controller)+ multimodal = (+ None+ if attachment_status == "not_configured"+ else SimpleNamespace(complete=lambda: True)+ )+ self.controller.config = SimpleNamespace(+ memory=SimpleNamespace(+ enabled=True,+ recovery_intent=None,+ processing=SimpleNamespace(multimodal=multimodal),+ )+ )+ self.controller.platform_settings_managers = {+ "slack": _SettingsManager(bound=bound)+ }+ self.controller.memory_runtime = self.runtime+ self.controller.memory_module = self.module+ self.controller.get_cwd = lambda _context: str(root / "project")+ self.is_dm = is_dm+ self.downloader: _SlackDownloader | None = None+ self.last_context: MessageContext | None = None++ async def capture(+ self,+ *,+ text: str,+ payloads: dict[str, tuple[str, bytes]],+ ) -> None:+ files = [+ FileAttachment(+ name=name,+ mimetype=mimetype,+ url=f"https://files.slack.test/{index}",+ size=len(payload),+ )+ for index, (name, (mimetype, payload)) in enumerate(payloads.items())+ ]+ event = {+ "type": "message",+ "subtype": "file_share",+ "user": "U1",+ "text": text,+ "files": [+ {"name": item.name, "mimetype": item.mimetype, "size": item.size}+ for item in files+ ],+ "blocks": [+ {+ "type": "rich_text",+ "elements": [+ {+ "type": "rich_text_section",+ "elements": ([{"type": "text", "text": text}] if text else []),+ }+ ],+ }+ ],+ }+ context = MessageContext(+ user_id="U1",+ channel_id="D1" if self.is_dm else "C1",+ platform="slack",+ thread_id="native-1",+ message_id="native-1",+ platform_specific={"platform": "slack", "is_dm": self.is_dm},+ files=files,+ is_ordinary_text=is_ordinary_slack_text(event, files),+ is_ordinary_attachment=is_ordinary_slack_attachment(event, files),+ )+ self.last_context = context+ self.downloader = _SlackDownloader(+ {name: payload for name, (_mimetype, payload) in payloads.items()}+ )+ batch = await InboundAttachmentMaterializer(+ effective_home=self.home,+ attachments_root=self.home / "attachments",+ ).materialize(context, self.downloader)+ memory_lease = None+ try:+ reservation = self.controller.reserve_memory_attachment_capture(+ context,+ "stable-session",+ )+ config_generation = getattr(reservation, "config_generation", None)+ if config_generation is not None:+ memory_lease = batch.lease.retain()+ await self.controller.capture_user_memory(+ context,+ text,+ "stable-session",+ attachment_lease=memory_lease,+ attachment_reservation=reservation,+ attachment_config_generation=config_generation,+ )+ batch.lease.adopt()+ finally:+ if memory_lease is not None:+ memory_lease.release()+ batch.lease.release()+ await self.module.drain()+ await self.module.final_flush(+ principal_id=PRINCIPAL,+ project_id=PROJECT,+ raw_session_id="stable-session",+ )++ @property+ def memory_bundle_entries(self) -> tuple[Path, ...]:+ bundles = self.home / "memory" / "attachments" / "bundles"+ return tuple(bundles.iterdir()) if bundles.exists() else ()diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 5e65ae623..603540a77 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -69,12 +69,23 @@ capabilities:- ui/src/context/ApiContext.memoryList.test.tsx- id: memory_im_attachment_capturename: Bound-DM attachment capture through EverOS multimodal ingest- status: planned+ status: activecatalog: tests/scenarios/memory_im_attachment_capture/catalog.yamlobservations: tests/scenarios/memory_im_attachment_capture/observations.yaml- scenario_tests: []+ scenario_tests:+ - tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py+ harness:+ - tests/scenario_harness/memory_im_attachments.pyunit_or_contract_tests:- tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_catalog.py+ - tests/test_memory_admission.py+ - tests/test_memory_im_attachments.py+ - tests/test_inbound_attachments.py+ - tests/test_memory_runtime.py+ - tests/test_memory_slice3.py+ - tests/test_message_handler_typing.py+ - tests/test_slack_dm_mentions.py+ - tests/test_ui_memory_routes.py- id: memory_repairname: Live Memory index repair via admitted artifact syncstatus: activediff --git a/tests/scenarios/memory_im_attachment_capture/catalog.yaml b/tests/scenarios/memory_im_attachment_capture/catalog.yamlindex fd6a2d029..517c45d09 100644--- a/tests/scenarios/memory_im_attachment_capture/catalog.yaml+++ b/tests/scenarios/memory_im_attachment_capture/catalog.yaml@@ -4,6 +4,11 @@ capability:name: Bound-DM attachment capture through EverOS multimodal ingestcanonical_tests:- tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_catalog.py+ - tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py+ - tests/test_memory_admission.py+ - tests/test_memory_im_attachments.py+ - tests/test_inbound_attachments.py+ - tests/test_ui_memory_routes.pycontract:admission: bound_enabled_one_to_one_dm_fail_closedopt_in: explicit_complete_multimodal_endpoint@@ -13,29 +18,33 @@ contract:preflight: generated_image_without_user_dataworkbench_compatibility: implicit_main_llm_for_one_cyclestatus_legend:- planned: scenario id and invariant reserved; behavior evidence lands in a later slice+ covered: executable evidence existsscenarios:- id: MEMORY-IM-ATTACH-001name: Bound Slack DM attachments traverse one download, pin, add, flush, and search path- status: planned+ status: coveredkind: happy_pathlayer: scenariodelivery_slice: 4+ test: tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py::test_bound_slack_dm_attachment_reaches_search_with_redacted_call_log- id: MEMORY-IM-ATTACH-002name: Group and unbound events perform no Memory attachment acquisition- status: planned+ status: coveredkind: authorizationlayer: scenariodelivery_slice: 4+ test: tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py::test_denied_slack_scope_never_reaches_memory_provider- id: MEMORY-IM-ATTACH-003name: Missing multimodal configuration preserves eligible text without attachment provider activity- status: planned+ status: coveredkind: degradationlayer: scenariodelivery_slice: 4+ test: tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py::test_missing_multimodal_config_preserves_text_without_attachment_activity- id: MEMORY-IM-ATTACH-004name: Invalid attachments preserve valid siblings and leave no temporary or bundle leak- status: planned+ status: coveredkind: boundarylayer: scenariodelivery_slice: 4+ test: tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py::test_invalid_sibling_preserves_valid_attachment_and_leaves_no_memory_leakdiff --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 5a5edff28..b98b4248c 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@@ -1,4 +1,4 @@-"""Mechanical contract for the planned IM attachment capture scenarios."""+"""Mechanical contract for the active IM attachment capture scenarios."""from pathlib import Path@@ -35,11 +35,14 @@ def test_memory_im_attachment_catalog_is_indexed_and_locks_the_approved_contract)assert catalog["contract"] == LOCKED_CONTRACT- assert entry["status"] == "planned"+ assert entry["status"] == "active"assert entry["catalog"] == (SCENARIO_ROOT / "catalog.yaml").as_posix()assert entry["observations"] == (SCENARIO_ROOT / "observations.yaml").as_posix()- assert entry["unit_or_contract_tests"] == [- (SCENARIO_ROOT / "test_memory_im_attachment_capture_catalog.py").as_posix()+ assert entry["scenario_tests"] == [+ (SCENARIO_ROOT / "test_memory_im_attachment_capture_scenarios.py").as_posix()+ ]+ assert entry["harness"] == [+ "tests/scenario_harness/memory_im_attachments.py"]scenario_ids = [row["id"] for row in catalog["scenarios"]]@@ -60,12 +63,12 @@ def test_memory_im_attachment_catalog_is_indexed_and_locks_the_approved_contract("MEMORY-IM-ATTACH-004", "boundary", 4),],)-def test_memory_im_attachment_planned_scenario_contract(+def test_memory_im_attachment_covered_scenario_contract(scenario_id: str,kind: str,delivery_slice: int,) -> None:- """The four MEMORY-IM-ATTACH scenario IDs stay stable until behavior evidence replaces this contract."""+ """The four MEMORY-IM-ATTACH scenario IDs map to executable evidence."""catalog = _load(SCENARIO_ROOT / "catalog.yaml")rows = {row["id"]: row for row in catalog["scenarios"]}@@ -77,8 +80,10 @@ def test_memory_im_attachment_planned_scenario_contract("MEMORY-IM-ATTACH-003","MEMORY-IM-ATTACH-004",}- assert rows[scenario_id]["status"] == "planned"+ assert rows[scenario_id]["status"] == "covered"assert rows[scenario_id]["kind"] == kindassert rows[scenario_id]["layer"] == "scenario"assert rows[scenario_id]["delivery_slice"] == delivery_slice- assert "test" not in rows[scenario_id]+ assert rows[scenario_id]["test"].startswith(+ "tests/scenarios/memory_im_attachment_capture/"+ )diff --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.pynew file mode 100644index 000000000..1a042740e--- /dev/null+++ b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py@@ -0,0 +1,206 @@+"""Closed-loop scenario evidence for Slack Memory attachment capture."""++from __future__ import annotations++import asyncio+import base64+import json++import pytest++from core.caller_context import AVIBE_SESSION_ID_ENV+from core.memory.types import RecallItems, RecallPolicy, memory_item_payload+from tests.scenario_harness.memory_im_attachments import (+ PNG_BYTES,+ PRINCIPAL,+ PROJECT,+ MemoryIMAttachmentScenarioHarness,+)+from vibe import cli, internal_client+++def test_bound_slack_dm_attachment_reaches_search_with_redacted_call_log(+ tmp_path,+ monkeypatch,+ capsys,+) -> None:+ """Scenario: MEMORY-IM-ATTACH-001."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe-home"))+ harness = MemoryIMAttachmentScenarioHarness(tmp_path)+ asyncio.run(+ harness.capture(+ text="Remember this screenshot",+ payloads={"screenshot.png": ("image/png", PNG_BYTES)},+ )+ )++ assert harness.downloader is not None+ assert harness.downloader.calls == [+ {"name": "screenshot.png", "max_bytes": None}+ ]+ assert len(harness.provider.captures) == 1+ assert len(harness.provider.flushes) == 1+ assert harness.provider.observed_payloads == [PNG_BYTES]+ assert len(harness.provider.call_log) == 1++ call = harness.provider.call_log[0]+ encoded = base64.b64encode(PNG_BYTES).decode("ascii")+ assert call.kind == "multimodal_llm"+ assert "data:image/png" not in call.request_json+ assert encoded not in call.request_json+ assert "file://" not in call.request_json+ assert "[ATTACHMENT_OMITTED]" in call.request_json++ monkeypatch.setenv(AVIBE_SESSION_ID_ENV, "ses-memory-im-attachment")++ def search_sync(query: str, limit: int, **kwargs):+ assert kwargs == {+ "mode": "hybrid",+ "project": None,+ "caller_session_id": "ses-memory-im-attachment",+ }+ result = asyncio.run(+ harness.module.recall(+ query,+ policy=RecallPolicy(mode="hybrid", max_results=limit),+ principal_id=PRINCIPAL,+ project_id=PROJECT,+ )+ )+ assert isinstance(result, RecallItems)+ return {+ "status_code": 200,+ "body": {+ "status": "ok",+ "items": [memory_item_payload(item) for item in result.items],+ },+ }++ monkeypatch.setattr(internal_client, "memory_search_sync", search_sync)+ args = cli.build_parser().parse_args(+ ["memory", "search", "screenshot", "--limit", "3", "--json"]+ )++ assert cli.cmd_memory(args) == 0+ payload = json.loads(capsys.readouterr().out)+ assert payload["result"]["items"] == [+ {+ "kind": "fact",+ "text": "Captured Slack attachment screenshot.png",+ "date": None,+ }+ ]+++ ("bound", "is_dm"),+ [(False, True), (True, False)],+)+def test_denied_slack_scope_never_reaches_memory_provider(+ tmp_path,+ monkeypatch,+ bound: bool,+ is_dm: bool,+) -> None:+ """Scenario: MEMORY-IM-ATTACH-002."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe-home"))+ harness = MemoryIMAttachmentScenarioHarness(+ tmp_path,+ bound=bound,+ is_dm=is_dm,+ )+ asyncio.run(+ harness.capture(+ text="Do not capture",+ payloads={"private.png": ("image/png", PNG_BYTES)},+ )+ )++ assert harness.downloader is not None+ assert len(harness.downloader.calls) == 1+ assert harness.provider.captures == []+ assert harness.provider.flushes == []+ assert harness.provider.call_log == []+ assert harness.memory_bundle_entries == ()+++def test_missing_multimodal_config_preserves_text_without_attachment_activity(+ tmp_path,+ monkeypatch,+) -> None:+ """Scenario: MEMORY-IM-ATTACH-003."""++ mixed_root = tmp_path / "mixed"+ monkeypatch.setenv("AVIBE_HOME", str(mixed_root / "avibe-home"))+ mixed = MemoryIMAttachmentScenarioHarness(+ mixed_root,+ attachment_status="not_configured",+ )+ asyncio.run(+ mixed.capture(+ text="Remember the accompanying note",+ payloads={"note.png": ("image/png", PNG_BYTES)},+ )+ )++ assert len(mixed.provider.captures) == 1+ assert mixed.provider.captures[0].text == "Remember the accompanying note"+ assert mixed.provider.captures[0].attachments == ()+ assert len(mixed.provider.flushes) == 1+ assert mixed.provider.call_log == []+ assert mixed.memory_bundle_entries == ()++ attachment_only_root = tmp_path / "attachment-only"+ monkeypatch.setenv("AVIBE_HOME", str(attachment_only_root / "avibe-home"))+ attachment_only = MemoryIMAttachmentScenarioHarness(+ attachment_only_root,+ attachment_status="not_configured",+ )+ asyncio.run(+ attachment_only.capture(+ text="",+ payloads={"only.png": ("image/png", PNG_BYTES)},+ )+ )++ assert attachment_only.provider.captures == []+ assert attachment_only.provider.flushes == []+ assert attachment_only.provider.call_log == []+ assert attachment_only.memory_bundle_entries == ()+++def test_invalid_sibling_preserves_valid_attachment_and_leaves_no_memory_leak(+ tmp_path,+ monkeypatch,+) -> None:+ """Scenario: MEMORY-IM-ATTACH-004."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe-home"))+ harness = MemoryIMAttachmentScenarioHarness(tmp_path)+ asyncio.run(+ harness.capture(+ text="Keep only the valid image",+ payloads={+ "valid.png": ("image/png", PNG_BYTES),+ "excluded.svg": (+ "image/svg+xml",+ b'<svg xmlns="http://www.w3.org/2000/svg"></svg>',+ ),+ },+ )+ )++ assert harness.downloader is not None+ assert [call["name"] for call in harness.downloader.calls] == [+ "valid.png",+ "excluded.svg",+ ]+ assert len(harness.provider.captures) == 1+ assert [item.name for item in harness.provider.captures[0].attachments] == [+ "valid.png"+ ]+ assert len(harness.provider.call_log) == 1+ assert harness.memory_bundle_entries == ()+ assert not tuple(harness.home.rglob("*.part"))diff --git a/tests/test_controller_dispatch_loop.py b/tests/test_controller_dispatch_loop.pyindex 6f8970e00..6c3622d31 100644--- a/tests/test_controller_dispatch_loop.py+++ b/tests/test_controller_dispatch_loop.py@@ -341,6 +341,7 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:"supervisor": False,"runtime": False,"capture": False,+ "capture-registration": False,}stop_order: list[str] = []@@ -376,7 +377,12 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:stop_order.append("memory-runtime")class _MessageHandler:- async def drain_memory_capture_tasks(self) -> None:+ def quiesce_memory_capture_tasks(self) -> None:+ stopped["capture-registration"] = True+ stop_order.append("capture-registration")++ async def cancel_memory_capture_tasks(self) -> None:+ assert stopped["capture-registration"] is Truestopped["capture"] = Truestop_order.append("capture")@@ -410,6 +416,7 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:assert stopped["supervisor"] is Trueassert stopped["runtime"] is Trueassert stopped["capture"] is True+ assert stopped["capture-registration"] is Trueassert old_memory_runtime.closed is Falseassert fresh_memory_runtime.closed is Trueruntime_work_order = [@@ -419,7 +426,11 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:assert set(runtime_work_order[1:3]) == {"tasks", "watch"}assert runtime_work_order[3] == "supervisor"assert stop_order.index("factory-reset") < stop_order.index("capture")- assert stop_order[-2:] == ["capture", "memory-runtime"]+ assert stop_order[-3:] == [+ "capture-registration",+ "capture",+ "memory-runtime",+ ]@pytest.mark.asynciodiff --git a/tests/test_memory_admission.py b/tests/test_memory_admission.pyindex 5696dab6f..f5358d508 100644--- a/tests/test_memory_admission.py+++ b/tests/test_memory_admission.py@@ -2,6 +2,8 @@from __future__ import annotations+import asyncio+import osfrom pathlib import Pathfrom types import SimpleNamespace@@ -9,7 +11,9 @@ import pytestfrom core.memory.admission import CaptureAdmission, InboundTurnFactsfrom core.memory.attachments import workbench_capture_attachments-from core.memory.types import CaptureRequest, CaptureSkipped+from core.memory.types import CaptureAttachment, CaptureRequest, CaptureSkipped+from core.handlers.inbound_attachments import InboundAttachmentMaterializer+from modules.im.base import FileAttachment, FileDownloadResult, MessageContextfrom modules.im.message_facts import is_ordinary_workbench_text@@ -69,6 +73,42 @@ def _facts(**overrides) -> InboundTurnFacts:return InboundTurnFacts(**{**defaults, **overrides})+class _PdfDownloader:+ async def download_file_to_path(+ self,+ _file_info,+ _target_path,+ *,+ target_fd=None,+ **_kwargs,+ ) -> FileDownloadResult:+ assert target_fd is not None+ os.write(target_fd, b"%PDF-1.7\nslack attachment")+ return FileDownloadResult(True)+++def _slack_pdf_lease(tmp_path: Path):+ context = MessageContext(+ user_id="user-1",+ channel_id="dm-1",+ platform="slack",+ files=[+ FileAttachment(+ name="receipt.pdf",+ mimetype="application/pdf",+ url="https://files.slack.test/private",+ size=24,+ )+ ],+ )+ return asyncio.run(+ InboundAttachmentMaterializer(+ effective_home=tmp_path,+ attachments_root=tmp_path / "downloads",+ ).materialize(context, _PdfDownloader())+ )++@pytest.mark.parametrize("platform", ["slack", "discord", "telegram", "feishu", "lark", "wechat"])def test_every_enabled_bound_dm_user_is_admitted(platform: str) -> None:admission = _admission()@@ -214,6 +254,184 @@ def test_a_literal_true_still_admits_after_strict_normalization() -> None:assert isinstance(_admission().decide(_facts(is_dm=True, memory_enabled=True)), CaptureRequest)+def test_bound_slack_attachment_turn_selects_only_the_materialized_lease(+ tmp_path: Path,+) -> None:+ """Scenario: MEMORY-IM-ATTACH-001."""++ batch = _slack_pdf_lease(tmp_path)+ try:+ request = _admission().decide(+ _facts(+ text="remember this receipt",+ files=[object()],+ is_ordinary_text=False,+ is_ordinary_attachment=True,+ attachment_lease=batch.lease,+ attachment_capture_status="ready",+ attachment_config_generation=1,+ )+ )+ finally:+ batch.lease.release()++ assert isinstance(request, CaptureRequest)+ assert request.text == "remember this receipt"+ assert [(item.name, item.kind, item.ext) for item in request.attachments] == [+ ("receipt.pdf", "pdf", "pdf")+ ]+++def test_missing_multimodal_keeps_mixed_text_without_an_attachment() -> None:+ """Scenario: MEMORY-IM-ATTACH-003."""++ request = _admission().decide(+ _facts(+ text="remember the caption",+ files=[object()],+ is_ordinary_text=False,+ is_ordinary_attachment=True,+ attachment_capture_status="not_configured",+ )+ )++ assert isinstance(request, CaptureRequest)+ assert request.text == "remember the caption"+ assert request.attachments == ()+++def test_missing_multimodal_skips_attachment_only_turn() -> None:+ """Scenario: MEMORY-IM-ATTACH-003."""++ assert _admission().decide(+ _facts(+ text="",+ files=[object()],+ is_ordinary_text=False,+ is_ordinary_attachment=True,+ attachment_capture_status="not_configured",+ )+ ) == CaptureSkipped(reason="memory_invalid_input")+++ "overrides",+ [+ {"is_dm": False},+ {"is_ordinary_attachment": False},+ {"is_ordinary_attachment": None},+ {"platform": "discord", "is_ordinary_attachment": True},+ ],+)+def test_denied_attachment_turn_never_reads_the_lease(+ monkeypatch: pytest.MonkeyPatch,+ overrides: dict[str, object],+) -> None:+ """Scenario: MEMORY-IM-ATTACH-002."""++ monkeypatch.setattr(+ "core.memory.admission.select_memory_attachments",+ lambda _lease: pytest.fail("denied turn reached Memory attachment selection"),+ )+ facts = _facts(+ **{+ "files": [object()],+ "is_ordinary_text": False,+ "is_ordinary_attachment": True,+ "attachment_capture_status": "ready",+ **overrides,+ }+ )++ assert isinstance(_admission().decide(facts), CaptureSkipped)+++def test_not_configured_attachment_turn_keeps_safe_caption() -> None:+ secret_name = "quarterly-secret.pdf"+ secret_url = "https://files.slack.test/token-bearing-url"+ native_file = SimpleNamespace(name=secret_name, url=secret_url)++ request = _admission().decide(+ _facts(+ text="safe caption",+ files=[native_file],+ is_ordinary_text=False,+ is_ordinary_attachment=True,+ attachment_capture_status="not_configured",+ )+ )++ assert isinstance(request, CaptureRequest)+ assert request.text == "safe caption"+ assert request.attachments == ()+++def test_mixed_attachment_rejections_keep_caption(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ "core.memory.admission.select_memory_attachments",+ lambda _lease: SimpleNamespace(+ attachments=(),+ skipped=("file_too_large", "unsupported_type"),+ ),+ )++ request = _admission().decide(+ _facts(+ text="safe caption",+ files=[object(), object()],+ is_ordinary_text=False,+ is_ordinary_attachment=True,+ attachment_lease=object(),+ attachment_capture_status="ready",+ attachment_config_generation=1,+ )+ )++ assert isinstance(request, CaptureRequest)+ assert request.attachments == ()+++def test_unexpected_attachment_selection_failure_keeps_text(+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ """Scenario: MEMORY-IM-ATTACH-004."""++ monkeypatch.setattr(+ "core.memory.admission.select_memory_attachments",+ lambda _lease: (_ for _ in ()).throw(+ RuntimeError("secret attachment name must not be logged")+ ),+ )+ caplog.set_level("INFO", logger="core.memory.admission")++ request = _admission().decide(+ _facts(+ text="keep this caption",+ files=[object()],+ is_ordinary_text=False,+ is_ordinary_attachment=True,+ attachment_lease=object(),+ attachment_capture_status="ready",+ attachment_config_generation=9,+ )+ )++ assert isinstance(request, CaptureRequest)+ assert request.text == "keep this caption"+ assert request.attachments == ()+ warnings = [+ record+ for record in caplog.records+ if record.message.startswith("memory_attachment_selection_failed")+ ]+ assert len(warnings) == 1+ assert "error_type=RuntimeError" in warnings[0].getMessage()+ assert "secret attachment name" not in caplog.text++def test_disabled_memory_is_answered_before_any_directory_lookup() -> None:principals = _Principals(raises=True)bindings = _Bindings(raises=True)diff --git a/tests/test_memory_attachment_drop_accounting.py b/tests/test_memory_attachment_drop_accounting.pynew file mode 100644index 000000000..0496bce15--- /dev/null+++ b/tests/test_memory_attachment_drop_accounting.py@@ -0,0 +1,130 @@+"""Result-driven telemetry for IM attachment capture attempts."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace+from unittest.mock import Mock++import pytest++from core.memory.attachments import AttachmentPinError+from modules.im.base import FileAttachment+++def _attachment_context(message_id: str, count: int):+ from tests.test_memory_slice3 import _context++ context = _context("slack", ordinary=False)+ context.message_id = message_id+ context.files = [+ FileAttachment(+ name=f"attachment-{index}.pdf",+ mimetype="application/pdf",+ url=f"https://files.slack.test/private/{index}",+ )+ for index in range(count)+ ]+ context.is_ordinary_attachment = True+ return context+++def _assert_single_conservation_record(+ caplog: pytest.LogCaptureFixture,+ *,+ total: int,+ captured: int,+) -> None:+ records = [+ record.getMessage()+ for record in caplog.records+ if record.message.startswith("memory_attachment_capture ")+ ]+ assert len(records) == 1+ fields = dict(part.split("=", 1) for part in records[0].split()[1:])+ assert set(fields) == {"platform", "total", "captured", "dropped"}+ assert fields["platform"] == "slack"+ assert int(fields["total"]) == total+ assert int(fields["captured"]) == captured+ assert int(fields["dropped"]) == total - captured+++async def test_attachment_capture_telemetry_uses_terminal_result(+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+ tmp_path: Path,+) -> None:+ """Scenario: MEMORY-IM-ATTACH-004."""++ from tests.test_memory_module import _attachment_store, _module, _source_attachment+ from tests.test_memory_slice3 import _Runtime, _controller++ caplog.set_level("INFO", logger="core.memory.admission")++ # A partial download followed by reservation failure reaches the terminal+ # text-only result with no captured attachments.+ controller = _controller()+ controller.memory_module.reserve_capture_admission = Mock(+ side_effect=RuntimeError("reservation unavailable")+ )+ context = _attachment_context("reservation-failure", 2)+ assert (+ controller.reserve_memory_attachment_capture(context, "stable-session")+ is None+ )+ await controller.capture_user_memory(+ context,+ "keep this caption",+ "stable-session",+ )+ _assert_single_conservation_record(caplog, total=2, captured=0)++ # The stale state produced when /new wins during materialization follows the+ # same no-reservation path and still emits exactly one terminal record.+ caplog.clear()+ controller = _controller()+ context = _attachment_context("stale-after-reset", 1)+ await controller.capture_user_memory(+ context,+ "keep this caption",+ "stable-session",+ )+ _assert_single_conservation_record(caplog, total=1, captured=0)++ # One materialized survivor reaches pinning, but the terminal text fallback+ # reports zero because no attachment bundle was actually enqueued.+ caplog.clear()+ attachment_store = _attachment_store()+ module, store, _provider = _module(tmp_path, attachment_store=attachment_store)+ controller = _controller()+ controller.memory_module = module+ controller.memory_runtime = _Runtime(module)+ survivor = _source_attachment("survivor.pdf", b"survivor")+ monkeypatch.setattr(+ "core.memory.admission.select_memory_attachments",+ lambda _lease: SimpleNamespace(attachments=(survivor,), skipped=()),+ )++ def fail_pin(*_args, **_kwargs):+ raise AttachmentPinError(+ "memory_store_unavailable",+ "leased source changed before pinning",+ )++ monkeypatch.setattr(attachment_store, "pin", fail_pin)+ context = _attachment_context("pin-failure", 2)+ reservation = controller.reserve_memory_attachment_capture(+ context,+ "stable-session",+ )+ assert reservation is not None+ await controller.capture_user_memory(+ context,+ "keep this caption",+ "stable-session",+ attachment_lease=object(),+ attachment_reservation=reservation,+ )+ assert store.list_queue_rows()[0].payload_attachments is None+ _assert_single_conservation_record(caplog, total=2, captured=0)diff --git a/tests/test_memory_module.py b/tests/test_memory_module.pyindex 7c020b86f..289c1f061 100644--- a/tests/test_memory_module.py+++ b/tests/test_memory_module.py@@ -11,7 +11,7 @@ from pathlib import Pathimport pytestfrom config import paths-from core.memory.attachments import AttachmentPinStore, PinnedBundle+from core.memory.attachments import AttachmentPinError, AttachmentPinStore, PinnedBundlefrom core.memory.everos import FakeMemoryProvider, MemoryProviderFailurefrom core.memory.module import (MAX_CAPTURE_ATTACHMENT_METADATA_BYTES,@@ -385,7 +385,9 @@ async def test_capture_pins_a_real_attachment_and_forwards_the_private_copy(tmp_attachment = _source_attachment("diagram.png", b"real image bytes")source_path = Path(attachment.uri.removeprefix("file://"))- assert await module.capture(_request(attachments=(attachment,))) == CaptureAccepted()+ assert await module.capture(_request(attachments=(attachment,))) == CaptureAccepted(+ captured_attachment_count=1+ )queued = store.list_queue_rows()[0]assert queued.payload_attachments is not Noneassert queued.attachment_bundle_id is not None@@ -399,6 +401,74 @@ async def test_capture_pins_a_real_attachment_and_forwards_the_private_copy(tmp_assert store.list_queue_rows()[0].payload_attachments is None+async def test_capture_pin_failure_preserves_mixed_turn_text(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Scenario: MEMORY-IM-ATTACH-004."""++ attachment_store = _attachment_store()+ module, store, _provider = _module(tmp_path, attachment_store=attachment_store)+ attachment = _source_attachment("changed.png", b"original bytes")++ def fail_pin(*_args, **_kwargs):+ raise AttachmentPinError(+ "memory_store_unavailable",+ "leased source changed before pinning",+ )++ monkeypatch.setattr(attachment_store, "pin", fail_pin)+ mixed = replace(+ _request(source="mixed-pin-failure", attachments=(attachment,)),+ text="keep this caption",+ attachment_config_generation=7,+ )+ assert await module.capture(mixed) == CaptureAccepted()++ rows = store.list_queue_rows()+ assert len(rows) == 1+ assert rows[0].payload_text == "keep this caption"+ assert rows[0].payload_attachments is None+ assert rows[0].attachment_bundle_id is None+ attachment_only = replace(+ mixed,+ source_message_id="attachment-only-pin-failure",+ text="",+ )+ assert await module.capture(attachment_only) == OperationFailed(+ error="memory_store_unavailable"+ )+ assert len(store.list_queue_rows()) == 1+++async def test_unexpected_capture_pin_failure_preserves_mixed_turn_text(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Scenario: MEMORY-IM-ATTACH-004."""++ attachment_store = _attachment_store()+ module, store, _provider = _module(tmp_path, attachment_store=attachment_store)+ attachment = _source_attachment("unexpected.png", b"original bytes")++ def fail_pin(*_args, **_kwargs):+ raise RuntimeError("unexpected pin failure")++ monkeypatch.setattr(attachment_store, "pin", fail_pin)+ mixed = replace(+ _request(source="unexpected-pin-failure", attachments=(attachment,)),+ text="keep this caption",+ attachment_config_generation=7,+ )++ assert await module.capture(mixed) == CaptureAccepted()+ rows = store.list_queue_rows()+ assert len(rows) == 1+ assert rows[0].payload_text == "keep this caption"+ assert rows[0].payload_attachments is None+ assert rows[0].attachment_bundle_id is None++async def test_boot_reconcile_waits_for_attachment_admission_and_preserves_accepted_bundle(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,@@ -442,7 +512,7 @@ async def test_boot_reconcile_waits_for_attachment_admission_and_preserves_accepassert completed == set()allow_pin_return.set()- assert await capture == CaptureAccepted()+ assert await capture == CaptureAccepted(captured_attachment_count=1)await recoveryfinally:allow_pin_return.set()diff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.pyindex 1057011ff..1519444c5 100644--- a/tests/test_memory_runtime.py+++ b/tests/test_memory_runtime.py@@ -1723,44 +1723,6 @@ async def test_final_flush_fences_capture_before_queue_visibility(original_run_blocking = memory_module.run_blockingmonkeypatch.setattr(memory_module, "run_blocking", gate_attachment_pin)- class ObservedAdmissionLock:- def __init__(self) -> None:- self._lock = asyncio.Lock()- self._acquisitions = 0- self.final_flush_waiting = asyncio.Event()- self.later_capture_waiting = asyncio.Event()-- async def acquire(self) -> bool:- self._acquisitions += 1- if self._acquisitions == 2:- self.final_flush_waiting.set()- elif self._acquisitions == 3:- self.later_capture_waiting.set()- return await self._lock.acquire()-- def locked(self) -> bool:- return self._lock.locked()-- def release(self) -> None:- self._lock.release()-- async def __aenter__(self):- await self.acquire()- return self-- async def __aexit__(self, exc_type, exc_value, traceback) -> None:- del exc_type, exc_value, traceback- self.release()-- admission_lock = ObservedAdmissionLock()- runtime.module._capture_admission_locks[- (- old_request.principal_id,- old_request.project_id,- old_request.session_id,- )- ] = admission_lock-try:old_capture = asyncio.create_task(runtime.module.capture(old_request))await asyncio.wait_for(pin_entered.wait(), timeout=handshake_timeout_seconds)@@ -1773,16 +1735,9 @@ async def test_final_flush_fences_capture_before_queue_visibility(deadline_seconds=2.0,))- await asyncio.wait_for(- admission_lock.final_flush_waiting.wait(),- timeout=handshake_timeout_seconds,- )+ await asyncio.sleep(0)later_capture = asyncio.create_task(runtime.module.capture(later_request))- await asyncio.wait_for(- admission_lock.later_capture_waiting.wait(),- timeout=handshake_timeout_seconds,- )- assert admission_lock.locked()+ await asyncio.sleep(0)assert not final_flush.done()assert not later_capture.done()@@ -2071,6 +2026,318 @@ async def test_session_lifecycle_does_not_reset_when_capture_fence_times_out(await memory_runtime_factory.close(runtime)+async def test_deferred_capture_handoff_keeps_memory_lifecycle_fenced(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ memory_runtime_factory,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ runtime = memory_runtime_factory(+ MemoryConfig(enabled=True),+ store=MemoryStore(),+ artifact_manager=_installed_artifact(),+ effective_home=tmp_path,+ )+ request = CaptureRequest(+ source_message_id="deferred-source",+ session_id="canonical-session",+ principal_id="u-11111111111111111111111111111111",+ project_id=PROJECT,+ provenance="user_input",+ text="remember this",+ occurred_at_ms=1_725_000_001_234,+ )+ lifecycle_ran = asyncio.Event()++ async def reset_session() -> None:+ lifecycle_ran.set()++ try:+ async with runtime.module.capture_admission(+ principal_id=request.principal_id,+ project_id=request.project_id,+ session_id=request.session_id,+ ) as admission:+ lifecycle = asyncio.create_task(+ runtime.run_session_lifecycle(+ principal_id=request.principal_id,+ project_id=request.project_id,+ raw_session_id=request.session_id,+ operation=reset_session,+ deadline_seconds=2.0,+ )+ )+ await asyncio.sleep(0)+ assert not lifecycle_ran.is_set()+ assert isinstance(+ await runtime.module.capture(request, admission=admission),+ CaptureAccepted,+ )+ assert not lifecycle_ran.is_set()++ await asyncio.wait_for(lifecycle, timeout=2.0)+ assert lifecycle_ran.is_set()+ finally:+ await memory_runtime_factory.close(runtime)+++async def test_capture_reservations_are_fifo_per_session_and_parallel_across_sessions(+) -> None:+ """Scenario: MEMORY-IM-ATTACH-001."""++ module = memory_module.MemoryModule(+ MemoryStore(),+ FakeMemoryProvider(),+ enabled=True,+ )+ scope = {+ "principal_id": PRINCIPAL,+ "project_id": PROJECT,+ }+ first = module.reserve_capture_admission(**scope, session_id="same-session")+ second = module.reserve_capture_admission(**scope, session_id="same-session")+ independent = module.reserve_capture_admission(+ **scope,+ session_id="other-session",+ )+ first_entered = asyncio.Event()+ release_first = asyncio.Event()+ second_entered = asyncio.Event()+ independent_entered = asyncio.Event()++ async def hold_first() -> None:+ async with module.capture_admission(+ **scope,+ session_id="same-session",+ reservation=first,+ ):+ first_entered.set()+ await release_first.wait()++ async def enter_second() -> None:+ async with module.capture_admission(+ **scope,+ session_id="same-session",+ reservation=second,+ ):+ second_entered.set()++ async def enter_independent() -> None:+ async with module.capture_admission(+ **scope,+ session_id="other-session",+ reservation=independent,+ ):+ independent_entered.set()++ first_task = asyncio.create_task(hold_first())+ second_task = asyncio.create_task(enter_second())+ independent_task = asyncio.create_task(enter_independent())+ await asyncio.wait_for(first_entered.wait(), timeout=1.0)+ await asyncio.wait_for(independent_entered.wait(), timeout=1.0)+ assert not second_entered.is_set()++ release_first.set()+ await asyncio.wait_for(second_entered.wait(), timeout=1.0)+ await asyncio.gather(first_task, second_task, independent_task)+++async def test_unreserved_text_capture_queues_behind_existing_session_tickets() -> None:+ """Scenario: MEMORY-IM-ATTACH-001."""++ store = MemoryStore()+ module = memory_module.MemoryModule(+ store,+ FakeMemoryProvider(),+ enabled=True,+ )+ scope = {+ "principal_id": PRINCIPAL,+ "project_id": PROJECT,+ "session_id": "mixed-capture-session",+ }+ first = module.reserve_capture_admission(**scope)+ second = module.reserve_capture_admission(**scope)+ first_entered = asyncio.Event()+ release_first = asyncio.Event()++ def request(source: str, text: str) -> CaptureRequest:+ return CaptureRequest(+ source_message_id=source,+ session_id=scope["session_id"],+ principal_id=scope["principal_id"],+ project_id=scope["project_id"],+ provenance="user_input",+ text=text,+ occurred_at_ms=1_725_000_001_234,+ )++ async def capture_reserved(ticket, source: str, text: str, *, hold: bool = False):+ async with module.capture_admission(**scope, reservation=ticket) as admission:+ receipt = await module.capture(+ request(source, text),+ admission=admission,+ )+ if hold:+ first_entered.set()+ await release_first.wait()+ return receipt++ first_task = asyncio.create_task(+ capture_reserved(first, "reserved-first", "reserved first", hold=True)+ )+ second_task = asyncio.create_task(+ capture_reserved(second, "reserved-second", "reserved second")+ )+ await asyncio.wait_for(first_entered.wait(), timeout=1.0)+ text_task = asyncio.create_task(+ module.capture(request("later-text", "later text"))+ )+ await asyncio.sleep(0)++ release_first.set()+ assert await asyncio.gather(first_task, second_task, text_task) == [+ CaptureAccepted(),+ CaptureAccepted(),+ CaptureAccepted(),+ ]+ assert [row.payload_text for row in store.list_queue_rows()] == [+ "reserved first",+ "reserved second",+ "later text",+ ]+++async def test_cancelled_capture_ticket_does_not_let_successor_overtake(+) -> None:+ """Scenario: MEMORY-IM-ATTACH-004."""++ module = memory_module.MemoryModule(+ MemoryStore(),+ FakeMemoryProvider(),+ enabled=True,+ )+ scope = {+ "principal_id": PRINCIPAL,+ "project_id": PROJECT,+ "session_id": "cancelled-ticket-session",+ }+ first = module.reserve_capture_admission(**scope)+ cancelled = module.reserve_capture_admission(**scope)+ first_entered = asyncio.Event()+ release_first = asyncio.Event()+ successor_entered = asyncio.Event()++ async def hold_first() -> None:+ async with module.capture_admission(**scope, reservation=first):+ first_entered.set()+ await release_first.wait()++ async def wait_cancelled() -> None:+ async with module.capture_admission(**scope, reservation=cancelled):+ raise AssertionError("cancelled ticket entered")++ first_task = asyncio.create_task(hold_first())+ cancelled_task = asyncio.create_task(wait_cancelled())+ await asyncio.wait_for(first_entered.wait(), timeout=1.0)+ cancelled_task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await cancelled_task++ successor = module.reserve_capture_admission(**scope)++ async def enter_successor() -> None:+ async with module.capture_admission(**scope, reservation=successor):+ successor_entered.set()++ successor_task = asyncio.create_task(enter_successor())+ await asyncio.sleep(0)+ assert not successor_entered.is_set()++ release_first.set()+ await asyncio.wait_for(successor_entered.wait(), timeout=1.0)+ await asyncio.gather(first_task, successor_task)+++async def test_session_lifecycle_barrier_waits_for_registered_capture_tickets() -> None:+ """Scenario: MEMORY-IM-ATTACH-001."""++ module = memory_module.MemoryModule(+ MemoryStore(),+ FakeMemoryProvider(),+ enabled=True,+ )+ scope = {+ "principal_id": PRINCIPAL,+ "project_id": PROJECT,+ "session_id": "barrier-session",+ }+ first = module.reserve_capture_admission(**scope)+ second = module.reserve_capture_admission(**scope)+ release_first = asyncio.Event()+ release_second = asyncio.Event()+ first_entered = asyncio.Event()+ second_entered = asyncio.Event()+ lifecycle_ran = asyncio.Event()++ async def capture(ticket, entered: asyncio.Event, release: asyncio.Event) -> None:+ async with module.capture_admission(**scope, reservation=ticket):+ entered.set()+ await release.wait()++ async def reset() -> None:+ lifecycle_ran.set()++ first_task = asyncio.create_task(capture(first, first_entered, release_first))+ second_task = asyncio.create_task(capture(second, second_entered, release_second))+ await asyncio.wait_for(first_entered.wait(), timeout=1.0)+ lifecycle = asyncio.create_task(+ module.run_session_lifecycle(+ principal_id=PRINCIPAL,+ project_id=PROJECT,+ raw_session_id="barrier-session",+ operation=reset,+ deadline_seconds=1.0,+ )+ )+ await asyncio.sleep(0)+ assert not lifecycle_ran.is_set()++ release_first.set()+ await asyncio.wait_for(second_entered.wait(), timeout=1.0)+ assert not lifecycle_ran.is_set()+ release_second.set()++ await asyncio.gather(first_task, second_task, lifecycle)+ assert lifecycle_ran.is_set()+++async def test_session_lifecycle_ticket_barrier_is_bounded() -> None:+ """Scenario: MEMORY-IM-ATTACH-003."""++ module = memory_module.MemoryModule(+ MemoryStore(),+ FakeMemoryProvider(),+ enabled=True,+ )+ reservation = module.reserve_capture_admission(+ principal_id=PRINCIPAL,+ project_id=PROJECT,+ session_id="stalled-session",+ )++ with pytest.raises(MemorySessionLifecycleBusyError, match="did not quiesce"):+ await module.run_session_lifecycle(+ principal_id=PRINCIPAL,+ project_id=PROJECT,+ raw_session_id="stalled-session",+ operation=lambda: asyncio.sleep(0),+ deadline_seconds=0.01,+ )++ module.cancel_capture_reservation(reservation)++async def test_retired_close_aborts_when_claim_quiescence_times_out(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,@@ -2322,7 +2589,9 @@ async def test_memory_clear_201_discards_manual_required_evidence_and_allows_new),),)- assert await runtime.module.capture(first) == CaptureAccepted()+ assert await runtime.module.capture(first) == CaptureAccepted(+ captured_attachment_count=1+ )assert await runtime.module.drain() == 1ambiguous = runtime._store.list_queue_rows()@@ -3632,7 +3901,6 @@ async def test_status_preserves_everos_disabled_recorder_state(memory_runtime_factory,) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setattr(memory_runtime, "IM_ATTACHMENT_CAPTURE_AVAILABLE", True)config = MemoryConfig(enabled=True,processing=replace(@@ -3688,7 +3956,6 @@ async def test_attachment_capture_status_rejects_stale_runtime_health(memory_runtime_factory,) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setattr(memory_runtime, "IM_ATTACHMENT_CAPTURE_AVAILABLE", True)config = MemoryConfig(enabled=True,processing=replace(@@ -3739,7 +4006,7 @@ async def test_attachment_capture_status_rejects_stale_runtime_health(await memory_runtime_factory.close(runtime)-def test_attachment_capture_status_stays_unavailable_until_im_capture_lands() -> None:+def test_attachment_capture_status_becomes_ready_after_slack_capture_lands() -> None:config = MemoryConfig(enabled=True,processing=replace(@@ -3756,10 +4023,7 @@ def test_attachment_capture_status_stays_unavailable_until_im_capture_lands() ->"disabled_features": [],}- assert (- memory_runtime._attachment_capture_status(config, "available", health)- == "unavailable"- )+ assert memory_runtime._attachment_capture_status(config, "available", health) == "ready"async def test_recorder_reap_hands_call_log_to_host_until_restart(@@ -5725,6 +5989,32 @@ def _processing_config() -> MemoryProcessingConfig:)+async def test_attachment_capture_config_generation_is_transition_bound(+ memory_runtime_factory,+) -> None:+ processing = replace(+ _processing_config(),+ multimodal=MemoryEndpointConfig(+ "https://vision.example.test/v1",+ "vision-model",+ "vision-secret",+ ),+ )+ runtime = memory_runtime_factory(+ MemoryConfig(enabled=True, processing=processing),+ artifact_manager=_installed_artifact(),+ )++ before = runtime.attachment_capture_config_generation()+ assert isinstance(before, int)+ async with runtime._reconcile_lock:+ assert runtime.attachment_capture_config_generation() is None+ after = runtime.attachment_capture_config_generation()++ assert isinstance(after, int)+ assert after > before++async def test_runtime_restart_replaces_process_without_processing_preflight(tmp_path: Path,memory_runtime_factory,diff --git a/tests/test_memory_slice3.py b/tests/test_memory_slice3.pyindex e23aad09d..553a4e0b0 100644--- a/tests/test_memory_slice3.py+++ b/tests/test_memory_slice3.py@@ -7,16 +7,26 @@ import asyncioimport gcimport jsonimport sys+import threadingimport weakref+from contextlib import asynccontextmanagerfrom pathlib import Pathfrom types import SimpleNamespace+from unittest.mock import Mockimport pytestfrom config.v2_config import MemoryConfig, MemoryEndpointConfig, MemoryProcessingConfigfrom core.controller import Controllerfrom core.handlers.message_handler import MessageHandler-from core.memory import CaptureAccepted, CaptureDuplicate, CaptureRequest, CaptureSkipped+from core.memory import (+ CaptureAccepted,+ CaptureAttachment,+ CaptureDuplicate,+ CaptureRequest,+ CaptureSkipped,+ MemoryModule,+)from core.memory.artifact import FakeMemoryArtifactManagerfrom core.memory.everos import FakeMemoryProviderfrom core.memory.runtime import MemoryRuntime@@ -25,6 +35,7 @@ from modules.im.base import FileAttachment, MessageContextfrom modules.im.message_facts import (is_ordinary_discord_text,is_ordinary_feishu_text,+ is_ordinary_slack_attachment,is_ordinary_slack_text,is_ordinary_telegram_text,is_ordinary_wechat_text,@@ -61,6 +72,8 @@ class _Runtime:self.module = moduleself.available = Trueself.retired = False+ self.attachment_status = "ready"+ self.attachment_generation: int | None = 1self.final_flush_calls: list[dict[str, object]] = []self.final_flush_result = Trueself.final_flush_error: Exception | None = None@@ -79,6 +92,12 @@ class _Runtime:assert workdir == "/tmp/project"return PROJECT+ async def attachment_capture_status(self) -> str:+ return self.attachment_status++ def attachment_capture_config_generation(self) -> int | None:+ return self.attachment_generation+async def resolve_current_session_scope(self, raw_session_id: str) -> tuple[str, str] | None:self.scope_recovery_calls.append(raw_session_id)return self.recovered_scope@@ -115,19 +134,45 @@ class _CaptureModule:def __init__(self) -> None:self.accepted = []self.seen: set[str] = set()+ self.reservations: list[object] = []++ def reserve_capture_admission(self, **_scope):+ reservation = object()+ self.reservations.append(reservation)+ return reservation++ def cancel_capture_reservation(self, _reservation):+ return None- async def capture(self, request):+ @asynccontextmanager+ async def capture_admission(self, **_scope):+ yield object()++ async def capture(self, request, **_options):if request.source_message_id in self.seen:return CaptureDuplicate()self.seen.add(request.source_message_id)self.accepted.append(request)- return CaptureAccepted()+ return CaptureAccepted(+ captured_attachment_count=len(request.attachments)+ )def _controller(*, user=None):user = user or SimpleNamespace(enabled=True, is_admin=False)controller = Controller.__new__(Controller)- controller.config = SimpleNamespace(memory=SimpleNamespace(enabled=True))+ controller.config = SimpleNamespace(+ memory=SimpleNamespace(+ enabled=True,+ processing=MemoryProcessingConfig(+ multimodal=MemoryEndpointConfig(+ base_url="https://multimodal.test/v1",+ model="vision-test",+ api_key="secret",+ )+ ),+ )+ )controller.platform_settings_managers = {platform: _Manager(user)for platform in ("slack", "discord", "telegram", "feishu", "wechat", "lark")@@ -201,6 +246,31 @@ def test_message_handler_drains_memory_capture_tasks() -> None:asyncio.run(run())+def test_message_handler_cancels_and_joins_memory_capture_tasks() -> None:+ handler = MessageHandler.__new__(MessageHandler)+ handler._memory_capture_tasks = set()+ released = Mock()++ async def run() -> None:+ started = asyncio.Event()++ async def capture() -> None:+ started.set()+ await asyncio.Event().wait()++ task = asyncio.create_task(capture())+ handler._track_memory_capture_task(task, attachment_lease=released)+ await started.wait()++ await handler.cancel_memory_capture_tasks()++ assert task.cancelled()+ assert handler._memory_capture_tasks == set()+ released.release.assert_called_once_with()++ asyncio.run(run())++@pytest.mark.parametrize("platform", ["slack", "discord", "telegram", "feishu", "wechat"])def test_capture_admits_every_enabled_bound_dm_user(platform: str) -> None:controller = _controller(user=SimpleNamespace(enabled=True, is_admin=False))@@ -209,6 +279,384 @@ def test_capture_admits_every_enabled_bound_dm_user(platform: str) -> None:assert controller.memory_capture_admitted(_context(platform, is_dm=False)) is False[email protected]("status", ["ready", "unavailable"])+def test_slack_memory_lease_retention_is_local_and_ignores_runtime_health(+ status: str,+) -> None:+ """Scenarios: MEMORY-IM-ATTACH-001, MEMORY-IM-ATTACH-003."""++ controller = _controller()+ controller.memory_runtime.attachment_status = status+ context = _context("slack", ordinary=False)+ context.files = [+ FileAttachment(+ name="receipt.pdf",+ mimetype="application/pdf",+ url="https://files.slack.test/private",+ )+ ]+ context.is_ordinary_attachment = True++ reservation = controller.reserve_memory_attachment_capture(+ context,+ "stable-session",+ )++ assert reservation is not None+ assert reservation.config_generation == 1+++def test_slack_memory_reservation_survives_without_multimodal_opt_in() -> None:+ """Scenario: MEMORY-IM-ATTACH-003."""++ controller = _controller()+ controller.memory_runtime.attachment_generation = None+ context = _context("slack", ordinary=False)+ context.files = [+ FileAttachment(+ name="receipt.pdf",+ mimetype="application/pdf",+ url="https://files.slack.test/private",+ )+ ]+ context.is_ordinary_attachment = True++ reservation = controller.reserve_memory_attachment_capture(+ context,+ "stable-session",+ )++ assert reservation is not None+ assert reservation.config_generation is None+++def test_attachment_reservation_failure_preserves_caption_as_text_only() -> None:+ """Scenario: MEMORY-IM-ATTACH-004."""++ controller = _controller()+ controller.memory_module.reserve_capture_admission = Mock(+ side_effect=RuntimeError("reservation unavailable")+ )+ context = _context("slack", ordinary=False)+ context.files = [+ FileAttachment(+ name="receipt.pdf",+ mimetype="application/pdf",+ url="https://files.slack.test/private",+ )+ ]+ context.is_ordinary_attachment = True++ reservation = controller.reserve_memory_attachment_capture(+ context,+ "stable-session",+ )+ assert reservation is None++ asyncio.run(+ controller.capture_user_memory(+ context,+ "keep the caption",+ "stable-session",+ attachment_reservation=reservation,+ )+ )++ assert len(controller.memory_module.accepted) == 1+ request = controller.memory_module.accepted[0]+ assert request.text == "keep the caption"+ assert request.attachments == ()+++def test_retained_lease_failure_preserves_reserved_caption_as_text_only() -> None:+ """Scenario: MEMORY-IM-ATTACH-004."""++ controller = _controller()+ context = _context("slack", ordinary=False)+ context.files = [+ FileAttachment(+ name="receipt.pdf",+ mimetype="application/pdf",+ url="https://files.slack.test/private",+ )+ ]+ context.is_ordinary_attachment = True+ reservation = controller.reserve_memory_attachment_capture(+ context,+ "stable-session",+ )+ assert reservation is not None++ asyncio.run(+ controller.capture_user_memory(+ context,+ "keep the caption",+ "stable-session",+ attachment_reservation=reservation,+ attachment_text_only=True,+ )+ )++ assert len(controller.memory_module.accepted) == 1+ request = controller.memory_module.accepted[0]+ assert request.text == "keep the caption"+ assert request.attachments == ()+++def test_slack_without_multimodal_opt_in_skips_live_health_read() -> None:+ """Scenario: MEMORY-IM-ATTACH-003."""++ async def run() -> None:+ controller = _controller()+ store = MemoryStore()+ module = MemoryModule(store, FakeMemoryProvider(), enabled=True)+ controller.memory_module = module+ controller.memory_runtime = _Runtime(module)+ controller.memory_runtime.attachment_generation = None+ health_reads = 0++ async def attachment_capture_status() -> str:+ nonlocal health_reads+ health_reads += 1+ await asyncio.Event().wait()+ return "ready"++ controller.memory_runtime.attachment_capture_status = attachment_capture_status+ context = _context("slack", ordinary=False)+ context.files = [+ FileAttachment(+ name="receipt.pdf",+ mimetype="application/pdf",+ url="https://files.slack.test/private",+ )+ ]+ context.is_ordinary_attachment = True+ reservation = controller.reserve_memory_attachment_capture(+ context,+ "stable-session",+ )+ assert reservation is not None+ assert reservation.config_generation is None++ await asyncio.wait_for(+ controller.capture_user_memory(+ context,+ "keep the caption",+ "stable-session",+ attachment_reservation=reservation,+ ),+ timeout=1.0,+ )++ assert health_reads == 0+ rows = store.list_queue_rows()+ assert len(rows) == 1+ assert rows[0].payload_text == "keep the caption"+ assert rows[0].payload_attachments is None++ reset_ran = False++ async def reset() -> None:+ nonlocal reset_ran+ reset_ran = True++ await asyncio.wait_for(+ module.run_session_lifecycle(+ principal_id="u-" + ("1" * 32),+ project_id=PROJECT,+ raw_session_id="stable-session",+ operation=reset,+ deadline_seconds=1.0,+ ),+ timeout=1.5,+ )+ assert reset_ran is True++ asyncio.run(run())+++def test_attachment_capture_hands_off_before_runtime_health_read() -> None:+ """Scenario: MEMORY-IM-ATTACH-001."""++ async def run() -> None:+ controller = _controller()+ health_started = asyncio.Event()+ release_health = asyncio.Event()++ async def attachment_capture_status() -> str:+ health_started.set()+ await release_health.wait()+ return "unavailable"++ controller.memory_runtime.attachment_capture_status = attachment_capture_status+ context = _context("slack", ordinary=False)+ context.files = [+ FileAttachment(+ name="receipt.pdf",+ mimetype="application/pdf",+ url="https://files.slack.test/private",+ )+ ]+ context.is_ordinary_attachment = True+ reservation = controller.reserve_memory_attachment_capture(+ context,+ "stable-session",+ )+ assert reservation is not None++ capture = asyncio.create_task(+ controller.capture_user_memory(+ context,+ "remember this",+ "stable-session",+ attachment_lease=object(),+ attachment_reservation=reservation,+ )+ )+ await asyncio.wait_for(health_started.wait(), timeout=1.0)+ assert not capture.done()++ release_health.set()+ await asyncio.wait_for(capture, timeout=1.0)++ asyncio.run(run())+++def test_attachment_selection_runs_off_event_loop(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Scenario: MEMORY-IM-ATTACH-001."""++ async def run() -> None:+ controller = _controller()+ event_loop_thread = threading.get_ident()+ binding_threads: list[int] = []+ settings_store = controller.platform_settings_managers["slack"].get_store()+ original_maybe_reload = settings_store.maybe_reload++ def observe_settings_access() -> None:+ binding_threads.append(threading.get_ident())+ original_maybe_reload()++ monkeypatch.setattr(settings_store, "maybe_reload", observe_settings_access)+ attachment = CaptureAttachment(+ kind="pdf",+ name="receipt.pdf",+ uri="file:///leased/receipt.pdf",+ ext="pdf",+ )+ selector_threads: list[int] = []+ release_selection = threading.Event()+ released_by_event_loop: list[bool] = []++ def select_attachments(_lease):+ selector_threads.append(threading.get_ident())+ released_by_event_loop.append(release_selection.wait(timeout=1.0))+ return SimpleNamespace(attachments=(attachment,), skipped=())++ monkeypatch.setattr(+ "core.memory.admission.select_memory_attachments",+ select_attachments,+ )+ context = _context("slack", ordinary=False)+ context.files = [+ FileAttachment(+ name="receipt.pdf",+ mimetype="application/pdf",+ url="https://files.slack.test/private",+ )+ ]+ context.is_ordinary_attachment = True+ reservation = controller.reserve_memory_attachment_capture(+ context,+ "stable-session",+ )+ assert reservation is not None++ asyncio.get_running_loop().call_later(0.05, release_selection.set)+ await asyncio.wait_for(+ controller.capture_user_memory(+ context,+ "remember this",+ "stable-session",+ attachment_lease=object(),+ attachment_reservation=reservation,+ ),+ timeout=2.0,+ )++ assert binding_threads and set(binding_threads) == {event_loop_thread}+ assert selector_threads and selector_threads[0] != event_loop_thread+ assert released_by_event_loop == [True]++ asyncio.run(run())+++def test_attachment_capture_fails_closed_when_config_generation_changes(+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ """Scenario: MEMORY-IM-ATTACH-003."""++ caplog.set_level("INFO", logger="core.memory.admission")++ async def run() -> None:+ controller = _controller()+ attachment = CaptureAttachment(+ kind="pdf",+ name="receipt.pdf",+ uri="file:///leased/receipt.pdf",+ ext="pdf",+ )+ monkeypatch.setattr(+ "core.memory.admission.select_memory_attachments",+ lambda _lease: SimpleNamespace(attachments=(attachment,), skipped=()),+ )++ async def attachment_capture_status() -> str:+ controller.memory_runtime.attachment_generation = 2+ return "ready"++ controller.memory_runtime.attachment_capture_status = attachment_capture_status+ context = _context("slack", ordinary=False)+ context.files = [+ FileAttachment(+ name="receipt.pdf",+ mimetype="application/pdf",+ url="https://files.slack.test/private",+ )+ ]+ context.is_ordinary_attachment = True+ reservation = controller.reserve_memory_attachment_capture(+ context,+ "stable-session",+ )+ assert reservation is not None++ await controller.capture_user_memory(+ context,+ "keep the caption",+ "stable-session",+ attachment_lease=object(),+ attachment_reservation=reservation,+ )++ assert len(controller.memory_module.accepted) == 1+ request = controller.memory_module.accepted[0]+ assert request.text == "keep the caption"+ assert request.attachments == ()+ assert request.attachment_config_generation is None++ asyncio.run(run())+ records = [+ record+ for record in caplog.records+ if record.message.startswith("memory_attachment_capture ")+ ]+ assert len(records) == 1+ assert "platform=slack total=1 captured=0 dropped=1" in records[0].getMessage()++@pytest.mark.parametrize("context,text,enabled",[@@ -1021,6 +1469,14 @@ def test_slack_non_text_block_payloads_are_not_ordinary() -> None:],)assert is_ordinary_slack_text(upload, None) is False+ extracted_upload = [+ FileAttachment(+ name="screenshot.png",+ mimetype="image/png",+ url="https://files.slack.com/files-pri/T04-F04/screenshot.png",+ )+ ]+ assert is_ordinary_slack_attachment(upload, extracted_upload) is True# Forwarded / shared message: composer rich text PLUS a share attachment.forwarded = _slack_dm_event(@@ -1037,6 +1493,7 @@ def test_slack_non_text_block_payloads_are_not_ordinary() -> None:],)assert is_ordinary_slack_text(forwarded, None) is False+ assert is_ordinary_slack_attachment(forwarded, extracted_upload) is False# App-authored layout blocks are not composer output, even without ``bot_id``.app_blocks = _slack_dm_event(@@ -1047,6 +1504,7 @@ def test_slack_non_text_block_payloads_are_not_ordinary() -> None:],)assert is_ordinary_slack_text(app_blocks, None) is False+ assert is_ordinary_slack_attachment(app_blocks, extracted_upload) is False# An unrecognized node inside rich text fails closed.unknown_element = _slack_dm_event(diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex 30ffa4bd2..b65c81da3 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -1,6 +1,8 @@import asyncioimport importlib.util+import osimport sys+import tempfileimport typesimport unittestfrom dataclasses import dataclass@@ -269,6 +271,10 @@ class _StubController:return "en"+def _capture_reservation(generation: int | None = 1):+ return types.SimpleNamespace(config_generation=generation, release=Mock())++class _StubSessionHandler:def __init__(self):self.alias_calls = []@@ -461,6 +467,229 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):lease.adopt.assert_called_once_with()lease.release.assert_called_once_with()+ async def test_memory_attachment_capture_starts_after_one_shared_materialization(self):+ """Scenario: MEMORY-IM-ATTACH-001."""++ from modules.im.base import FileAttachment++ controller = _StubController(+ platform="slack",+ ack_mode="reaction",+ typing_result=True,+ )+ controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())+ reservation = _capture_reservation()+ controller.reserve_memory_attachment_capture = Mock(+ return_value=reservation+ )+ events = []+ retained_lease = Mock()+ lease = Mock()+ lease.retain.return_value = retained_lease+ attachment = FileAttachment(+ name="report.pdf",+ mimetype="application/pdf",+ local_path="/tmp/leased-report.pdf",+ size=10,+ )++ async def capture_user_memory(+ _context,+ _text,+ _session_id,+ *,+ attachment_lease,+ attachment_reservation,+ attachment_config_generation,+ ):+ self.assertIs(attachment_reservation, reservation)+ self.assertEqual(attachment_config_generation, 1)+ events.append(("capture", attachment_lease))++ controller.capture_user_memory = capture_user_memory+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(return_value="review this")++ async def materialize(_context, _working_path):+ events.append(("materialize", None))+ return types.SimpleNamespace(+ attachments=(attachment,),+ display_errors=(),+ errors=("download_failed",),+ lease=lease,+ )++ handler._materialize_file_attachments = AsyncMock(side_effect=materialize)++ async def admit(**kwargs):+ events.append(("agent-admission", kwargs["attachment_lease"]))+ lease.adopt()+ lease.release()+ return True++ handler._admit_human_delivery = AsyncMock(side_effect=admit)+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ message_id="m-memory-attachment",+ platform="slack",+ platform_specific={"is_dm": True},+ files=[FileAttachment("report.pdf", "application/pdf", url="private")],+ is_ordinary_attachment=True,+ )++ await handler.handle_user_message(context, "remember this")+ await handler.drain_memory_capture_tasks()++ handler._materialize_file_attachments.assert_awaited_once()+ controller.reserve_memory_attachment_capture.assert_called_once_with(+ context,+ "base-session",+ )+ lease.retain.assert_called_once_with()+ retained_lease.release.assert_called_once_with()+ self.assertLess(+ [kind for kind, _value in events].index("materialize"),+ [kind for kind, _value in events].index("capture"),+ )+ self.assertIn(("capture", retained_lease), events)++ async def test_memory_lease_retain_failure_still_schedules_caption_capture(self):+ """Scenario: MEMORY-IM-ATTACH-004."""++ from modules.im.base import FileAttachment++ controller = _StubController(+ platform="slack",+ ack_mode="reaction",+ typing_result=True,+ )+ controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())+ reservation = _capture_reservation()+ controller.reserve_memory_attachment_capture = Mock(+ return_value=reservation+ )+ captured = []++ async def capture_user_memory(+ _context,+ text,+ _session_id,+ *,+ attachment_reservation,+ attachment_config_generation,+ attachment_text_only,+ ):+ self.assertIs(attachment_reservation, reservation)+ self.assertEqual(attachment_config_generation, 1)+ self.assertIs(attachment_text_only, True)+ captured.append(text)++ controller.capture_user_memory = capture_user_memory+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(return_value="remember this")+ lease = Mock()+ lease.retain.side_effect = RuntimeError("retain failed")+ attachment = FileAttachment(+ name="report.pdf",+ mimetype="application/pdf",+ local_path="/tmp/leased-report.pdf",+ size=10,+ )+ handler._materialize_file_attachments = AsyncMock(+ return_value=types.SimpleNamespace(+ attachments=(attachment,),+ display_errors=(),+ lease=lease,+ )+ )++ async def admit(**_kwargs):+ lease.adopt()+ lease.release()+ return True++ handler._admit_human_delivery = AsyncMock(side_effect=admit)+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ message_id="m-retain-failure",+ platform="slack",+ platform_specific={"is_dm": True},+ files=[FileAttachment("report.pdf", "application/pdf", url="private")],+ is_ordinary_attachment=True,+ )++ await handler.handle_user_message(context, "remember this")+ await handler.drain_memory_capture_tasks()++ self.assertEqual(captured, ["remember this"])+ lease.retain.assert_called_once_with()+ lease.adopt.assert_called_once_with()+ lease.release.assert_called_once_with()++ async def test_denied_attachment_turn_does_not_retain_a_memory_lease(self):+ """Scenario: MEMORY-IM-ATTACH-002."""++ from modules.im.base import FileAttachment++ controller = _StubController(+ platform="slack",+ ack_mode="reaction",+ typing_result=True,+ )+ controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())+ controller.reserve_memory_attachment_capture = Mock(return_value=None)+ controller.capture_user_memory = AsyncMock()+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(return_value="review this")+ lease = Mock()+ attachment = FileAttachment(+ name="report.pdf",+ mimetype="application/pdf",+ local_path="/tmp/leased-report.pdf",+ size=10,+ )+ handler._materialize_file_attachments = AsyncMock(+ return_value=types.SimpleNamespace(+ attachments=(attachment,),+ display_errors=(),+ lease=lease,+ )+ )++ async def admit(**_kwargs):+ lease.adopt()+ lease.release()+ return True++ handler._admit_human_delivery = AsyncMock(side_effect=admit)+ context = MessageContext(+ user_id="U1",+ channel_id="C-public",+ message_id="m-denied-memory-attachment",+ platform="slack",+ platform_specific={"is_dm": False},+ files=[FileAttachment("report.pdf", "application/pdf", url="private")],+ is_ordinary_attachment=True,+ )++ await handler.handle_user_message(context, "review this")+ await handler.drain_memory_capture_tasks()++ lease.retain.assert_not_called()+ controller.capture_user_memory.assert_called_once()+ args, kwargs = controller.capture_user_memory.call_args+ self.assertEqual(args, (context, "review this", "base-session"))+ self.assertIsNone(kwargs["attachment_reservation"])+ self.assertNotIn("attachment_lease", kwargs)+async def test_failed_durable_admission_releases_unowned_attachment_lease(self):from modules.im.base import FileAttachment@@ -714,6 +943,717 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):admission = await asyncio.wait_for(blocked_lifecycle, timeout=1.0)admission.release()+ async def test_text_memory_capture_starts_before_agent_route_resolution(self):+ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ captured = asyncio.Event()++ async def capture_user_memory(_context, _text, session_id):+ self.assertEqual(session_id, "base-session")+ captured.set()++ controller.capture_user_memory = capture_user_memory+ controller.resolve_vibe_agent_for_context = Mock(+ side_effect=RuntimeError("route unavailable")+ )+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ message_id="m-early-memory",+ platform="slack",+ )++ await handler.handle_user_message(context, "remember this")+ await handler.drain_memory_capture_tasks()++ assert captured.is_set()++ async def test_shutdown_quiesce_prevents_late_text_capture_registration(self):+ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ lifecycle_admission = Mock()+ controller.session_turns = types.SimpleNamespace(+ acquire_lifecycle_admission=AsyncMock(+ return_value=lifecycle_admission+ ),+ )+ controller.capture_user_memory = AsyncMock()+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler.quiesce_memory_capture_tasks()+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ message_id="m-quiesced-text-memory",+ platform="slack",+ )++ await handler.handle_user_message(context, "remember this")++ controller.capture_user_memory.assert_not_called()+ lifecycle_admission.release.assert_called_once_with()+ assert handler._memory_capture_tasks == set()++ async def test_attachment_capture_uses_anchor_before_agent_variant_namespace(self):+ from modules.im.base import FileAttachment++ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())+ reservation = _capture_reservation()+ controller.reserve_memory_attachment_capture = Mock(+ return_value=reservation+ )+ captured_session_ids = []+ lease = Mock()+ retained_lease = Mock()+ lease.retain.return_value = retained_lease+ attachment = FileAttachment(+ name="report.pdf",+ mimetype="application/pdf",+ local_path="/tmp/leased-report.pdf",+ size=10,+ )++ async def capture_user_memory(+ _context,+ _text,+ session_id,+ *,+ attachment_lease,+ attachment_reservation,+ attachment_config_generation,+ ):+ self.assertIs(attachment_lease, retained_lease)+ self.assertIs(attachment_reservation, reservation)+ self.assertEqual(attachment_config_generation, 1)+ captured_session_ids.append(session_id)++ controller.capture_user_memory = capture_user_memory+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(return_value="review this")+ handler._materialize_file_attachments = AsyncMock(+ return_value=types.SimpleNamespace(+ attachments=(attachment,),+ display_errors=(),+ lease=lease,+ )+ )++ async def admit(**kwargs):+ self.assertEqual(kwargs["session_anchor"], "base-session:researcher")+ lease.adopt()+ lease.release()+ return True++ handler._admit_human_delivery = AsyncMock(side_effect=admit)+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ message_id="m-canonical-memory",+ platform="slack",+ platform_specific={+ "is_dm": True,+ "agent_run_target": {"agent_variant": "researcher"},+ },+ files=[FileAttachment("report.pdf", "application/pdf", url="private")],+ is_ordinary_attachment=True,+ )++ await handler.handle_user_message(context, "remember this")+ await handler.drain_memory_capture_tasks()++ self.assertEqual(captured_session_ids, ["base-session"])++ async def test_attachment_capture_releases_turn_fence_before_background_work(self):+ from modules.im.base import FileAttachment++ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ lifecycle_released = asyncio.Event()+ capture_can_finish = asyncio.Event()+ capture_finished = asyncio.Event()++ async def acquire_lifecycle_admission(session_id):+ self.assertEqual(session_id, "base-session")++ class Admission:+ def release(self):+ lifecycle_released.set()++ return Admission()++ controller.session_turns = types.SimpleNamespace(+ deliver=AsyncMock(),+ acquire_lifecycle_admission=acquire_lifecycle_admission,+ )+ reservation = _capture_reservation()+ controller.reserve_memory_attachment_capture = Mock(+ return_value=reservation+ )+ lease = Mock()+ retained_lease = Mock()+ lease.retain.return_value = retained_lease+ attachment = FileAttachment(+ name="report.pdf",+ mimetype="application/pdf",+ local_path="/tmp/leased-report.pdf",+ size=10,+ )++ async def capture_user_memory(+ _context,+ _text,+ _session_id,+ *,+ attachment_lease,+ attachment_reservation,+ attachment_config_generation,+ ):+ self.assertIs(attachment_lease, retained_lease)+ self.assertIs(attachment_reservation, reservation)+ self.assertEqual(attachment_config_generation, 1)+ await capture_can_finish.wait()+ capture_finished.set()++ controller.capture_user_memory = capture_user_memory+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(return_value="review this")+ handler._materialize_file_attachments = AsyncMock(+ return_value=types.SimpleNamespace(+ attachments=(attachment,),+ display_errors=(),+ lease=lease,+ )+ )++ async def admit(**_kwargs):+ assert lifecycle_released.is_set()+ assert not capture_finished.is_set()+ lease.adopt()+ lease.release()+ return True++ handler._admit_human_delivery = AsyncMock(side_effect=admit)+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ message_id="m-background-memory",+ platform="slack",+ platform_specific={"is_dm": True},+ files=[FileAttachment("report.pdf", "application/pdf", url="private")],+ is_ordinary_attachment=True,+ )++ await asyncio.wait_for(+ handler.handle_user_message(context, "remember this"),+ timeout=1.0,+ )++ assert lifecycle_released.is_set()+ assert not capture_finished.is_set()+ handler._admit_human_delivery.assert_awaited_once()+ capture_can_finish.set()+ await handler.drain_memory_capture_tasks()+ retained_lease.release.assert_called_once_with()++ async def test_session_reset_during_download_drops_stale_attachment_without_waiting(+ self,+ ):+ """Scenario: MEMORY-IM-ATTACH-004."""++ from core.session_turns import SessionTurnManager+ from modules.im.base import FileAttachment++ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ controller.session_turns = SessionTurnManager(controller)+ controller.reserve_memory_attachment_capture = Mock(+ return_value=_capture_reservation()+ )+ controller.capture_user_memory = AsyncMock()+ download_started = asyncio.Event()+ release_download = asyncio.Event()+ lease = Mock()+ attachment = FileAttachment(+ name="report.pdf",+ mimetype="application/pdf",+ local_path="/tmp/leased-report.pdf",+ size=10,+ )++ async def materialize(_context, _working_path):+ download_started.set()+ await release_download.wait()+ return types.SimpleNamespace(+ attachments=(attachment,),+ display_errors=(),+ errors=(),+ lease=lease,+ )++ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(return_value="review this")+ handler._materialize_file_attachments = materialize++ async def admit(**kwargs):+ admitted_lease = kwargs["attachment_lease"]+ admitted_lease.adopt()+ admitted_lease.release()+ return True++ handler._admit_human_delivery = AsyncMock(side_effect=admit)+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ message_id="m-reset-during-download",+ platform="slack",+ platform_specific={"is_dm": True},+ files=[FileAttachment("report.pdf", "application/pdf", url="private")],+ is_ordinary_attachment=True,+ )++ turn = asyncio.create_task(+ handler.handle_user_message(context, "keep this caption")+ )+ await asyncio.wait_for(download_started.wait(), timeout=1.0)+ reset_completed = asyncio.Event()++ async def reset_operation():+ reset_completed.set()+ return "reset"++ reset = await asyncio.wait_for(+ controller.session_turns.run_session_lifecycle(+ "base-session",+ reset_operation,+ deadline_seconds=0.05,+ ),+ timeout=0.1,+ )+ self.assertEqual(reset, "reset")+ assert reset_completed.is_set()+ assert not turn.done()++ release_download.set()+ await asyncio.wait_for(turn, timeout=1.0)+ await handler.drain_memory_capture_tasks()++ controller.reserve_memory_attachment_capture.assert_not_called()+ lease.retain.assert_not_called()+ controller.capture_user_memory.assert_awaited_once()+ capture_call = controller.capture_user_memory.await_args+ self.assertEqual(capture_call.args[1], "keep this caption")+ self.assertIsNone(capture_call.kwargs["attachment_reservation"])+ self.assertIsNone(capture_call.kwargs["attachment_config_generation"])++ async def test_second_same_session_attachment_turn_does_not_wait_for_first_capture(+ self,+ ):+ """Scenario: MEMORY-IM-ATTACH-001."""++ from modules.im.base import FileAttachment++ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ released_admissions = []++ async def acquire_lifecycle_admission(session_id):+ self.assertEqual(session_id, "base-session")++ class Admission:+ def release(self):+ released_admissions.append(session_id)++ return Admission()++ controller.session_turns = types.SimpleNamespace(+ deliver=AsyncMock(),+ acquire_lifecycle_admission=acquire_lifecycle_admission,+ )+ reservations = [_capture_reservation(), _capture_reservation()]+ controller.reserve_memory_attachment_capture = Mock(+ side_effect=reservations+ )+ first_capture_started = asyncio.Event()+ release_first_capture = asyncio.Event()+ second_capture_started = asyncio.Event()+ capture_index = 0++ async def capture_user_memory(+ _context,+ _text,+ _session_id,+ **_options,+ ):+ nonlocal capture_index+ index = capture_index+ capture_index += 1+ if index == 0:+ first_capture_started.set()+ await release_first_capture.wait()+ return+ await release_first_capture.wait()+ second_capture_started.set()++ controller.capture_user_memory = capture_user_memory+ leases = [Mock(), Mock()]+ retained = [Mock(), Mock()]+ for lease, retained_lease in zip(leases, retained, strict=True):+ lease.retain.return_value = retained_lease+ attachments = [+ FileAttachment(+ name=f"report-{index}.pdf",+ mimetype="application/pdf",+ local_path=f"/tmp/leased-report-{index}.pdf",+ size=10,+ )+ for index in range(2)+ ]+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(return_value="review this")+ handler._materialize_file_attachments = AsyncMock(+ side_effect=[+ types.SimpleNamespace(+ attachments=(attachment,),+ display_errors=(),+ lease=lease,+ )+ for attachment, lease in zip(attachments, leases, strict=True)+ ]+ )++ async def admit(**kwargs):+ lease = kwargs["attachment_lease"]+ lease.adopt()+ lease.release()+ return True++ handler._admit_human_delivery = AsyncMock(side_effect=admit)++ async def send(index: int) -> None:+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ message_id=f"m-overlap-{index}",+ platform="slack",+ platform_specific={"is_dm": True},+ files=[+ FileAttachment(+ f"report-{index}.pdf",+ "application/pdf",+ url="private",+ )+ ],+ is_ordinary_attachment=True,+ )+ await handler.handle_user_message(context, "remember this")++ await asyncio.wait_for(send(0), timeout=1.0)+ await asyncio.wait_for(first_capture_started.wait(), timeout=1.0)+ await asyncio.wait_for(send(1), timeout=1.0)++ self.assertEqual(handler._admit_human_delivery.await_count, 2)+ self.assertEqual(released_admissions, ["base-session", "base-session"])+ assert not second_capture_started.is_set()+ release_first_capture.set()+ await handler.drain_memory_capture_tasks()+ assert second_capture_started.is_set()++ async def test_attachment_capture_cancelled_during_admission_does_not_retain_lease(+ self,+ ):+ from modules.im.base import FileAttachment++ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ acquisition_started = asyncio.Event()+ never_acquired = asyncio.Event()++ async def acquire_lifecycle_admission(session_id):+ self.assertEqual(session_id, "base-session")+ acquisition_started.set()+ await never_acquired.wait()+ raise AssertionError("unreachable")++ controller.session_turns = types.SimpleNamespace(+ deliver=AsyncMock(),+ acquire_lifecycle_admission=acquire_lifecycle_admission,+ )+ controller.reserve_memory_attachment_capture = Mock(+ return_value=_capture_reservation()+ )+ controller.capture_user_memory = AsyncMock()+ lease = Mock()+ attachment = FileAttachment(+ name="report.pdf",+ mimetype="application/pdf",+ local_path="/tmp/leased-report.pdf",+ size=10,+ )+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(return_value="review this")+ handler._materialize_file_attachments = AsyncMock(+ return_value=types.SimpleNamespace(+ attachments=(attachment,),+ display_errors=(),+ lease=lease,+ )+ )+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ message_id="m-cancelled-memory-admission",+ platform="slack",+ platform_specific={"is_dm": True},+ files=[FileAttachment("report.pdf", "application/pdf", url="private")],+ is_ordinary_attachment=True,+ )++ task = asyncio.create_task(+ handler.handle_user_message(context, "remember this")+ )+ await asyncio.wait_for(acquisition_started.wait(), timeout=1.0)+ task.cancel()+ with self.assertRaises(asyncio.CancelledError):+ await task++ lease.retain.assert_not_called()+ lease.release.assert_called_once_with()+ controller.capture_user_memory.assert_not_called()++ async def test_shutdown_quiesce_closes_capture_registration_before_sweep(+ self,+ ):+ """Scenario: MEMORY-IM-ATTACH-004."""++ from modules.im.base import FileAttachment++ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ acquisition_started = asyncio.Event()+ release_acquisition = asyncio.Event()+ lifecycle_admission = Mock()++ async def acquire_lifecycle_admission(session_id):+ self.assertEqual(session_id, "base-session")+ acquisition_started.set()+ await release_acquisition.wait()+ return lifecycle_admission++ controller.session_turns = types.SimpleNamespace(+ deliver=AsyncMock(),+ acquire_lifecycle_admission=acquire_lifecycle_admission,+ )+ controller.reserve_memory_attachment_capture = Mock(+ return_value=_capture_reservation()+ )+ controller.capture_user_memory = AsyncMock()+ lease = Mock()+ attachment = FileAttachment(+ name="report.pdf",+ mimetype="application/pdf",+ local_path="/tmp/leased-report.pdf",+ size=10,+ )+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(return_value="review this")+ handler._materialize_file_attachments = AsyncMock(+ return_value=types.SimpleNamespace(+ attachments=(attachment,),+ display_errors=(),+ lease=lease,+ )+ )++ async def admit(**kwargs):+ admitted_lease = kwargs["attachment_lease"]+ admitted_lease.adopt()+ admitted_lease.release()+ return True++ handler._admit_human_delivery = AsyncMock(side_effect=admit)+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ message_id="m-shutdown-registration",+ platform="slack",+ platform_specific={"is_dm": True},+ files=[FileAttachment("report.pdf", "application/pdf", url="private")],+ is_ordinary_attachment=True,+ )++ turn = asyncio.create_task(+ handler.handle_user_message(context, "remember this")+ )+ await asyncio.wait_for(acquisition_started.wait(), timeout=1.0)+ handler.quiesce_memory_capture_tasks()+ await handler.cancel_memory_capture_tasks()+ release_acquisition.set()+ await asyncio.wait_for(turn, timeout=1.0)++ controller.reserve_memory_attachment_capture.assert_not_called()+ controller.capture_user_memory.assert_not_called()+ lease.retain.assert_not_called()+ lifecycle_admission.release.assert_called_once_with()+ assert handler._memory_capture_tasks == set()++ async def test_cancelled_attachment_registration_removes_real_lease_directory(+ self,+ ):+ """Scenario: MEMORY-IM-ATTACH-004."""++ from core.handlers.inbound_attachments import InboundAttachmentMaterializer+ from modules.im.base import FileAttachment, FileDownloadResult++ class Downloader:+ async def download_file_to_path(+ self,+ _file_info,+ _target_path,+ *,+ target_fd=None,+ **_kwargs,+ ):+ assert target_fd is not None+ os.write(target_fd, b"%PDF-1.7\n")+ return FileDownloadResult(True)++ root = Path(self.enterContext(tempfile.TemporaryDirectory())).resolve()+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ message_id="m-real-cancelled-registration",+ platform="slack",+ platform_specific={"is_dm": True},+ files=[+ FileAttachment(+ "report.pdf",+ "application/pdf",+ url="private",+ size=9,+ )+ ],+ is_ordinary_attachment=True,+ )+ batch = await InboundAttachmentMaterializer(+ effective_home=root,+ attachments_root=root / "attachments",+ ).materialize(context, Downloader())+ leased_path = Path(batch.attachments[0].local_path)+ assert leased_path.exists()++ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ acquisition_started = asyncio.Event()+ never_acquired = asyncio.Event()++ async def acquire_lifecycle_admission(_session_id):+ acquisition_started.set()+ await never_acquired.wait()+ raise AssertionError("unreachable")++ controller.session_turns = types.SimpleNamespace(+ deliver=AsyncMock(),+ acquire_lifecycle_admission=acquire_lifecycle_admission,+ )+ controller.reserve_memory_attachment_capture = Mock(+ side_effect=AssertionError("registration must not run after cancellation")+ )+ controller.capture_user_memory = AsyncMock()+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(return_value="review this")+ handler._materialize_file_attachments = AsyncMock(return_value=batch)++ task = asyncio.create_task(+ handler.handle_user_message(context, "remember this")+ )+ await asyncio.wait_for(acquisition_started.wait(), timeout=1.0)+ task.cancel()+ with self.assertRaises(asyncio.CancelledError):+ await task++ assert not leased_path.exists()+ assert list((root / "attachments" / "im").iterdir()) == []+ controller.capture_user_memory.assert_not_called()++ async def test_shutdown_cancels_inflight_capture_and_removes_real_lease_directory(+ self,+ ):+ """Scenario: MEMORY-IM-ATTACH-004."""++ from core.handlers.inbound_attachments import InboundAttachmentMaterializer+ from modules.im.base import FileAttachment, FileDownloadResult++ class Downloader:+ async def download_file_to_path(+ self,+ _file_info,+ _target_path,+ *,+ target_fd=None,+ **_kwargs,+ ):+ assert target_fd is not None+ os.write(target_fd, b"%PDF-1.7\n")+ return FileDownloadResult(True)++ root = Path(self.enterContext(tempfile.TemporaryDirectory())).resolve()+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ message_id="m-shutdown-capture",+ platform="slack",+ platform_specific={"is_dm": True},+ files=[+ FileAttachment(+ "report.pdf",+ "application/pdf",+ url="private",+ size=9,+ )+ ],+ is_ordinary_attachment=True,+ )+ batch = await InboundAttachmentMaterializer(+ effective_home=root,+ attachments_root=root / "attachments",+ ).materialize(context, Downloader())+ leased_path = Path(batch.attachments[0].local_path)+ retained_lease = batch.lease.retain()+ batch.lease.release()+ assert leased_path.exists()++ handler = MessageHandler(+ _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ )+ capture_started = asyncio.Event()++ async def capture() -> None:+ capture_started.set()+ await asyncio.Event().wait()++ capture_task = asyncio.create_task(capture())+ handler._track_memory_capture_task(+ capture_task,+ attachment_lease=retained_lease,+ )+ await capture_started.wait()++ await handler.cancel_memory_capture_tasks()++ assert capture_task.cancelled()+ assert handler._memory_capture_tasks == set()+ assert not leased_path.exists()+ assert list((root / "attachments" / "im").iterdir()) == []+async def test_scope_model_and_reasoning_override_vibe_agent_defaults(self):controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)controller.settings_manager.routing = type(diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex 7f99067e3..8e63b4ad9 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -247,6 +247,42 @@ async def test_session_lifecycle_waits_for_admitted_turn_capture(managers) -> Noassert lifecycle_entered.is_set()+async def test_session_lifecycle_advances_local_epoch_after_operation(managers) -> None:+ manager, _other, _engine, _engine_b, _starts = managers+ pre_epoch = manager.session_lifecycle_epoch("ses_fsm")++ async def lifecycle_operation() -> str:+ assert manager.session_lifecycle_epoch("ses_fsm") == pre_epoch+ return "reset"++ assert await manager.run_session_lifecycle(+ "ses_fsm",+ lifecycle_operation,+ ) == "reset"+ assert manager.session_lifecycle_epoch_matches("ses_fsm", pre_epoch + 1)+++async def test_failed_session_lifecycle_preserves_sampled_epoch(managers) -> None:+ """MEMORY-IM-ATTACH-001: failed reset preserves an in-flight turn epoch."""++ manager, _other, _engine, _engine_b, _starts = managers+ sampled_epoch = manager.session_lifecycle_epoch("ses_fsm")++ async def lifecycle_operation() -> str:+ raise RuntimeError("reset failed")++ with pytest.raises(RuntimeError, match="reset failed"):+ await manager.run_session_lifecycle("ses_fsm", lifecycle_operation)++ admission = await manager.acquire_lifecycle_admission("ses_fsm")+ try:+ assert manager.session_lifecycle_epoch_matches("ses_fsm", sampled_epoch)+ finally:+ admission.release()++async def _activate(manager: SessionTurnManager,*,diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.pyindex 1de80c4db..62b71b2e0 100644--- a/tests/test_slack_dm_mentions.py+++ b/tests/test_slack_dm_mentions.py@@ -761,6 +761,70 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(received, {"text": "<@U_BOT> hello"})+ async def test_dm_file_share_sets_the_separate_attachment_classification(self):+ """Scenario: MEMORY-IM-ATTACH-001."""++ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))+ received = {}++ async def _on_message(context, text):+ received.update(+ text=text,+ ordinary_text=context.is_ordinary_text,+ ordinary_attachment=context.is_ordinary_attachment,+ files=[file.name for file in context.files or ()],+ )++ slack.register_callbacks(on_message=_on_message)+ payload = {+ "event_id": "evt-dm-file-share",+ "team_id": "T1",+ "authorizations": [{"user_id": "U_BOT"}],+ "event": {+ "type": "message",+ "subtype": "file_share",+ "channel": "D123",+ "channel_type": "im",+ "user": "U123",+ "text": "remember this receipt",+ "ts": "1710000000.000201",+ "files": [+ {+ "id": "F123",+ "name": "receipt.pdf",+ "mimetype": "application/pdf",+ "size": 128,+ "url_private_download": "https://files.slack.test/receipt.pdf",+ }+ ],+ "blocks": [+ {+ "type": "rich_text",+ "elements": [+ {+ "type": "rich_text_section",+ "elements": [+ {"type": "text", "text": "remember this receipt"}+ ],+ }+ ],+ }+ ],+ },+ }++ await slack._handle_event(payload)++ self.assertEqual(+ received,+ {+ "text": "remember this receipt",+ "ordinary_text": False,+ "ordinary_attachment": True,+ "files": ["receipt.pdf"],+ },+ )+async def test_bound_user_message_from_mismatched_dm_channel_is_ignored(self):slack = SlackBot(SlackConfig(bot_token="xoxb-test"))received = {"called": False}diff --git a/tests/test_ui_memory_routes.py b/tests/test_ui_memory_routes.pyindex 4efdaf3fa..850a4f01f 100644--- a/tests/test_ui_memory_routes.py+++ b/tests/test_ui_memory_routes.py@@ -63,6 +63,33 @@ def test_memory_rebuild_result_preserves_closed_preflight_diagnostic() -> None:}+ ("enabled_platforms", "expected"),+ [+ (["slack"], True),+ (["discord"], False),+ (["discord", "slack"], True),+ ([], False),+ ],+)+def test_attachment_capture_availability_follows_enabled_platform_allowlist(+ enabled_platforms: list[str],+ expected: bool,+) -> None:+ """MEMORY-IM-ATTACH-003: UI availability follows enabled capture platforms."""++ config = V2Config(+ mode="self_host",+ version="v2",+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ )+ config.platforms.enabled = enabled_platforms++ assert ui_memory_routes._memory_im_attachment_capture_available(config) is expected++def test_memory_settings_patch_accepts_optional_complete_rerank_endpoint() -> None:current = V2Config(mode="self_host",@@ -209,7 +236,7 @@ def test_enabled_memory_can_clear_optional_endpoint_and_reconcile(assert response.status_code == 200assert response.get_json()["enabled"] is True- assert response.get_json()["im_attachment_capture_available"] is False+ assert response.get_json()["im_attachment_capture_available"] is Trueassert endpoint not in response.get_json()["processing"]saved = V2Config.load().memoryassert saved.enabled is True@@ -598,7 +625,7 @@ def test_memory_settings_are_direct_loopback_only_and_write_only(monkeypatch, tmassert response.get_json()["processing"]["llm"]["has_api_key"] is Falseassert response.get_json()["rebuild_required"] is Falseassert response.get_json()["repair_available"] is False- assert response.get_json()["im_attachment_capture_available"] is False+ assert response.get_json()["im_attachment_capture_available"] is Trueassert "recovery_intent" not in response.get_json()assert "embedding_change_pending" not in response.get_json()assert "diagnostics" not in response.get_json()diff --git a/vibe/ui_memory_routes.py b/vibe/ui_memory_routes.pyindex fdee294be..f67c0a64e 100644--- a/vibe/ui_memory_routes.py+++ b/vibe/ui_memory_routes.py@@ -115,10 +115,12 @@ def _memory_settings_projection(memory: object) -> dict:return payload-def _memory_im_attachment_capture_available() -> bool:- from core.memory.attachments import IM_ATTACHMENT_CAPTURE_AVAILABLE+def _memory_im_attachment_capture_available(config: V2Config) -> bool:+ from core.memory.attachments import IM_ATTACHMENT_CAPTURE_PLATFORMS- return IM_ATTACHMENT_CAPTURE_AVAILABLE+ return bool(+ IM_ATTACHMENT_CAPTURE_PLATFORMS.intersection(config.enabled_platforms())+ )def _memory_repair_available() -> bool:@@ -133,11 +135,12 @@ def _memory_repair_available() -> bool:def _memory_settings_payload() -> dict:# Tag the response, not `memory_config_to_payload` itself: the same helper# feeds the persisted config, which must stay free of result envelopes.- memory = V2Config.load().memory+ config = V2Config.load()+ memory = config.memorypayload = _memory_settings_projection(memory)payload["status"] = "ok"payload["im_attachment_capture_available"] = (- _memory_im_attachment_capture_available()+ _memory_im_attachment_capture_available(config))# Read-only projection while a durable rebuild marker is pending.payload["rebuild_required"] = memory.recovery_intent == "rebuild"@@ -714,13 +717,14 @@ def _memory_repair_request_task(*, user_key: str) -> asyncio.Task[tuple[dict, in)-async def _settings_ok_payload(memory, runtime_payload: dict | None = None) -> dict:+async def _settings_ok_payload(config: V2Config, runtime_payload: dict | None = None) -> dict:from core.memory.blocking import run_blocking+ memory = config.memorypayload = _memory_settings_projection(memory)payload["status"] = "ok"payload["im_attachment_capture_available"] = (- _memory_im_attachment_capture_available()+ _memory_im_attachment_capture_available(config))payload["rebuild_required"] = getattr(memory, "recovery_intent", None) == "rebuild"payload["factory_reset_required"] = getattr(memory, "recovery_intent", None) == "factory_reset"@@ -828,7 +832,7 @@ async def _apply_memory_settings_patch()# Do not reconcile here: the durable reset marker remains the# authority and Retry must perform the fenced deletion/activation.- return _memory_response(await _settings_ok_payload(saved.memory))+ return _memory_response(await _settings_ok_payload(saved))# An exact credential-only update under an existing marker updates the# candidate without touching the fenced runtime. Every broader patch@@ -850,7 +854,7 @@ async def _apply_memory_settings_patch(return _memory_response({"status": "failed", "error": "memory_invalid_input"}, status_code=400)except Exception:return _memory_response({"status": "failed", "error": "memory_store_unavailable"}, status_code=503)- return _memory_response(await _settings_ok_payload(saved.memory))+ return _memory_response(await _settings_ok_payload(saved))recovery_intent = "rebuild" if pending_marker or identity_changed else None@@ -912,7 +916,7 @@ async def _apply_memory_settings_patch()runtime_payload = body if isinstance(body, dict) else {}latest = await asyncio.to_thread(V2Config.load)- payload = await _settings_ok_payload(latest.memory, runtime_payload)+ payload = await _settings_ok_payload(latest, runtime_payload)if status_code != 200 or runtime_payload.get("ok") is not True:error = _memory_closed_error(runtime_payload,@@ -937,7 +941,7 @@ async def _apply_memory_settings_patch()# Pending-marker reconcile that only needs rebuild is not a rollback.if closed_error == "memory_embedding_rebuild_required":- payload = await _settings_ok_payload(saved.memory, runtime_payload)+ payload = await _settings_ok_payload(saved, runtime_payload)payload["rebuild_required"] = Truereturn _memory_response(payload)# Ordinary non-identity saves must not outrun the controller's closed@@ -973,7 +977,7 @@ async def _apply_memory_settings_patch(if response.status_code >= 500:return responselatest = await asyncio.to_thread(V2Config.load)- return _memory_response(await _settings_ok_payload(latest.memory, runtime_payload))+ return _memory_response(await _settings_ok_payload(latest, runtime_payload))def register_memory_routes(app) -> None: