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
fix(memory): decouple optional lifecycle work (#1601)
rkrkrkk209d1498c9e0
diff --git a/core/controller.py b/core/controller.pyindex a7c815555..50fd5cbd3 100644--- a/core/controller.py+++ b/core/controller.py@@ -265,6 +265,8 @@ class Controller:self._removed_im_clients: Dict[str, BaseIMClient] = {}self._memory_scopes_by_session: Dict[str, tuple[str, str]] = {}self._memory_cli_facts_by_session: Dict[str, InboundTurnFacts] = {}+ self._archive_memory_flush_tasks: set[asyncio.Task[None]] = set()+ self._archive_memory_flush_registration_open = True# Session tracking (must be initialized before handlers)self.claude_sessions: Dict[str, Any] = {}@@ -2131,6 +2133,16 @@ class Controller:return scopereturn None+ def _forget_memory_cli_session(self, session_id: str) -> None:+ """Drop process-local Memory authorization after a terminal archive."""++ scopes = getattr(self, "_memory_scopes_by_session", None)+ if isinstance(scopes, dict):+ scopes.pop(session_id, None)+ facts = getattr(self, "_memory_cli_facts_by_session", None)+ if isinstance(facts, dict):+ facts.pop(session_id, None)+def memory_principal_for_cli_session(self, session_id: str) -> Optional[str]:"""Return the principal associated with an admitted Agent session."""@@ -2309,6 +2321,10 @@ class Controller:def _schedule_best_effort_archive_memory_flush(self, raw_session_id: str) -> None:"""Flush Memory for an archived session without owning the archive result."""+ if not getattr(self, "_archive_memory_flush_registration_open", True):+ self._forget_memory_cli_session(raw_session_id)+ return+async def _flush() -> None:try:await self.final_flush_memory_cli_session(raw_session_id)@@ -2318,6 +2334,8 @@ class Controller:raw_session_id,exc_info=True,)+ finally:+ self._forget_memory_cli_session(raw_session_id)def _consume(task: asyncio.Task[None]) -> None:tasks = getattr(self, "_archive_memory_flush_tasks", None)@@ -2338,32 +2356,40 @@ class Controller:loop = asyncio.get_running_loop()except RuntimeError:loop = getattr(self, "_loop", None)- if loop is None or loop.is_closed():+ if loop is None or loop.is_closed() or not loop.is_running():logger.debug(- "archive: Memory flush dropped; no event loop for %s",+ "archive: Memory flush dropped; no running event loop for %s",raw_session_id,)+ self._forget_memory_cli_session(raw_session_id)return- future = asyncio.run_coroutine_threadsafe(_flush(), loop)-- def _consume_future(completed: concurrent.futures.Future[None]) -> None:- if completed.cancelled():- return- error = completed.exception()- if error is not None:- logger.debug(- "archive: best-effort Memory flush failed for %s",- raw_session_id,- exc_info=error,- )-- future.add_done_callback(_consume_future)+ try:+ loop.call_soon_threadsafe(+ self._schedule_best_effort_archive_memory_flush,+ raw_session_id,+ )+ except RuntimeError:+ logger.debug(+ "archive: Memory flush dropped; event loop stopped for %s",+ raw_session_id,+ )+ self._forget_memory_cli_session(raw_session_id)return- task = loop.create_task(- _flush(),- name=f"archive-memory-flush:{raw_session_id}",- )+ scheduled = _flush()+ try:+ task = loop.create_task(+ scheduled,+ name=f"archive-memory-flush:{raw_session_id}",+ )+ except RuntimeError:+ scheduled.close()+ logger.debug(+ "archive: Memory flush dropped; event loop stopped for %s",+ raw_session_id,+ )+ self._forget_memory_cli_session(raw_session_id)+ returntasks = getattr(self, "_archive_memory_flush_tasks", None)if tasks is None:self._archive_memory_flush_tasks = tasks = set()@@ -2409,6 +2435,7 @@ class Controller:existing = await asyncio.to_thread(read_session)if existing.get("status") == "archived":+ self._forget_memory_cli_session(raw_session_id)return existingdef archive_session() -> dict[str, Any]:@@ -2438,6 +2465,7 @@ class Controller:"archive: Memory flush dropped; event loop closed for %s",raw_session_id,)+ self._forget_memory_cli_session(raw_session_id)return sessionreturn await run_blocking(archive_and_schedule)@@ -3375,6 +3403,21 @@ class Controller:if callable(cancel):await cancel()+ async def _cancel_archive_memory_flush_tasks() -> None:+ tasks = getattr(self, "_archive_memory_flush_tasks", None)+ if not isinstance(tasks, set):+ return+ pending = tuple(task for task in tasks if not task.done())+ for task in pending:+ task.cancel()+ if pending:+ await asyncio.gather(*pending, return_exceptions=True)+ tasks.clear()++ # Close registration before the loop-owned sweep so a completed archive+ # cannot add another optional flush behind Memory runtime shutdown.+ self._archive_memory_flush_registration_open = False+# 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(@@ -3382,6 +3425,11 @@ class Controller:"Memory capture tasks",timeout=None,)+ _stop_loop_coroutine(+ _cancel_archive_memory_flush_tasks(),+ "Archive Memory flush 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/inbound_attachments.py b/core/handlers/inbound_attachments.pyindex 3e2804fa3..f1697ecb2 100644--- a/core/handlers/inbound_attachments.py+++ b/core/handlers/inbound_attachments.py@@ -9,96 +9,24 @@ import osimport reimport secretsimport stat-import threadingfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Anyfrom config import pathsfrom core.audio_asr import AUDIO_SIGNATURE_SAMPLE_BYTES, detect_audio_mime_from_sample+from core.inbound_attachment_lease import (+ InboundAttachmentLease,+ LeasedAttachmentRecord,+ leased_attachment_records,+ open_leased_attachment_record,+)from modules.im.base import FileAttachment, FileDownloadResult, MessageContextfrom vibe.i18n import t as i18n_t_MAX_FILENAME_BYTES = 200_SAFE_FILENAME = re.compile(r"[^\w.\-]", re.UNICODE)-_LEASE_ID = re.compile(r"[0-9a-f]{32}")---@dataclass(frozen=True, slots=True)-class _LeasedAttachmentRecord:- name: str- mimetype: str- declared_size: int | None- size: int- path: Path- device: int- inode: int- sha256: str---class _LeaseState:- def __init__(- self,- root: Path,- directory: Path,- root_fd: int,- directory_fd: int,- ) -> None:- self.root = root- self.directory = directory- self.root_fd = root_fd- self.directory_fd = directory_fd- self.records: tuple[_LeasedAttachmentRecord, ...] = ()- self.references = 1- self.adopted = False- self.lock = threading.Lock()---class InboundAttachmentLease:- """Opaque reference to one private set of materialized native files."""-- __slots__ = ("__state", "__released")-- def __init__(self, state: _LeaseState) -> None:- self.__state = state- self.__released = False-- def retain(self) -> "InboundAttachmentLease":- """Return an independent reference to the same immutable file set."""-- state = self.__state- with state.lock:- if self.__released or state.references <= 0:- raise RuntimeError("attachment lease is no longer active")- state.references += 1- return InboundAttachmentLease(state)-- def adopt(self) -> None:- """Transfer final-file ownership to the ordinary Agent attachment path."""-- state = self.__state- with state.lock:- if self.__released or state.references <= 0:- raise RuntimeError("attachment lease is no longer active")- state.adopted = True-- def release(self) -> None:- """Release this reference and remove unadopted files after the last user."""-- state = self.__state- with state.lock:- if self.__released:- return- self.__released = True- state.references -= 1- last_reference = state.references == 0- remove = last_reference and (not state.adopted or not state.records)- if remove:- _remove_lease_directory(state)- elif last_reference:- os.close(state.directory_fd)- os.close(state.root_fd)@dataclass(frozen=True, slots=True)@@ -176,8 +104,12 @@ class InboundAttachmentMaterializer:os.close(lease_fd)os.close(root_fd)raise- state = _LeaseState(self._root, lease_dir, root_fd, lease_fd)- lease = InboundAttachmentLease(state)+ lease = InboundAttachmentLease.create(+ root=self._root,+ directory=lease_dir,+ root_fd=root_fd,+ directory_fd=lease_fd,+ )candidates = tuple(attachment@@ -204,13 +136,13 @@ class InboundAttachmentMaterializer:outcomes = await asyncio.gather(*(acquire(index, attachment) for index, attachment in enumerate(candidates)))- _verify_lease_directory_entry(state)+ lease.verify_directory()except BaseException:lease.release()raiseattachments: list[FileAttachment] = []- records: list[_LeasedAttachmentRecord] = []+ records: list[LeasedAttachmentRecord] = []errors: list[str] = []display_errors: list[str] = []for outcome in outcomes:@@ -222,7 +154,7 @@ class InboundAttachmentMaterializer:attachments.append(attachment)if record is not None:records.append(record)- state.records = tuple(records)+ lease.publish_records(tuple(records))return MaterializedAttachmentBatch(tuple(attachments),tuple(errors),@@ -242,7 +174,7 @@ class InboundAttachmentMaterializer:max_bytes: int | None,timeout_seconds: int,language: str,- ) -> tuple[FileAttachment, _LeasedAttachmentRecord | None] | _MaterializationFailure:+ ) -> tuple[FileAttachment, LeasedAttachmentRecord | None] | _MaterializationFailure:if attachment.local_path and Path(attachment.local_path).is_file():size = attachment.sizeif size is None:@@ -339,7 +271,7 @@ class InboundAttachmentMaterializer:local_path=str(final_path),size=size,)- outcome = snapshot, _LeasedAttachmentRecord(+ outcome = snapshot, LeasedAttachmentRecord(name=name,mimetype=mimetype,declared_size=declared_size,@@ -367,59 +299,6 @@ class InboundAttachmentMaterializer:pass-def leased_attachment_records(- lease: InboundAttachmentLease,-) -> tuple[Path, int, tuple[_LeasedAttachmentRecord, ...]]:- """Snapshot an active lease and duplicate its anchored directory descriptor."""-- if type(lease) is not InboundAttachmentLease:- raise ValueError("invalid attachment lease")- state = lease._InboundAttachmentLease__state- released = lease._InboundAttachmentLease__released- with state.lock:- if released or state.references <= 0 or _LEASE_ID.fullmatch(state.directory.name) is None:- raise ValueError("attachment lease is no longer active")- records = state.records- try:- directory_fd = os.dup(state.directory_fd)- except OSError as error:- raise ValueError("attachment lease is no longer active") from error- return state.root, directory_fd, records---def open_leased_attachment_record(- directory_fd: int,- record: _LeasedAttachmentRecord,-) -> tuple[int, os.stat_result]:- """Open the exact materialized inode relative to its retained lease directory."""-- if type(record) is not _LeasedAttachmentRecord:- raise ValueError("invalid leased attachment record")- filename = record.path.name- if not filename or Path(filename).name != filename:- raise ValueError("invalid leased attachment record")- try:- descriptor = os.open(filename, _file_read_flags(), dir_fd=directory_fd)- except OSError as error:- raise ValueError("leased attachment is unavailable") from error- try:- info = os.fstat(descriptor)- getuid = getattr(os, "getuid", None)- if (- not stat.S_ISREG(info.st_mode)- or stat.S_IMODE(info.st_mode) != 0o600- or (callable(getuid) and info.st_uid != getuid())- or info.st_dev != record.device- or info.st_ino != record.inode- or info.st_size != record.size- ):- raise ValueError("leased attachment no longer matches its materialized inode")- return descriptor, info- except BaseException:- os.close(descriptor)- raise--def _download_info(context: MessageContext, attachment: FileAttachment) -> dict[str, Any]:info: dict[str, Any] = {"url": attachment.url,@@ -509,18 +388,6 @@ def _file_create_flags() -> int:)-def _file_read_flags() -> int:- no_follow = getattr(os, "O_NOFOLLOW", None)- if no_follow is None:- raise RuntimeError("attachment leases require no-follow filesystem support")- return (- os.O_RDONLY- | int(no_follow)- | int(getattr(os, "O_NONBLOCK", 0))- | int(getattr(os, "O_CLOEXEC", 0))- )--def _descriptor_path(descriptor: int) -> str:root = "/dev/fd" if Path("/dev/fd").is_dir() else "/proc/self/fd"return f"{root}/{descriptor}"@@ -554,42 +421,6 @@ def _unlink_at_quietly(parent_fd: int, name: str) -> None:pass-def _verify_lease_directory_entry(state: _LeaseState) -> None:- expected = os.fstat(state.directory_fd)- observed = os.stat(- state.directory.name,- dir_fd=state.root_fd,- follow_symlinks=False,- )- if (- not stat.S_ISDIR(observed.st_mode)- or observed.st_dev != expected.st_dev- or observed.st_ino != expected.st_ino- ):- raise OSError("attachment lease directory changed during materialization")---def _remove_lease_directory(state: _LeaseState) -> None:- try:- try:- names = os.listdir(state.directory_fd)- except OSError:- names = []- for name in names:- try:- os.unlink(name, dir_fd=state.directory_fd)- except OSError:- pass- try:- _verify_lease_directory_entry(state)- os.rmdir(state.directory.name, dir_fd=state.root_fd)- except OSError:- pass- finally:- os.close(state.directory_fd)- os.close(state.root_fd)--def _owned_parts_below(anchor: Path,home: Path,diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 331aa2ebf..32be45cec 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -24,10 +24,6 @@ from core.native_dispatch_phase import (DISPATCH_PHASE_PREWRITE,set_dispatch_phase,)--# Keep this string local: importing ``core.session_turns`` here cycles through-# Memory admission into ``core.handlers``.-TURN_LIFECYCLE_EPOCH_KEY = "_turn_lifecycle_epoch"from modules.agents.base import AgentRequestfrom modules.agents.catalog import display_name_for_backend, is_agent_backendfrom modules.im import MessageContext@@ -154,10 +150,10 @@ class MessageHandler(BaseHandler):async def _run_memory_capture(self,session_id: str,- expected_epoch: int,+ expected_snapshot: object,capture: Awaitable[None],) -> None:- """Acquire the lifecycle lock and attribute only if the epoch still matches."""+ """Acquire the lifecycle lock and attribute only in the same generation."""pending: Awaitable[None] | None = capturetry:@@ -167,15 +163,15 @@ class MessageHandler(BaseHandler):try:if not self._memory_capture_registration_open:return- if not self._memory_session_lifecycle_epoch_matches(+ if not self._memory_session_lifecycle_snapshot_matches(session_id,- expected_epoch,+ expected_snapshot,):logger.info("Memory capture abandoned after session lifecycle ""transition session=%s epoch=%s",session_id,- expected_epoch,+ getattr(expected_snapshot, "epoch", None),)returnawait capture@@ -194,7 +190,7 @@ class MessageHandler(BaseHandler):self,*,session_id: str,- expected_epoch: int,+ expected_snapshot: object,capture: Awaitable[None],attachment_lease: Any = None,attachment_reservation: Any = None,@@ -204,7 +200,7 @@ class MessageHandler(BaseHandler):if not self._memory_capture_registration_open:return Nonecapture_task = asyncio.create_task(- self._run_memory_capture(session_id, expected_epoch, capture),+ self._run_memory_capture(session_id, expected_snapshot, capture),name="memory-capture",)self._track_memory_capture_task(@@ -215,50 +211,83 @@ class MessageHandler(BaseHandler):)return capture_task+ @staticmethod+ def _close_memory_capture(capture: object) -> None:+ close = getattr(capture, "close", None)+ if not callable(close):+ return+ try:+ close()+ except Exception:+ logger.debug("Memory capture coroutine close failed", exc_info=True)+def _schedule_text_only_memory_capture(self,context: MessageContext,text: str,session_id: str,*,- expected_epoch: int,+ expected_snapshot: object,) -> None:capture_memory = getattr(self.controller, "capture_user_memory", None)if not callable(capture_memory) or not text.strip():returnif not self._memory_capture_registration_open:return- capture = capture_memory(context, text, session_id)- if (- self._schedule_memory_capture_task(- session_id=session_id,- expected_epoch=expected_epoch,- capture=capture,+ capture: Awaitable[None] | None = None+ try:+ capture = capture_memory(context, text, session_id)+ if (+ self._schedule_memory_capture_task(+ session_id=session_id,+ expected_snapshot=expected_snapshot,+ capture=capture,+ )+ is None+ ):+ self._close_memory_capture(capture)+ except Exception:+ self._close_memory_capture(capture)+ logger.warning(+ "Memory text capture could not be scheduled",+ exc_info=True,)- is None- ):- close = getattr(capture, "close", None)- if callable(close):- close()- def _memory_session_lifecycle_epoch(self, session_id: str) -> int:+ def _memory_session_lifecycle_snapshot(self, session_id: str) -> object:manager = getattr(self.controller, "session_turns", None)+ snapshot = getattr(manager, "snapshot_session_lifecycle", None)+ if callable(snapshot):+ try:+ return snapshot(session_id)+ except Exception:+ logger.warning(+ "Memory lifecycle snapshot failed session=%s",+ session_id,+ exc_info=True,+ )+ return Noneread_epoch = getattr(manager, "session_lifecycle_epoch", None)if not callable(read_epoch):return 0epoch = read_epoch(session_id)return epoch if isinstance(epoch, int) and not isinstance(epoch, bool) else 0- def _memory_session_lifecycle_epoch_matches(+ def _memory_session_lifecycle_snapshot_matches(self,session_id: str,- expected_epoch: int,+ expected_snapshot: object,) -> bool:manager = getattr(self.controller, "session_turns", None)- matches = getattr(manager, "session_lifecycle_epoch_matches", None)+ matches = getattr(manager, "session_lifecycle_snapshot_matches", None)if callable(matches):- return bool(matches(session_id, expected_epoch))- return self._memory_session_lifecycle_epoch(session_id) == expected_epoch+ return bool(matches(session_id, expected_snapshot))+ legacy_matches = getattr(manager, "session_lifecycle_epoch_matches", None)+ if callable(legacy_matches):+ return bool(legacy_matches(session_id, expected_snapshot))+ return (+ self._memory_session_lifecycle_snapshot(session_id)+ == expected_snapshot+ )async def drain_memory_capture_tasks(self) -> None:"""Settle captures accepted before controller shutdown closes Memory."""@@ -283,17 +312,40 @@ class MessageHandler(BaseHandler):self._memory_capture_registration_open = False- async def handle_user_message(self, context: MessageContext, message: str):+ async def handle_user_message(+ self,+ context: MessageContext,+ message: str,+ *,+ lifecycle_snapshot: object | None = None,+ ):"""Process regular human-originated messages and route to configured agent."""- await self._handle_turn(context, message, source=self.TURN_SOURCE_HUMAN)+ await self._handle_turn(+ context,+ message,+ source=self.TURN_SOURCE_HUMAN,+ lifecycle_snapshot=lifecycle_snapshot,+ )- async def handle_scheduled_message(self, context: MessageContext, message: str, parsed_session_key=None):+ async def handle_scheduled_message(+ self,+ context: MessageContext,+ message: str,+ parsed_session_key=None,+ *,+ lifecycle_snapshot: object | None = None,+ ):"""Process a scheduler-originated turn through the shared turn pipeline."""if parsed_session_key is not None:payload = dict(context.platform_specific or {})payload["parsed_session_key"] = parsed_session_keycontext.platform_specific = payload- return await self._handle_turn(context, message, source=self.TURN_SOURCE_SCHEDULED)+ return await self._handle_turn(+ context,+ message,+ source=self.TURN_SOURCE_SCHEDULED,+ lifecycle_snapshot=lifecycle_snapshot,+ )async def _prepare_turn_context(self, context: MessageContext, source: str) -> MessageContext:payload = dict(context.platform_specific or {})@@ -350,7 +402,14 @@ class MessageHandler(BaseHandler):)return False- async def _handle_turn(self, context: MessageContext, message: str, *, source: str) -> Optional[str]:+ async def _handle_turn(+ self,+ context: MessageContext,+ message: str,+ *,+ source: str,+ lifecycle_snapshot: object | None = None,+ ) -> Optional[str]:"""Shared turn-processing pipeline used by both human and scheduled turns."""processing_indicator = Nonerequest: AgentRequest | None = None@@ -458,14 +517,15 @@ class MessageHandler(BaseHandler):base_session_id, working_path, composite_key = self.session_handler.get_session_info(context, source=source)memory_session_id = base_session_id+ memory_session_snapshot: object | None = None+ if is_human:+ memory_session_snapshot = (+ lifecycle_snapshot+ if lifecycle_snapshot is not None+ else self._memory_session_lifecycle_snapshot(memory_session_id)+ )+ lifecycle_snapshot = Nonepayload = dict(context.platform_specific or {})- snapshotted_epoch = payload.pop(TURN_LIFECYCLE_EPOCH_KEY, None)- memory_session_pre_epoch = (- snapshotted_epoch- if isinstance(snapshotted_epoch, int)- and not isinstance(snapshotted_epoch, bool)- else self._memory_session_lifecycle_epoch(memory_session_id)- )payload["turn_source"] = sourcepayload["turn_base_session_id"] = base_session_idpayload["scheduled_anchor_required"] = self.session_handler.should_allocate_scheduled_anchor(@@ -481,8 +541,9 @@ class MessageHandler(BaseHandler):context,control_message,memory_session_id,- expected_epoch=memory_session_pre_epoch,+ expected_snapshot=memory_session_snapshot,)+ memory_session_snapshot = 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:@@ -876,7 +937,7 @@ class MessageHandler(BaseHandler):context,control_message,memory_session_id,- expected_epoch=memory_session_pre_epoch,+ expected_snapshot=memory_session_snapshot,)except Exception:logger.warning(@@ -915,9 +976,9 @@ class MessageHandler(BaseHandler):if not self._memory_capture_registration_open:raise _MemoryCaptureRegistrationClosedstale_attachment_capture = (- not self._memory_session_lifecycle_epoch_matches(+ not self._memory_session_lifecycle_snapshot_matches(memory_session_id,- memory_session_pre_epoch,+ memory_session_snapshot,))reserve_attachment = getattr(@@ -971,15 +1032,13 @@ class MessageHandler(BaseHandler):)capture_task = self._schedule_memory_capture_task(session_id=memory_session_id,- expected_epoch=memory_session_pre_epoch,+ expected_snapshot=memory_session_snapshot,capture=capture,attachment_lease=memory_attachment_lease,attachment_reservation=memory_capture_reservation,)if capture_task is None:- close = getattr(capture, "close", None)- if callable(close):- close()+ self._close_memory_capture(capture)raise _MemoryCaptureRegistrationClosedexcept _MemoryCaptureRegistrationClosed:if memory_attachment_lease is not None:@@ -1011,6 +1070,7 @@ class MessageHandler(BaseHandler):"Memory capture task could not be scheduled",exc_info=True,)+ memory_session_snapshot = Noneif durable_ingress_enabled and not durable_delivery_owned:assert durable_dispatch_text is not Nonediff --git a/core/inbound_attachment_lease.py b/core/inbound_attachment_lease.pynew file mode 100644index 000000000..7e5e9cee5--- /dev/null+++ b/core/inbound_attachment_lease.py@@ -0,0 +1,232 @@+"""Opaque lease primitives shared by inbound delivery and optional consumers."""++from __future__ import annotations++import os+import re+import stat+import threading+from dataclasses import dataclass+from pathlib import Path+++_LEASE_ID = re.compile(r"[0-9a-f]{32}")+++@dataclass(frozen=True, slots=True)+class LeasedAttachmentRecord:+ name: str+ mimetype: str+ declared_size: int | None+ size: int+ path: Path+ device: int+ inode: int+ sha256: str+++class _LeaseState:+ def __init__(+ self,+ root: Path,+ directory: Path,+ root_fd: int,+ directory_fd: int,+ ) -> None:+ self.root = root+ self.directory = directory+ self.root_fd = root_fd+ self.directory_fd = directory_fd+ self.records: tuple[LeasedAttachmentRecord, ...] = ()+ self.published = False+ self.references = 1+ self.adopted = False+ self.lock = threading.Lock()+++class InboundAttachmentLease:+ """Opaque reference to one private set of materialized native files."""++ __slots__ = ("__state", "__released")++ def __init__(self, state: _LeaseState) -> None:+ self.__state = state+ self.__released = False++ @classmethod+ def create(+ cls,+ *,+ root: Path,+ directory: Path,+ root_fd: int,+ directory_fd: int,+ ) -> "InboundAttachmentLease":+ """Create the first reference owned by the shared materializer."""++ return cls(_LeaseState(root, directory, root_fd, directory_fd))++ def retain(self) -> "InboundAttachmentLease":+ """Return an independent reference to the same immutable file set."""++ state = self.__state+ with state.lock:+ if self.__released or state.references <= 0:+ raise RuntimeError("attachment lease is no longer active")+ state.references += 1+ return InboundAttachmentLease(state)++ def adopt(self) -> None:+ """Transfer final-file ownership to the ordinary Agent attachment path."""++ state = self.__state+ with state.lock:+ if self.__released or state.references <= 0:+ raise RuntimeError("attachment lease is no longer active")+ state.adopted = True++ def publish_records(+ self,+ records: tuple[LeasedAttachmentRecord, ...],+ ) -> None:+ """Publish the immutable record set after materialization verifies it."""++ state = self.__state+ with state.lock:+ if self.__released or state.references <= 0 or state.published:+ raise RuntimeError("attachment lease is no longer publishable")+ state.records = records+ state.published = True++ def verify_directory(self) -> None:+ """Verify that the retained directory still names the opened inode."""++ state = self.__state+ with state.lock:+ if self.__released or state.references <= 0:+ raise RuntimeError("attachment lease is no longer active")+ _verify_lease_directory_entry(state)++ def release(self) -> None:+ """Release this reference and remove unadopted files after the last user."""++ state = self.__state+ with state.lock:+ if self.__released:+ return+ self.__released = True+ state.references -= 1+ last_reference = state.references == 0+ remove = last_reference and (not state.adopted or not state.records)+ if remove:+ _remove_lease_directory(state)+ elif last_reference:+ os.close(state.directory_fd)+ os.close(state.root_fd)+++def leased_attachment_records(+ lease: InboundAttachmentLease,+) -> tuple[Path, int, tuple[LeasedAttachmentRecord, ...]]:+ """Snapshot an active lease and duplicate its anchored directory descriptor."""++ if type(lease) is not InboundAttachmentLease:+ raise ValueError("invalid attachment lease")+ state = lease._InboundAttachmentLease__state+ released = lease._InboundAttachmentLease__released+ with state.lock:+ if (+ released+ or state.references <= 0+ or _LEASE_ID.fullmatch(state.directory.name) is None+ ):+ raise ValueError("attachment lease is no longer active")+ records = state.records+ try:+ directory_fd = os.dup(state.directory_fd)+ except OSError as error:+ raise ValueError("attachment lease is no longer active") from error+ return state.root, directory_fd, records+++def open_leased_attachment_record(+ directory_fd: int,+ record: LeasedAttachmentRecord,+) -> tuple[int, os.stat_result]:+ """Open the exact materialized inode relative to its retained directory."""++ if type(record) is not LeasedAttachmentRecord:+ raise ValueError("invalid leased attachment record")+ filename = record.path.name+ if not filename or Path(filename).name != filename:+ raise ValueError("invalid leased attachment record")+ try:+ descriptor = os.open(filename, _file_read_flags(), dir_fd=directory_fd)+ except OSError as error:+ raise ValueError("leased attachment is unavailable") from error+ try:+ info = os.fstat(descriptor)+ getuid = getattr(os, "getuid", None)+ if (+ not stat.S_ISREG(info.st_mode)+ or stat.S_IMODE(info.st_mode) != 0o600+ or (callable(getuid) and info.st_uid != getuid())+ or info.st_dev != record.device+ or info.st_ino != record.inode+ or info.st_size != record.size+ ):+ raise ValueError(+ "leased attachment no longer matches its materialized inode"+ )+ return descriptor, info+ except BaseException:+ os.close(descriptor)+ raise+++def _file_read_flags() -> int:+ no_follow = getattr(os, "O_NOFOLLOW", None)+ if no_follow is None:+ raise RuntimeError("attachment leases require no-follow filesystem support")+ return (+ os.O_RDONLY+ | int(no_follow)+ | int(getattr(os, "O_NONBLOCK", 0))+ | int(getattr(os, "O_CLOEXEC", 0))+ )+++def _verify_lease_directory_entry(state: _LeaseState) -> None:+ expected = os.fstat(state.directory_fd)+ observed = os.stat(+ state.directory.name,+ dir_fd=state.root_fd,+ follow_symlinks=False,+ )+ if (+ not stat.S_ISDIR(observed.st_mode)+ or observed.st_dev != expected.st_dev+ or observed.st_ino != expected.st_ino+ ):+ raise OSError("attachment lease directory changed during materialization")+++def _remove_lease_directory(state: _LeaseState) -> None:+ try:+ try:+ names = os.listdir(state.directory_fd)+ except OSError:+ names = []+ for name in names:+ try:+ os.unlink(name, dir_fd=state.directory_fd)+ except OSError:+ pass+ try:+ _verify_lease_directory_entry(state)+ os.rmdir(state.directory.name, dir_fd=state.root_fd)+ except OSError:+ pass+ finally:+ os.close(state.directory_fd)+ os.close(state.root_fd)diff --git a/core/memory/__init__.py b/core/memory/__init__.pyindex f7cb6f157..f5f0c910c 100644--- a/core/memory/__init__.py+++ b/core/memory/__init__.py@@ -1,30 +1,37 @@-"""Provider-independent core for Avibe's local Memory capability."""--from core.memory.module import MemoryModule-from core.memory.types import (- CaptureAccepted,- CaptureAttachment,- CaptureDuplicate,- CaptureReceipt,- CaptureRequest,- CaptureSkipped,- MemoryErrorCode,- MemoryItem,- MemoryItems,- MemoryKind,- MemoryListItem,- MemoryListPage,- MemoryListResult,- MemoryProfile,- MemoryProfileExplicitInfo,- MemoryProfileTrait,- MemoryResult,- OperationFailed,- ProviderSessionRef,- RecallItems,- RecallMode,- RecallPolicy,- RecallResult,+"""Provider-independent public exports for Avibe's local Memory capability."""++from __future__ import annotations++from importlib import import_module+from typing import TYPE_CHECKING, Any+++_TYPE_EXPORTS = frozenset(+ {+ "CaptureAccepted",+ "CaptureAttachment",+ "CaptureDuplicate",+ "CaptureReceipt",+ "CaptureRequest",+ "CaptureSkipped",+ "MemoryErrorCode",+ "MemoryItem",+ "MemoryItems",+ "MemoryKind",+ "MemoryListItem",+ "MemoryListPage",+ "MemoryListResult",+ "MemoryProfile",+ "MemoryProfileExplicitInfo",+ "MemoryProfileTrait",+ "MemoryResult",+ "OperationFailed",+ "ProviderSessionRef",+ "RecallItems",+ "RecallMode",+ "RecallPolicy",+ "RecallResult",+ })__all__ = [@@ -53,3 +60,48 @@ __all__ = ["RecallPolicy","RecallResult",]++if TYPE_CHECKING:+ from core.memory.module import MemoryModule as MemoryModule+ from core.memory.types import (+ CaptureAccepted as CaptureAccepted,+ CaptureAttachment as CaptureAttachment,+ CaptureDuplicate as CaptureDuplicate,+ CaptureReceipt as CaptureReceipt,+ CaptureRequest as CaptureRequest,+ CaptureSkipped as CaptureSkipped,+ MemoryErrorCode as MemoryErrorCode,+ MemoryItem as MemoryItem,+ MemoryItems as MemoryItems,+ MemoryKind as MemoryKind,+ MemoryListItem as MemoryListItem,+ MemoryListPage as MemoryListPage,+ MemoryListResult as MemoryListResult,+ MemoryProfile as MemoryProfile,+ MemoryProfileExplicitInfo as MemoryProfileExplicitInfo,+ MemoryProfileTrait as MemoryProfileTrait,+ MemoryResult as MemoryResult,+ OperationFailed as OperationFailed,+ ProviderSessionRef as ProviderSessionRef,+ RecallItems as RecallItems,+ RecallMode as RecallMode,+ RecallPolicy as RecallPolicy,+ RecallResult as RecallResult,+ )+++def __getattr__(name: str) -> Any:+ """Load public compatibility exports without penalizing leaf imports."""++ if name == "MemoryModule":+ value = getattr(import_module("core.memory.module"), name)+ elif name in _TYPE_EXPORTS:+ value = getattr(import_module("core.memory.types"), name)+ else:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ globals()[name] = value+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(__all__))diff --git a/core/memory/attachments.py b/core/memory/attachments.pyindex 54309ce9b..5f28a9879 100644--- a/core/memory/attachments.py+++ b/core/memory/attachments.py@@ -14,10 +14,15 @@ import timefrom collections.abc import Collection, Sequencefrom dataclasses import dataclassfrom pathlib import Path, PurePosixPath-from typing import TYPE_CHECKINGfrom urllib.parse import unquote_to_bytes, urlsplitfrom config import paths+from core.inbound_attachment_lease import (+ InboundAttachmentLease,+ LeasedAttachmentRecord,+ leased_attachment_records,+ open_leased_attachment_record,+)from core.memory import modality as memory_modalityfrom core.memory.confined_filesystem import (ConfinedFilesystemError,@@ -33,13 +38,6 @@ from core.memory.types import (MemoryErrorCode,)-if TYPE_CHECKING:- from core.handlers.inbound_attachments import (- InboundAttachmentLease,- _LeasedAttachmentRecord,- )--MAX_PINNED_ATTACHMENTS = 8MAX_PINNED_ATTACHMENT_BYTES = 25 * 1024 * 1024MAX_PINNED_BUNDLE_BYTES = 100 * 1024 * 1024@@ -648,13 +646,9 @@ class AttachmentPinStore:def _pin_source(self,source_lease: InboundAttachmentLease | None,- ) -> tuple[Path, dict[Path, _LeasedAttachmentRecord] | None]:+ ) -> tuple[Path, dict[Path, LeasedAttachmentRecord] | None]:if source_lease is None:return self._source_root, None- from core.handlers.inbound_attachments import (- InboundAttachmentLease,- leased_attachment_records,- )if type(source_lease) is not InboundAttachmentLease:raise AttachmentPinError(@@ -691,7 +685,7 @@ class AttachmentPinStore:source: CaptureAttachment,*,source_root: Path,- allowed_records: dict[Path, _LeasedAttachmentRecord] | None,+ allowed_records: dict[Path, LeasedAttachmentRecord] | None,source_lease: InboundAttachmentLease | None,) -> tuple[int, os.stat_result, str | None]:source_path = _path_from_file_uri(source.uri)@@ -720,11 +714,6 @@ class AttachmentPinStore:raise AttachmentPinError("memory_invalid_input", "attachment extension is inconsistent")if source_lease is not None:- from core.handlers.inbound_attachments import (- leased_attachment_records,- open_leased_attachment_record,- )-directory_fd: int | None = Nonetry:current_root, directory_fd, current_records = leased_attachment_records(source_lease)diff --git a/core/memory/im_attachments.py b/core/memory/im_attachments.pyindex a25068c04..7420392df 100644--- a/core/memory/im_attachments.py+++ b/core/memory/im_attachments.py@@ -6,7 +6,7 @@ import osfrom dataclasses import dataclassfrom typing import Literal-from core.handlers.inbound_attachments import (+from core.inbound_attachment_lease import (InboundAttachmentLease,leased_attachment_records,open_leased_attachment_record,diff --git a/core/memory/module.py b/core/memory/module.pyindex 3b56809f9..d7f4ebbce 100644--- a/core/memory/module.py+++ b/core/memory/module.py@@ -68,7 +68,7 @@ from core.memory.types import (from core.memory.worker import MemoryWorker, ProcessingEventif TYPE_CHECKING:- from core.handlers.inbound_attachments import InboundAttachmentLease+ from core.inbound_attachment_lease import InboundAttachmentLeaseMAX_CAPTURE_TEXT_BYTES = 32 * 1024diff --git a/core/services/dispatch.py b/core/services/dispatch.pyindex 3b30f9c0c..99d32b0d4 100644--- a/core/services/dispatch.py+++ b/core/services/dispatch.py@@ -83,6 +83,7 @@ async def dispatch_turn(source: str = SOURCE_HUMAN,on_chunk: Optional[ChunkCallback] = None,logical_turn_id: str | None = None,+ lifecycle_snapshot: object | None = None,) -> Optional[str]:"""Run one agent turn for ``context`` and return the primary message id.@@ -97,6 +98,7 @@ async def dispatch_turn(source=source,on_chunk=on_chunk,logical_turn_id=logical_turn_id,+ lifecycle_snapshot=lifecycle_snapshot,)return outcome.error@@ -109,11 +111,14 @@ async def dispatch_turn_with_outcome(source: str = SOURCE_HUMAN,on_chunk: Optional[ChunkCallback] = None,logical_turn_id: str | None = None,+ lifecycle_snapshot: object | None = None,) -> TurnDispatchOutcome:"""Run one agent turn for ``context`` and report how its waiter was released.``source`` selects between the human-initiated and scheduler-initiatedpaths in ``MessageHandler``; today they only differ in source tagging.+ ``lifecycle_snapshot`` is a process-local capture token passed explicitly+ to the handler; it never enters the JSON-oriented platform payload.``on_chunk`` (the N3 socket / web Chat path) receives each notify/resultemit for this turn as it happens. Because the agent backends are@@ -130,9 +135,25 @@ async def dispatch_turn_with_outcome(handler = controller.message_handlerasync def _run() -> Optional[str]:+ nonlocal lifecycle_snapshot+ snapshot = lifecycle_snapshot+ lifecycle_snapshot = None+ snapshot_options = (+ {"lifecycle_snapshot": snapshot}+ if snapshot is not None+ else {}+ )if source == SOURCE_SCHEDULED:- return await handler.handle_scheduled_message(context, text)- return await handler.handle_user_message(context, text)+ return await handler.handle_scheduled_message(+ context,+ text,+ **snapshot_options,+ )+ return await handler.handle_user_message(+ context,+ text,+ **snapshot_options,+ )if on_chunk is None:# IM / CLI: fire-and-forget; no live stream to hold open.diff --git a/core/session_turns.py b/core/session_turns.pyindex 25c60cb58..9c2d0603c 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -19,6 +19,7 @@ import inspectimport jsonimport loggingimport uuid+import weakreffrom contextlib import contextmanagerfrom dataclasses import dataclass, field, replacefrom datetime import datetime, timezone@@ -78,7 +79,7 @@ from storage.models import ()from storage.workbench_sessions_service import derive_session_harness_activitiesfrom core.message_output import terminal_turn_output-from core.memory.admission import (+from core.memory.admission_metadata import (is_cli_admitted as memory_cli_admitted,is_ordinary_text as memory_ordinary_text,merge_identity as memory_admission_merge_identity,@@ -96,22 +97,35 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-TURN_LIFECYCLE_ADMISSION_KEY = "_turn_lifecycle_admission"-TURN_LIFECYCLE_EPOCH_KEY = "_turn_lifecycle_epoch"+@dataclass+class _SessionLifecycleState:+ """One live session generation retained only by active lifecycle work."""++ admission_lock: asyncio.Lock = field(default_factory=asyncio.Lock)+ operation_lock: asyncio.Lock = field(default_factory=asyncio.Lock)+ epoch: int = 0+++@dataclass(frozen=True, slots=True)+class SessionLifecycleSnapshot:+ """Strong reference proving which live session generation admitted a turn."""++ _state: _SessionLifecycleState+ epoch: int@dataclassclass TurnLifecycleAdmission:"""One idempotent lease bridging turn admission into Memory capture."""- _lock: asyncio.Lock+ _state: _SessionLifecycleState_released: bool = field(default=False, init=False)def release(self) -> None:if self._released:returnself._released = True- self._lock.release()+ self._state.admission_lock.release()def _utc_now_iso() -> str:@@ -611,9 +625,9 @@ class SessionTurnManager:self._draining_backends: set[str] = set()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] = {}- self._session_lifecycle_ops: dict[str, asyncio.Lock] = {}+ self._session_lifecycle_states: weakref.WeakValueDictionary[+ str, _SessionLifecycleState+ ] = weakref.WeakValueDictionary()# 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]]] = {}@@ -653,63 +667,75 @@ class SessionTurnManager:"""True when ``session_id`` has an active (RUNNING) turn."""return bool(session_id) and session_id in self.in_flight- async def acquire_lifecycle_admission(+ def _session_lifecycle_state(self,raw_session_id: str,- ) -> TurnLifecycleAdmission:- """Best-effort lease so a capture can quiesce before a destructive op.-- Turn dispatch must not await this lock. Capture tasks acquire it on- their own task so a hung sidecar cannot fence the next message.- """-+ ) -> _SessionLifecycleState:if not isinstance(raw_session_id, str) or not raw_session_id:- raise ValueError("session lifecycle admission requires a session id")- lock = self._session_lifecycle_locks.setdefault(- raw_session_id,- asyncio.Lock(),- )- await lock.acquire()- return TurnLifecycleAdmission(lock)+ raise ValueError("session lifecycle requires a session id")+ state = self._session_lifecycle_states.get(raw_session_id)+ if state is None:+ state = _SessionLifecycleState()+ self._session_lifecycle_states[raw_session_id] = state+ return state++ def snapshot_session_lifecycle(+ self,+ raw_session_id: str,+ ) -> SessionLifecycleSnapshot:+ """Retain the generation that may attribute one optional capture."""++ state = self._session_lifecycle_state(raw_session_id)+ return SessionLifecycleSnapshot(state, state.epoch)- def session_lifecycle_epoch(self, raw_session_id: str) -> int:- """Return the local lifecycle generation for one canonical session."""+ def session_lifecycle_snapshot_matches(+ self,+ raw_session_id: str,+ snapshot: object,+ ) -> bool:+ """Revalidate a retained generation before Memory attribution."""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)+ raise ValueError("session lifecycle requires a session id")+ if not isinstance(snapshot, SessionLifecycleSnapshot):+ return False+ state = self._session_lifecycle_states.get(raw_session_id)+ return (+ state is snapshot._state+ and snapshot._state.epoch == snapshot.epoch+ )- def session_lifecycle_epoch_matches(+ async def acquire_lifecycle_admission(self,raw_session_id: str,- expected_epoch: int,- ) -> bool:- """Revalidate a pre-await lifecycle fact before Memory attribution."""+ ) -> TurnLifecycleAdmission:+ """Best-effort lease so a capture can quiesce before a destructive op.- return self.session_lifecycle_epoch(raw_session_id) == expected_epoch+ Turn dispatch must not await this lock. Capture tasks acquire it on+ their own task so a hung sidecar cannot fence the next message.+ """- def _advance_session_lifecycle_epoch(+ state = self._session_lifecycle_state(raw_session_id)+ await state.admission_lock.acquire()+ return TurnLifecycleAdmission(state)++ def _advance_session_lifecycle(self,raw_session_id: str,+ state: _SessionLifecycleState,*,abandon_captures: bool = False,- ) -> int:- """Advance the generation token; cancel captures only when asked.-- Cancellation is for the timeout path, where a capture may still hold- the lifecycle lock. The success path only needs the epoch bump: the- capture task's epoch check discards stale work without killing a- capture admitted for the new generation.- """+ ) -> None:+ """Invalidate retained snapshots; cancel captures only when asked."""- next_epoch = self.session_lifecycle_epoch(raw_session_id) + 1- self._session_lifecycle_epochs[raw_session_id] = next_epoch+ if self._session_lifecycle_states.get(raw_session_id) is not state:+ raise RuntimeError("session lifecycle ownership changed")+ state.epoch += 1if abandon_captures:handler = getattr(self.controller, "message_handler", None)abandon = getattr(handler, "abandon_memory_captures_for_session", None)if callable(abandon):abandon(raw_session_id)- return next_epochasync def run_session_lifecycle(self,@@ -721,16 +747,13 @@ class SessionTurnManager:"""Run a destructive transition, failing open if capture is still busy.Waits up to ``deadline_seconds`` so a nearly-finished capture can- flush. On timeout the epoch advances, in-flight captures are+ flush. On timeout the generation advances, in-flight captures areabandoned, and ``operation`` still runs. A hung Memory sidecarmust not fail ``/new`` or archive."""- op_lock = self._session_lifecycle_ops.setdefault(- raw_session_id,- asyncio.Lock(),- )- await op_lock.acquire()+ state = self._session_lifecycle_state(raw_session_id)+ await state.operation_lock.acquire()admission = Nonetry:try:@@ -745,18 +768,19 @@ class SessionTurnManager:"session=%s",raw_session_id,)- pre_epoch = self.session_lifecycle_epoch(raw_session_id)+ pre_epoch = state.epochresult = await operation()- if self.session_lifecycle_epoch(raw_session_id) == pre_epoch:- self._advance_session_lifecycle_epoch(+ if state.epoch == pre_epoch:+ self._advance_session_lifecycle(raw_session_id,+ state,abandon_captures=admission is None,)return resultfinally:if admission is not None:admission.release()- op_lock.release()+ state.operation_lock.release()@staticmethoddef _agent_run_ids_from_spec(spec: Any) -> set[str]:@@ -4087,7 +4111,7 @@ class SessionTurnManager:delivery,str(turn["session_id"]),)- lifecycle_epoch = self.session_lifecycle_epoch(lifecycle_anchor)+ lifecycle_snapshot = self.snapshot_session_lifecycle(lifecycle_anchor)archived_before_dispatch = Falserun_terminal_before_dispatch = False@@ -4220,7 +4244,6 @@ class SessionTurnManager:return Falsetry:delivery_payload = self._hydrate_delivery_batch_context(resolved, deliveries)- resolved.platform_specific[TURN_LIFECYCLE_EPOCH_KEY] = lifecycle_epochresolved.platform_specific["turn_token"] = turn_idresolved.platform_specific["delivery_start_attempt_id"] = attempt_idmetadata = delivery_payload.get("metadata") or {}@@ -4283,6 +4306,9 @@ class SessionTurnManager:logical_turn_id=turn_id,delivery_id=str((delivery or {}).get("id") or "") or None,durable_preallocated=True,+ lifecycle_snapshot=(+ lifecycle_snapshot if source == SOURCE_HUMAN else None+ ),)return Trueexcept Exception:@@ -7176,6 +7202,7 @@ class SessionTurnManager:logical_turn_id: str | None = None,delivery_id: str | None = None,durable_preallocated: bool = False,+ lifecycle_snapshot: object | None = None,) -> None:"""Start a fire-and-forget turn and HOLD it open until it settles.@@ -7209,6 +7236,7 @@ class SessionTurnManager:context.platform_specific["turn_token"] = logical_turn_idasync def _runner() -> None:+ nonlocal lifecycle_snapshotcancelled = Falsefailed = Falseprewrite_refused = False@@ -7233,7 +7261,12 @@ class SessionTurnManager:evidence_kind="terminal_run_before_native_dispatch",)return- outcome = await dispatch_turn_with_outcome(+ snapshot_options = (+ {"lifecycle_snapshot": lifecycle_snapshot}+ if lifecycle_snapshot is not None+ else {}+ )+ dispatch = dispatch_turn_with_outcome(self.controller,context,text,@@ -7247,7 +7280,11 @@ class SessionTurnManager:# slot would free + a Chat send could preempt the still-running# scheduled turn (Codex P2).on_chunk=self._noop_chunk,+ **snapshot_options,)+ snapshot_options.clear()+ lifecycle_snapshot = None+ outcome = await dispatchsettled_by = outcome.settled_bydefinitive_prewrite_exit = outcome.backend_dispatch_attempted is Falsecurrent = self.in_flight.get(str(session_id or ""))diff --git a/docs/plans/memory-coupling-followup.md b/docs/plans/memory-coupling-followup.mdnew file mode 100644index 000000000..4cf12d8c9--- /dev/null+++ b/docs/plans/memory-coupling-followup.md@@ -0,0 +1,69 @@+# Memory coupling follow-up audit++## Background++PRs #1582, #1588, #1589, and #1590 removed four concrete ways in which+Memory could block session archive, overwrite transport identity, leak its+metadata vocabulary into the durable queue, or fence dispatch and `/new`.+Those fixes establish a broader invariant: failure or latency in optional+Memory work must not fail, delay without a product-owned bound, or mutate a+non-Memory workflow.++## Goal++Scan every Memory touchpoint outside `core/memory/` and close remaining+violations of that invariant. Keep Memory-owned operations fail-closed where+required for authorization or data integrity, while keeping messaging,+session lifecycle, startup, and shutdown independent.++## Approach++1. Inventory imports, awaits, locks, callbacks, shared identities, and mutable+ state crossing the Memory boundary.+2. Add fast hermetic tests for each credible coupling path before changing it.+3. Fix the highest shared layer and keep provider/platform policy out of core+ delivery code.+4. Run focused tests, the Memory independence scenario guardrails, Ruff, and+ the broader affected suites.++## Findings and resolution++- Metadata leaf imports previously executed eager `core.memory` package exports+ and loaded the full store/worker/provider stack. Public exports are now lazy,+ and subprocess contracts prove storage sees only the metadata leaf.+- Lifecycle snapshots previously crossed dispatch through the JSON-oriented+ `platform_specific` payload, and reading that key made `MessageHandler` import+ the SQLite-backed session FSM. Snapshots now use an explicit transient dispatch+ argument, are released after capture admission, and keep lightweight handler+ imports storage-free.+- IM attachment filtering previously reached back through `core.handlers`,+ creating a handler/session-turn import cycle. The opaque lease and descriptor+ validation primitives now live in a dependency-free core leaf.+- Session capture locks, operation locks, and generation integers retained one+ entry for every historical session. A weak lifecycle state now stays alive+ only while an operation or capture snapshot can still use it.+- Synchronous text-capture setup exceptions could escape into message dispatch.+ The scheduling boundary now logs and drops optional work.+- Archived Workbench sessions retained process-local Memory authorization, and+ archive flush tasks could outlive Memory runtime shutdown. Archive completion+ now forgets the cache, and shutdown closes registration then settles tracked+ flush tasks before closing the runtime.++## Residual boundaries++- A user-initiated factory reset remains settlement-first during shutdown. Its+ durable recovery intent and provider-root ownership make abandoning it less+ safe than waiting; this is explicit Memory maintenance, not an ordinary+ messaging dependency.+- No live provider or IM regression is required for these process-local+ contracts. Existing five-platform behavior remains covered by unchanged+ admission and adapter tests.++## Todo++- [x] Audit controller construction, startup reconciliation, and shutdown.+- [x] Audit capture scheduling, cancellation, and lifecycle generations.+- [x] Audit `/new`, archive, and multi-scope lifecycle paths.+- [x] Audit routing/admission identity and leaf-module dependency direction.+- [x] Add regression coverage and fix confirmed violations.+- [x] Record residual risks and verification evidence.diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 4630d7418..59a9eb493 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -68,7 +68,7 @@ capabilities:- ui/src/components/settings/memory/MemorySearchPanel.test.tsx- ui/src/context/ApiContext.memoryList.test.tsx- id: memory_independence- name: Memory capture must not fence dispatch or destructive session ops+ name: Memory remains optional across delivery and session lifecyclestatus: activecatalog: tests/scenarios/memory_independence/catalog.yamlscenario_tests:@@ -78,6 +78,11 @@ capabilities:- tests/test_command_handler_user_names.py- tests/test_memory_runtime.py- tests/test_internal_server.py+ - tests/test_memory_admission.py+ - tests/test_memory_slice3.py+ - tests/test_controller_dispatch_loop.py+ - tests/test_native_session_providers.py+ - tests/test_core_services_dispatch.py- id: memory_im_attachment_capturename: Bound-DM attachment capture through EverOS multimodal ingeststatus: activediff --git a/tests/scenarios/memory_independence/catalog.yaml b/tests/scenarios/memory_independence/catalog.yamlindex d7d3a289c..c7c2b0827 100644--- a/tests/scenarios/memory_independence/catalog.yaml+++ b/tests/scenarios/memory_independence/catalog.yaml@@ -1,17 +1,26 @@version: 1capability:id: memory_independence- name: Memory capture must not fence dispatch or destructive session ops+ name: Memory remains optional across delivery and session lifecyclecanonical_tests:- tests/test_session_delivery_fsm.py- tests/test_message_handler_typing.py- tests/test_command_handler_user_names.py- tests/test_memory_runtime.py+ - tests/test_memory_admission.py+ - tests/test_memory_slice3.py+ - tests/test_controller_dispatch_loop.py+ - tests/test_native_session_providers.py+ - tests/test_core_services_dispatch.pycontract:dispatch: capture_must_not_fence_turn_startdestructive_ops: new_and_archive_fail_open_on_capture_timeout- generation: epoch_snapshot_prevents_cross_generation_attribution- shutdown: drain_and_cancel_still_settle_accepted_captures+ generation: retained_snapshot_prevents_cross_generation_attribution+ shutdown: capture_and_archive_flush_tasks_settle_before_runtime_close+ imports: shared_delivery_and_handler_imports_stay_behind_leaf_boundaries+ retention: settled_lifecycle_and_archive_authorization_state_is_released+ scheduling: capture_setup_failure_is_best_effort+ transient_dispatch: lifecycle_snapshots_never_enter_platform_payloads_or_waitersstatus_legend:covered: executable evidence existsscenarios:@@ -33,3 +42,51 @@ scenarios:kind: regression_keeplayer: scenariotest: tests/test_session_delivery_fsm.py::test_idle_session_capture_attributes_and_shutdown_drains+ - id: MEMORY-INDEP-004+ name: Shared delivery imports do not load Memory implementations+ status: covered+ kind: guardrail+ layer: contract+ test: tests/test_memory_admission.py::test_session_turns_import_keeps_memory_and_handlers_behind_their_boundaries+ - id: MEMORY-INDEP-005+ name: Settled lifecycle generations do not retain historical sessions+ status: covered+ kind: guardrail+ layer: scenario+ test: tests/test_session_delivery_fsm.py::test_completed_memory_lifecycle_state_does_not_accumulate+ - id: MEMORY-INDEP-006+ name: A synchronous Memory capture setup failure stays best effort+ status: covered+ kind: correctness+ layer: contract+ test: tests/test_message_handler_typing.py::MessageHandlerTypingTests::test_text_memory_capture_setup_failure_is_best_effort+ - id: MEMORY-INDEP-007+ name: Archive releases process-local Memory authorization after final flush+ status: covered+ kind: guardrail+ layer: contract+ test: tests/test_memory_slice3.py::test_archive_memory_cli_session_commits_without_waiting_on_memory+ - id: MEMORY-INDEP-008+ name: Shutdown settles archive Memory flush tasks before closing the runtime+ status: covered+ kind: guardrail+ layer: contract+ test: tests/test_controller_dispatch_loop.py::test_cleanup_sync_stops_watch_service_on_stopped_loop+ - id: MEMORY-INDEP-009+ name: Lightweight handler imports do not load the session FSM or storage+ status: covered+ kind: guardrail+ layer: contract+ test: tests/test_native_session_providers.py::test_native_session_lightweight_imports_do_not_require_sqlite+ - id: MEMORY-INDEP-010+ name: Lifecycle snapshots cross dispatch outside the platform JSON payload+ status: covered+ kind: guardrail+ layer: scenario+ test: tests/test_session_delivery_fsm.py::test_session_lifecycle_waits_for_admitted_turn_capture+ - id: MEMORY-INDEP-011+ name: Streaming waiters release lifecycle snapshots after handler admission+ status: covered+ kind: guardrail+ layer: contract+ test: tests/test_core_services_dispatch.py::test_streaming_dispatch_releases_lifecycle_snapshot_after_handler_returnsdiff --git a/tests/test_controller_dispatch_loop.py b/tests/test_controller_dispatch_loop.pyindex 6c3622d31..f52071d74 100644--- a/tests/test_controller_dispatch_loop.py+++ b/tests/test_controller_dispatch_loop.py@@ -332,6 +332,8 @@ def test_setup_callbacks_gates_work_admission_but_not_runtime_evidence():def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:+ """Scenario: MEMORY-INDEP-008."""+controller = Controller.__new__(Controller)loop = asyncio.new_event_loop()controller._loop = loop@@ -372,6 +374,7 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:async def close(self) -> None:assert stopped["capture"] is True+ assert archive_flush_task.cancelled()self.closed = Truestopped["runtime"] = Truestop_order.append("memory-runtime")@@ -401,6 +404,16 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:controller.memory_runtime = fresh_memory_runtimecontroller._memory_factory_reset_task = loop.create_task(retained_factory_reset())++ async def pending_archive_flush() -> None:+ try:+ await asyncio.Event().wait()+ finally:+ stop_order.append("archive-flush")++ archive_flush_task = loop.create_task(pending_archive_flush())+ controller._archive_memory_flush_tasks = {archive_flush_task}+ loop.run_until_complete(asyncio.sleep(0))controller.update_checker = type("UpdateChecker", (), {"stop": lambda self: None})()controller.receiver_tasks = {}controller.im_client = None@@ -409,8 +422,14 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:try:controller.cleanup_sync()finally:+ if not archive_flush_task.done():+ archive_flush_task.cancel()+ loop.run_until_complete(+ asyncio.gather(archive_flush_task, return_exceptions=True)+ )loop.close()+ assert archive_flush_task.cancelled()assert stopped["tasks"] is Trueassert stopped["watch"] is Trueassert stopped["supervisor"] is True@@ -426,9 +445,10 @@ 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[-3:] == [+ assert stop_order[-4:] == ["capture-registration","capture",+ "archive-flush","memory-runtime",]diff --git a/tests/test_core_services_dispatch.py b/tests/test_core_services_dispatch.pyindex ff8e1362e..502d66f20 100644--- a/tests/test_core_services_dispatch.py+++ b/tests/test_core_services_dispatch.py@@ -17,8 +17,11 @@ streaming lands) cannot break the public contract silently.from __future__ import annotationsimport asyncio+import gcimport sys+import weakreffrom pathlib import Path+from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMockimport pytest@@ -131,6 +134,84 @@ def test_streaming_registers_turn_sink_and_waits_for_result():assert "turn_chunk_callback" not in (ctx.platform_specific or {})+def test_streaming_dispatch_releases_lifecycle_snapshot_after_handler_returns() -> None:+ """Scenario: MEMORY-INDEP-011."""++ class _Snapshot:+ pass++ async def exercise() -> None:+ controller = MagicMock()+ handler_returned = asyncio.Event()+ snapshot_reference = None+ sinks: dict[str, dict] = {}++ async def handle_user_message(+ _context,+ _text,+ *,+ lifecycle_snapshot=None,+ ):+ nonlocal snapshot_reference+ snapshot_reference = weakref.ref(lifecycle_snapshot)+ handler_returned.set()+ return None++ def register_sink(+ session_key,+ *,+ on_chunk,+ done_event,+ turn_token=None,+ context=None,+ ) -> None:+ sinks[session_key] = {+ "on_chunk": on_chunk,+ "done_event": done_event,+ "turn_token": turn_token,+ "context": context,+ }++ controller.message_handler = SimpleNamespace(+ handle_user_message=handle_user_message,+ )+ controller._get_session_key = MagicMock(return_value="slack::C")+ controller._get_turn_sink_key = MagicMock(return_value="slack::C")+ controller.get_turn_sink = MagicMock(+ side_effect=lambda key: sinks.get(key)+ )+ controller.register_turn_sink = MagicMock(side_effect=register_sink)+ controller.pop_turn_sink = MagicMock(+ side_effect=lambda key, _done=None: sinks.pop(key, None)+ )++ snapshot = _Snapshot()+ dispatch = asyncio.create_task(+ dispatch_turn_with_outcome(+ controller,+ _ctx(),+ "hi",+ on_chunk=AsyncMock(),+ lifecycle_snapshot=snapshot,+ )+ )+ del snapshot++ await asyncio.wait_for(handler_returned.wait(), timeout=1.0)+ await asyncio.sleep(0)+ gc.collect()+ assert snapshot_reference is not None+ assert snapshot_reference() is None++ sink = sinks["slack::C"]+ sink["settled_by"] = SETTLED_BY_TERMINAL_RESULT+ sink["done_event"].set()+ outcome = await asyncio.wait_for(dispatch, timeout=1.0)+ assert outcome.settled_by == SETTLED_BY_TERMINAL_RESULT++ asyncio.run(exercise())++def test_on_chunk_absent_keeps_platform_specific_untouched():controller = _build_controller_double()ctx = _ctx()diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 7aeab2033..7d85f7b08 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -277,15 +277,16 @@ def _build_controller_double(handler=None):controller = MagicMock()controller.message_handler = MagicMock()- async def _handle_user_message(context, text):+ async def _handle_user_message(+ context,+ text,+ *,+ lifecycle_snapshot=None,+ ):payload = context.platform_specific or {}- lifecycle_admission = payload.pop(- session_turns.TURN_LIFECYCLE_ADMISSION_KEY,- None,- )- release = getattr(lifecycle_admission, "release", None)- if callable(release):- release()+ assert "_turn_lifecycle_admission" not in payload+ assert "_turn_lifecycle_snapshot" not in payload+ del lifecycle_snapshotif handler is not None:return await handler(context, text)return None@@ -355,23 +356,19 @@ def _build_controller_double(handler=None):return controller-def test_controller_double_releases_turn_lifecycle_admission_before_handler() -> None:+def test_controller_double_omits_retired_turn_lifecycle_admission() -> None:async def _exercise() -> None:- lock = asyncio.Lock()- await lock.acquire()- admission = session_turns.TurnLifecycleAdmission(lock)context = MessageContext(user_id="U",channel_id="C",platform="avibe",- platform_specific={- session_turns.TURN_LIFECYCLE_ADMISSION_KEY: admission,- },+ platform_specific={},)async def handler(received_context, _text):- assert session_turns.TURN_LIFECYCLE_ADMISSION_KEY not in received_context.platform_specific- assert lock.locked() is False+ assert "_turn_lifecycle_admission" not in (+ received_context.platform_specific or {}+ )controller = _build_controller_double(handler=handler)await controller.message_handler.handle_user_message(context, "hello")@@ -2234,7 +2231,9 @@ def test_dispatch_async_stop_receipt_waits_for_terminal_evidence(monkeypatch, tmstarted = asyncio.Event()- async def _never_settles(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ async def _never_settles(+ ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None, **_kwargs+ ):# Model a long agent turn: the backend accepted the prompt but hasn't# produced its terminal result yet. dispatch_turn would normally hold on# ``await done.wait()`` with no timeout — emulate that by just sleeping so@@ -4425,7 +4424,16 @@ def test_scheduled_gate_idle_runs_turn_with_lifecycle(monkeypatch, tmp_path):captured: dict = {}started = asyncio.Event()- async def _fake_dispatch_turn(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ async def _fake_dispatch_turn(+ ctrl,+ ctx,+ text,+ *,+ source=SOURCE_HUMAN,+ on_chunk=None,+ lifecycle_snapshot=None,+ ):+ captured["lifecycle_snapshot"] = lifecycle_snapshotcaptured["source"] = sourcecaptured["on_chunk"] = on_chunkcaptured["text"] = text@@ -4471,6 +4479,7 @@ def test_scheduled_gate_idle_runs_turn_with_lifecycle(monkeypatch, tmp_path):events = asyncio.run(_go())assert captured["source"] == SOURCE_SCHEDULED, "scheduled run dispatches on the scheduler path"+ assert captured["lifecycle_snapshot"] is None# A scheduled run passes the no-op chunk SINK (callable, NOT None) so dispatch_turn# HOLDS the turn open to its terminal result — same as a Chat turn — instead of an# async backend returning at prompt-submit and freeing the slot (Codex P2). The sink@@ -4512,7 +4521,9 @@ def test_hfr_482_create_per_run_delivery_adopts_reserved_session(monkeypatch, tmstarted = asyncio.Event()- async def _fake_dispatch_turn(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ async def _fake_dispatch_turn(+ ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None, **_kwargs+ ):started.set()return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)@@ -4734,7 +4745,9 @@ def test_agent_run_send_now_steers_its_content_without_promoting_fifo(monkeypatcoriginal_started = asyncio.Event()seen: list[tuple[str, str]] = []- async def _dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ async def _dispatch(+ ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None, **_kwargs+ ):seen.append((text, source))if text == "original work":_bind_test_native_start(engine, ctx)@@ -5225,7 +5238,9 @@ def test_concurrent_agent_run_send_now_callers_steer_in_fifo_order(original_started = asyncio.Event()seen: list[str] = []- async def _dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ async def _dispatch(+ ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None, **_kwargs+ ):seen.append(text)_bind_test_native_start(engine, ctx)if text == "original work":@@ -5393,7 +5408,9 @@ def test_agent_run_send_now_restart_preserves_refused_queue_behind_durable_ownerseen: list[str] = []- async def _dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ async def _dispatch(+ ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None, **_kwargs+ ):seen.append(text)return TurnDispatchOutcome(error=None,@@ -5473,7 +5490,9 @@ def test_agent_run_send_now_on_an_idle_backlog_starts_its_own_content(monkeypatcassert request_store.claim(request.id) is not Noneseen: list[str] = []- async def _dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ async def _dispatch(+ ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None, **_kwargs+ ):seen.append(text)return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)@@ -5762,7 +5781,9 @@ def test_idle_send_now_releases_hold_and_starts_the_exact_head(app = internal_server.create_app(controller)controller.emit_agent_message = AsyncMock()- async def _dispatch(ctrl, context, text, *, source=SOURCE_HUMAN, on_chunk=None):+ async def _dispatch(+ ctrl, context, text, *, source=SOURCE_HUMAN, on_chunk=None, **_kwargs+ ):assert text == "retry me later"_bind_test_native_start(engine, context)return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)@@ -6033,7 +6054,16 @@ def test_scheduled_gate_retry_resumes_matching_reserved_delivery(monkeypatch, tmsession_id = session["id"]dispatched: list[str] = []- async def _accept_dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ async def _accept_dispatch(+ ctrl,+ ctx,+ text,+ *,+ source=SOURCE_HUMAN,+ on_chunk=None,+ lifecycle_snapshot=None,+ ):+ del lifecycle_snapshotdispatched.append(text)_bind_test_native_start(engine, ctx)return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)@@ -6200,7 +6230,16 @@ def test_scheduled_send_now_recovers_transferred_reservation(monkeypatch, tmp_paassert request_store.claim(run.id) is not Nonedispatched: list[str] = []- async def _accept_dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ async def _accept_dispatch(+ ctrl,+ ctx,+ text,+ *,+ source=SOURCE_HUMAN,+ on_chunk=None,+ lifecycle_snapshot=None,+ ):+ del lifecycle_snapshotdispatched.append(text)_bind_test_native_start(engine, ctx)return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)@@ -6293,7 +6332,9 @@ def test_scheduled_gate_cancel_stops_scheduled_run(monkeypatch, tmp_path):started = asyncio.Event()- async def _long_dispatch_turn(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ async def _long_dispatch_turn(+ ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None, **_kwargs+ ):_bind_test_native_start(engine, ctx)started.set()await asyncio.sleep(5) # held until the test cancels itdiff --git a/tests/test_memory_admission.py b/tests/test_memory_admission.pyindex 142a68d59..9f476511f 100644--- a/tests/test_memory_admission.py+++ b/tests/test_memory_admission.py@@ -691,7 +691,40 @@ from core.memory.admission_metadata import MEMORY_USER_ID_METADATAassert message_deliveries.MEMORY_USER_ID_METADATA is MEMORY_USER_ID_METADATAassert "core.memory.admission" not in sys.modulesassert "core.memory.im_attachments" not in sys.modules+assert "core.memory.module" not in sys.modules+assert "core.memory.store" not in sys.modules+assert "core.memory.types" not in sys.modulesassert "core.handlers" not in sys.modules+assert "httpx" not in sys.modules+"""+ completed = subprocess.run(+ [sys.executable, "-c", script],+ cwd=Path(__file__).resolve().parents[1],+ check=False,+ capture_output=True,+ text=True,+ )+ assert completed.returncode == 0, completed.stderr+++def test_session_turns_import_keeps_memory_and_handlers_behind_their_boundaries() -> None:+ """Scenario: MEMORY-INDEP-004.++ The delivery FSM must not load optional Memory or handler implementations.+ """++ script = """+import sys+import core.session_turns+assert "core.memory.admission" not in sys.modules+assert "core.memory.attachments" not in sys.modules+assert "core.memory.im_attachments" not in sys.modules+assert "core.memory.module" not in sys.modules+assert "core.memory.runtime" not in sys.modules+assert "core.memory.types" not in sys.modules+assert "core.handlers" not in sys.modules+assert "core.handlers.message_handler" not in sys.modules+assert "aiohttp" not in sys.modules"""completed = subprocess.run([sys.executable, "-c", script],diff --git a/tests/test_memory_slice3.py b/tests/test_memory_slice3.pyindex 722747df8..c76762ec1 100644--- a/tests/test_memory_slice3.py+++ b/tests/test_memory_slice3.py@@ -27,6 +27,7 @@ from core.memory import (CaptureSkipped,MemoryModule,)+from core.memory.admission import InboundTurnFactsfrom core.memory.artifact import FakeMemoryArtifactManagerfrom core.memory.everos import FakeMemoryProviderfrom core.memory.runtime import MemoryRuntime@@ -1094,6 +1095,8 @@ def test_archive_memory_cli_session_commits_without_waiting_on_memory(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,) -> None:+ """Scenario: MEMORY-INDEP-007."""+from storage import workbench_sessions_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state@@ -1139,7 +1142,15 @@ def test_archive_memory_cli_session_commits_without_waiting_on_memory(controller._memory_scopes_by_session = {session_id: (principal_id, PROJECT),}- controller._memory_cli_facts_by_session = {}+ controller._memory_cli_facts_by_session = {+ session_id: InboundTurnFacts(+ platform="avibe",+ user_id="workbench-user",+ message_id="message-1",+ session_id=session_id,+ memory_enabled=True,+ )+ }controller.memory_runtime.recovered_scopes = ((principal_id, PROJECT),)async def run() -> None:@@ -1163,6 +1174,8 @@ def test_archive_memory_cli_session_commits_without_waiting_on_memory(pending = list(getattr(controller, "_archive_memory_flush_tasks", set()))if pending:await asyncio.gather(*pending)+ assert session_id not in controller._memory_scopes_by_session+ assert session_id not in controller._memory_cli_facts_by_sessiontry:asyncio.run(run())@@ -1170,6 +1183,27 @@ def test_archive_memory_cli_session_commits_without_waiting_on_memory(engine.dispose()+def test_archive_memory_flush_drops_on_a_stopped_controller_loop() -> None:+ """Scenario: MEMORY-INDEP-007."""++ session_id = "ses-archived-on-stopped-loop"+ controller = _controller()+ controller._memory_scopes_by_session = {+ session_id: ("u-" + ("2" * 32), PROJECT),+ }+ controller._memory_cli_facts_by_session = {session_id: object()}+ controller._loop = asyncio.new_event_loop()++ try:+ controller._schedule_best_effort_archive_memory_flush(session_id)+ finally:+ controller._loop.close()++ assert session_id not in controller._memory_scopes_by_session+ assert session_id not in controller._memory_cli_facts_by_session+ assert getattr(controller, "_archive_memory_flush_tasks", set()) == set()++def test_archive_memory_cli_session_schedules_flush_when_commit_is_cancelled(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex 779516456..64b0b6d25 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -1198,6 +1198,34 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):admission = await asyncio.wait_for(blocked_lifecycle, timeout=1.0)admission.release()+ async def test_text_memory_capture_setup_failure_is_best_effort(self):+ """Scenario: MEMORY-INDEP-006."""++ controller = _StubController(+ platform="slack",+ ack_mode="reaction",+ typing_result=True,+ )+ controller.capture_user_memory = Mock(+ side_effect=RuntimeError("Memory runtime binding failed")+ )+ handler = MessageHandler(controller)+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ message_id="m-memory-setup-failure",+ platform="slack",+ )++ handler._schedule_text_only_memory_capture(+ context,+ "remember this",+ "base-session",+ expected_snapshot=0,+ )++ assert handler._memory_capture_tasks == set()+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()@@ -1822,7 +1850,7 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):handler._schedule_memory_capture_task(session_id="base-session",- expected_epoch=0,+ expected_snapshot=0,capture=capture_write(),attachment_lease=retained_lease,)diff --git a/tests/test_native_session_providers.py b/tests/test_native_session_providers.pyindex d64c5d75f..4d083d284 100644--- a/tests/test_native_session_providers.py+++ b/tests/test_native_session_providers.py@@ -624,10 +624,14 @@ def test_native_session_service_loads_default_providers_lazily(monkeypatch) -> Ndef test_native_session_lightweight_imports_do_not_require_sqlite() -> None:- """The agent-setup / command-handler / session-handler import path must NOT+ """Scenario: MEMORY-INDEP-009.++ The agent-setup / command-handler / session-handler import path must NOTtransitively pull in sqlite: those modules only need the avibe-cloud URLavailability helpers, which now live in the storage-free ``core.avibe_cloud``- (not ``core.show_pages``, which imports ``storage.db`` to back ``ShowPageStore``)."""+ (not ``core.show_pages``, which imports ``storage.db`` to back+ ``ShowPageStore``).+ """repo_root = Path(__file__).resolve().parents[1]env = dict(os.environ)env["PYTHONPATH"] = str(repo_root) + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")@@ -649,6 +653,8 @@ for module_name in ["core.handlers.session_handler",]:__import__(module_name)++assert "core.session_turns" not in sys.modules"""completed = subprocess.run(diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex d75c4a3a0..94a978991 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -12707,7 +12707,6 @@ def test_dead_accepted_owner_converges_run_session_and_persisted_fifo(from core.internal_server import create_appfrom core.message_output import terminal_output_forfrom core.session_turns import (- TURN_LIFECYCLE_ADMISSION_KEY,SessionTurnManager,emit_matches_active_turn,)@@ -12850,26 +12849,21 @@ def test_dead_accepted_owner_converges_run_session_and_persisted_fifo(async def _handle_scheduled_message(context, message, parsed_session_key=None):del parsed_session_key- lifecycle_admission = (context.platform_specific or {}).pop(- TURN_LIFECYCLE_ADMISSION_KEY,- None,+ assert "_turn_lifecycle_admission" not in (+ context.platform_specific or {}+ )+ await controller.agent_service.handle_message(+ "claude",+ AgentRequest(+ context=context,+ message=message,+ user_message=message,+ working_path=str(tmp_path),+ base_session_id=session_id,+ composite_session_id=f"{session_id}:{tmp_path}",+ session_key=controller._get_session_key(context),+ ),)- try:- await controller.agent_service.handle_message(- "claude",- AgentRequest(- context=context,- message=message,- user_message=message,- working_path=str(tmp_path),- base_session_id=session_id,- composite_session_id=f"{session_id}:{tmp_path}",- session_key=controller._get_session_key(context),- ),- )- finally:- if lifecycle_admission is not None:- lifecycle_admission.release()controller.message_handler = SimpleNamespace(handle_scheduled_message=_handle_scheduled_message,diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex 4caade505..0dec72e9b 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import gcimport jsonimport threadingfrom concurrent.futures import ThreadPoolExecutor@@ -34,8 +35,6 @@ from core.runtime_activation import (from core.session_turns import (SCHEDULED_PROVENANCE_KEY,SOURCE_SCHEDULED,- TURN_LIFECYCLE_ADMISSION_KEY,- TURN_LIFECYCLE_EPOCH_KEY,DeliveryRequest,DeliveryResult,SessionTurnManager,@@ -120,12 +119,12 @@ def _memory_facts_controller():def _complete_capture_admission(context: MessageContext) -> None:- admission = (context.platform_specific or {}).pop(- TURN_LIFECYCLE_ADMISSION_KEY,- None,- )- if admission is not None:- admission.release()+ """Guard that durable dispatch carries no lifecycle state in its JSON bag."""++ payload = context.platform_specific or {}+ assert "_turn_lifecycle_admission" not in payload+ assert "_turn_lifecycle_snapshot" not in payload+ json.dumps(payload)def _agentless_context(session_id: str = "ses_fsm") -> MessageContext:@@ -216,16 +215,50 @@ def _capture_handler(manager: SessionTurnManager) -> MessageHandler:return handler+async def test_completed_memory_lifecycle_state_does_not_accumulate(managers) -> None:+ """Scenario: MEMORY-INDEP-005.++ Settled optional Memory fences must not retain every historical session.+ """++ manager, _other, _engine, _engine_b, _starts = managers+ for index in range(256):+ session_id = f"settled-memory-session-{index}"+ snapshot = manager.snapshot_session_lifecycle(session_id)+ admission = await manager.acquire_lifecycle_admission(session_id)+ admission.release()++ async def reset_session() -> str:+ return "reset"++ assert await manager.run_session_lifecycle(+ session_id,+ reset_session,+ ) == "reset"+ assert not manager.session_lifecycle_snapshot_matches(+ session_id,+ snapshot,+ )++ del admission, snapshot+ gc.collect()+ assert len(manager._session_lifecycle_states) == 0++@pytest.mark.anyioasync def test_session_lifecycle_waits_for_admitted_turn_capture(managers) -> None:+ """Scenario: MEMORY-INDEP-010."""+manager, _other, _engine, _engine_b, _starts = managershandler = _capture_handler(manager)capture_entered = asyncio.Event()release_capture = asyncio.Event()lifecycle_entered = asyncio.Event()- async def run_turn(_session_id, context, _text, **_kwargs):- expected_epoch = context.platform_specific.get(TURN_LIFECYCLE_EPOCH_KEY, 0)+ async def run_turn(_session_id, context, _text, **kwargs):+ _complete_capture_admission(context)+ expected_snapshot = kwargs["lifecycle_snapshot"]async def capture() -> None:capture_entered.set()@@ -233,7 +266,7 @@ async def test_session_lifecycle_waits_for_admitted_turn_capture(managers) -> Nohandler._schedule_memory_capture_task(session_id="ses_fsm",- expected_epoch=expected_epoch,+ expected_snapshot=expected_snapshot,capture=capture(),)@@ -270,19 +303,19 @@ async def test_session_lifecycle_waits_for_admitted_turn_capture(managers) -> No@pytest.mark.anyio-async def test_session_lifecycle_advances_local_epoch_after_operation(managers) -> None:+async def test_session_lifecycle_invalidates_snapshot_after_operation(managers) -> None:manager, _other, _engine, _engine_b, _starts = managers- pre_epoch = manager.session_lifecycle_epoch("ses_fsm")+ snapshot = manager.snapshot_session_lifecycle("ses_fsm")async def lifecycle_operation() -> str:- assert manager.session_lifecycle_epoch("ses_fsm") == pre_epoch+ assert manager.session_lifecycle_snapshot_matches("ses_fsm", snapshot)return "reset"assert await manager.run_session_lifecycle("ses_fsm",lifecycle_operation,) == "reset"- assert manager.session_lifecycle_epoch_matches("ses_fsm", pre_epoch + 1)+ assert not manager.session_lifecycle_snapshot_matches("ses_fsm", snapshot)@pytest.mark.anyio@@ -290,7 +323,7 @@ async def test_failed_session_lifecycle_preserves_sampled_epoch(managers) -> Non"""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")+ sampled_snapshot = manager.snapshot_session_lifecycle("ses_fsm")async def lifecycle_operation() -> str:raise RuntimeError("reset failed")@@ -300,7 +333,10 @@ async def test_failed_session_lifecycle_preserves_sampled_epoch(managers) -> Nonadmission = await manager.acquire_lifecycle_admission("ses_fsm")try:- assert manager.session_lifecycle_epoch_matches("ses_fsm", sampled_epoch)+ assert manager.session_lifecycle_snapshot_matches(+ "ses_fsm",+ sampled_snapshot,+ )finally:admission.release()@@ -324,7 +360,7 @@ async def test_hung_memory_capture_does_not_fence_next_turn_or_destructive_ops(handler._schedule_memory_capture_task(session_id="ses_fsm",- expected_epoch=manager.session_lifecycle_epoch("ses_fsm"),+ expected_snapshot=manager.snapshot_session_lifecycle("ses_fsm"),capture=hung_capture(),)await asyncio.wait_for(capture_holding.wait(), timeout=1.0)@@ -389,7 +425,7 @@ async def test_capture_admitted_before_new_is_discarded_after_transition(attributed: list[str] = []admitted = asyncio.Event()finish_capture = asyncio.Event()- sampled_epoch = manager.session_lifecycle_epoch("ses_fsm")+ sampled_snapshot = manager.snapshot_session_lifecycle("ses_fsm")async def capture_write() -> None:attributed.append("wrote")@@ -399,7 +435,7 @@ async def test_capture_admitted_before_new_is_discarded_after_transition(await finish_capture.wait()await handler._run_memory_capture("ses_fsm",- sampled_epoch,+ sampled_snapshot,capture_write(),)@@ -415,7 +451,10 @@ async def test_capture_admitted_before_new_is_discarded_after_transition(reset_session,deadline_seconds=0.05,) == "reset"- assert not manager.session_lifecycle_epoch_matches("ses_fsm", sampled_epoch)+ assert not manager.session_lifecycle_snapshot_matches(+ "ses_fsm",+ sampled_snapshot,+ )finish_capture.set()await handler.drain_memory_capture_tasks()@@ -437,7 +476,7 @@ async def test_idle_session_capture_attributes_and_shutdown_drains(await handler._run_memory_capture("ses_fsm",- manager.session_lifecycle_epoch("ses_fsm"),+ manager.snapshot_session_lifecycle("ses_fsm"),capture_write(),)assert attributed == ["wrote"]@@ -470,7 +509,7 @@ async def test_successful_lifecycle_does_not_cancel_a_new_generation_capture(async def reset_session() -> str:task = handler._schedule_memory_capture_task(session_id="ses_fsm",- expected_epoch=manager.session_lifecycle_epoch("ses_fsm"),+ expected_snapshot=manager.snapshot_session_lifecycle("ses_fsm"),capture=asyncio.sleep(0),)assert task is not None@@ -503,13 +542,13 @@ async def test_failed_timeout_lifecycle_preserves_in_flight_captures(holding.set()await never_resolves.wait()+ sampled_snapshot = manager.snapshot_session_lifecycle("ses_fsm")handler._schedule_memory_capture_task(session_id="ses_fsm",- expected_epoch=manager.session_lifecycle_epoch("ses_fsm"),+ expected_snapshot=sampled_snapshot,capture=hung_capture(),)await asyncio.wait_for(holding.wait(), timeout=1.0)- sampled_epoch = manager.session_lifecycle_epoch("ses_fsm")async def reset_session() -> str:raise RuntimeError("reset failed")@@ -521,7 +560,10 @@ async def test_failed_timeout_lifecycle_preserves_in_flight_captures(deadline_seconds=0.05,)- assert manager.session_lifecycle_epoch_matches("ses_fsm", sampled_epoch)+ assert manager.session_lifecycle_snapshot_matches(+ "ses_fsm",+ sampled_snapshot,+ )assert handler._memory_capture_tasksassert all(not task.cancelled() for task in handler._memory_capture_tasks)never_resolves.set()@@ -5098,7 +5140,7 @@ def test_persisted_start_does_not_acquire_lifecycle_admission()assert acquired is False- assert "ses_fsm" not in manager._session_lifecycle_locks+ assert "ses_fsm" not in manager._session_lifecycle_states@pytest.mark.parametrize(