diff --git a/python/packages/core/AGENTS.md b/python/packages/core/AGENTS.md index a552412fd4c..441a4dc6801 100644 --- a/python/packages/core/AGENTS.md +++ b/python/packages/core/AGENTS.md @@ -331,7 +331,7 @@ The vector store API is experimental under the shared `VECTOR_STORES` feature ID - **`FileSystemAgentFileStore`** - Disk-backed store rooted under a configurable directory. Enforces relative-path normalization, root containment, and rejects symlink/reparse-point segments to prevent escape. - **`FileSearchResult`** / **`FileSearchMatch`** - `SerializationMixin` DTOs returned by `search`, carrying the matching file name, a context snippet, and the matching lines with 1-based line numbers. Implementers should report each matching line verbatim, including its own terminator, so it can be reused as a `file_access_replace_lines` `new_line`; the pattern itself is matched against the line with its whole terminator removed, so `^`/`$` anchor to the line's text on a CRLF file as they already did on an LF one. A custom store populates these DTOs from its own `search`; the verbatim text is a recommendation, but the line number is not — it must address `split_lines`. - **`FileStoreEntry`** - `SerializationMixin` DTO returned by `list_children`, carrying an entry `name` and `type` (`"file"` or `"directory"`). -- **`FileAccessProvider`** - `ContextProvider` that adds shared file-access tools (`file_access_write`, `file_access_read`, `file_access_read_lines`, `file_access_delete`, `file_access_ls`, `file_access_grep`, `file_access_replace`, `file_access_replace_lines`) plus default usage instructions to each invocation. `file_access_ls` enumerates direct children (both files and subdirectories) as `{name, type}` entries with an optional `glob_pattern`, so the agent can walk the tree level by level; `file_access_grep` searches recursively from an optional base `directory` and returns relative `file_name` paths, scoped via an `fnmatch` `glob_pattern` (where `*` crosses `/`, e.g. `*.md`, `reports/*`). `file_access_replace` substitutes `old_string` with `new_string` (failing if not found, or if multiple matches and `replace_all` is false); `file_access_replace_lines` replaces whole 1-based lines with literal text (each `new_line` includes its own trailing newline; an empty `new_line` deletes the line, including its line break). `file_access_read_lines` returns a 1-based inclusive line range, one line per row as `\t`; `end_line` may be omitted to read to the end of the file, and an `end_line` past the last line clamps to it. Everything after the tab is verbatim, including the line's own terminator (which therefore doubles as the row separator), so a row's text can be fed straight back as a `file_access_replace_lines` `new_line` without losing a `\r\n`. Its line numbering comes from the same `_split_lines_keepends` split as `file_access_replace_lines` and as the stores in this package, so with one of those a number reported by grep addresses the same line in all three tools, including the trailing empty line of a newline-terminated file; grep itself runs through `AgentFileStore.search`, which must number by the same split but does not inherit it, so a store overriding `search` owns its numbering and nothing verifies it at run time. All tools are registered with `approval_mode="always_require"` by default, so every file operation needs host approval. Pass `disable_write_tools=True` to advertise only the read-only tools. To run unattended you can disable approval at the source with `disable_readonly_tool_approval=True` (read, read_lines, ls, grep) and/or `disable_write_tool_approval=True` (write, delete, replace, replace_lines), which register the affected tools with `approval_mode="never_require"`; alternatively, keep approval on and pass one of the static auto-approval rules to `ToolApprovalMiddleware` (via `auto_approval_rules`): `FileAccessProvider.read_only_tools_auto_approval_rule` approves only the read-only tools (read, read_lines, ls, grep), while `FileAccessProvider.all_tools_auto_approval_rule` approves every file-access tool including the write tools. Both rules reject any call carrying a `server_label` so they stay scoped to this provider's local tools and never auto-approve a same-named hosted tool. The tool names are also exposed as class constants (`WRITE_TOOL_NAME`, `READ_TOOL_NAME`, `READ_LINES_TOOL_NAME`, `DELETE_TOOL_NAME`, `LS_TOOL_NAME`, `GREP_TOOL_NAME`, `REPLACE_TOOL_NAME`, `REPLACE_LINES_TOOL_NAME`). Unlike `MemoryContextProvider`, the store is intentionally shared across sessions and agents; pass `session_scoped=True` (with an optional explicit `scope`) to confine tool operations to a working folder derived from the session id or scope via the shared `_storage_key_segment` derivation (the provider fails closed when neither is available). +- **`FileAccessProvider`** - `ContextProvider` that adds shared file-access tools (`file_access_write`, `file_access_read`, `file_access_read_lines`, `file_access_delete`, `file_access_ls`, `file_access_grep`, `file_access_replace`, `file_access_replace_lines`) plus default usage instructions to each invocation. `file_access_ls` enumerates direct children (both files and subdirectories) as `{name, type}` entries with an optional `glob_pattern`, so the agent can walk the tree level by level; `file_access_grep` searches recursively from an optional base `directory` and returns relative `file_name` paths, scoped via an `fnmatch` `glob_pattern` (where `*` crosses `/`, e.g. `*.md`, `reports/*`). `file_access_replace` substitutes `old_string` with `new_string` (failing if not found, or if multiple matches and `replace_all` is false); `file_access_replace_lines` replaces whole 1-based lines with literal text (each `new_line` includes its own trailing newline; an empty `new_line` deletes the line, including its line break). `file_access_read_lines` returns a 1-based inclusive line range, one line per row as `\t`; `end_line` may be omitted to read to the end of the file, and an `end_line` past the last line clamps to it. Everything after the tab is verbatim, including the line's own terminator (which therefore doubles as the row separator), so a row's text can be fed straight back as a `file_access_replace_lines` `new_line` without losing a `\r\n`. Its line numbering comes from the same `_split_lines_keepends` split as `file_access_replace_lines` and as the stores in this package, so with one of those a number reported by grep addresses the same line in all three tools, including the trailing empty line of a newline-terminated file; grep itself runs through `AgentFileStore.search`, which must number by the same split but does not inherit it, so a store overriding `search` owns its numbering and nothing verifies it at run time. All tools are registered with `approval_mode="always_require"` by default, so every file operation needs host approval. Pass `disable_write_tools=True` to advertise only the read-only tools. To run unattended you can disable approval at the source with `disable_readonly_tool_approval=True` (read, read_lines, ls, grep) and/or `disable_write_tool_approval=True` (write, delete, replace, replace_lines), which register the affected tools with `approval_mode="never_require"`; alternatively, keep approval on and pass one of the static auto-approval rules to `ToolApprovalMiddleware` (via `auto_approval_rules`): `FileAccessProvider.read_only_tools_auto_approval_rule` approves only the read-only tools (read, read_lines, ls, grep), while `FileAccessProvider.all_tools_auto_approval_rule` approves every file-access tool including the write tools. Both rules reject any call carrying a `server_label` so they stay scoped to this provider's local tools and never auto-approve a same-named hosted tool. The tool names are also exposed as class constants (`WRITE_TOOL_NAME`, `READ_TOOL_NAME`, `READ_LINES_TOOL_NAME`, `DELETE_TOOL_NAME`, `LS_TOOL_NAME`, `GREP_TOOL_NAME`, `REPLACE_TOOL_NAME`, `REPLACE_LINES_TOOL_NAME`). Unlike `FileMemoryProvider`, the store is intentionally shared across sessions and agents; pass `session_scoped=True` (with an optional explicit `scope`) to confine tool operations to a working folder derived from the session id or scope via the shared `_storage_key_segment` derivation (the provider fails closed when neither is available). ### File Memory Harness (`_harness/_file_memory.py`) diff --git a/python/packages/core/agent_framework/_harness/_file_access.py b/python/packages/core/agent_framework/_harness/_file_access.py index 65b6036bb13..9257ce0ea65 100644 --- a/python/packages/core/agent_framework/_harness/_file_access.py +++ b/python/packages/core/agent_framework/_harness/_file_access.py @@ -2,8 +2,8 @@ """File-access harness provider exposing CRUD/search tools backed by an ``AgentFileStore``. -Unlike :class:`~agent_framework.MemoryContextProvider`, which provides -session-scoped memory that may be isolated per session, :class:`FileAccessProvider` +Unlike :class:`~agent_framework.FileMemoryProvider`, which provides memory +isolated per session by default, :class:`FileAccessProvider` operates on a shared, persistent storage area whose contents are visible across sessions and agents. The provider exposes tools — ``file_access_write``, ``file_access_read``, ``file_access_read_lines``, ``file_access_delete``, @@ -1945,8 +1945,8 @@ class FileAccessProvider(ContextProvider): When ``disable_write_tools`` is set, only the read-only tools (``file_access_read``, ``file_access_read_lines``, ``file_access_ls``, ``file_access_grep``) are advertised. - Unlike :class:`~agent_framework.MemoryContextProvider`, which provides - session-scoped memory that may be isolated per session, + Unlike :class:`~agent_framework.FileMemoryProvider`, which provides memory + isolated per session by default, :class:`FileAccessProvider` operates by default on a shared, persistent store whose contents are visible across sessions and agents. Pass ``session_scoped=True`` (with an optional explicit ``scope``) to confine diff --git a/python/packages/core/agent_framework/_harness/_memory.py b/python/packages/core/agent_framework/_harness/_memory.py index b444db76792..524acf0523f 100644 --- a/python/packages/core/agent_framework/_harness/_memory.py +++ b/python/packages/core/agent_framework/_harness/_memory.py @@ -1,13 +1,21 @@ # Copyright (c) Microsoft. All rights reserved. +"""Legacy memory provider and its storage types. + +``DEFAULT_MEMORY_SOURCE_ID`` is retained for use with this deprecated provider. +For new file-based memory, use :class:`~agent_framework.FileMemoryProvider`. +""" + from __future__ import annotations import asyncio import json import logging import re +import sys import threading import uuid +import warnings import weakref from abc import ABC, abstractmethod from base64 import b32decode @@ -17,6 +25,11 @@ from pathlib import Path from typing import Any, ClassVar, Final, cast +if sys.version_info >= (3, 13): + from warnings import deprecated # pragma: no cover +else: + from typing_extensions import deprecated # pragma: no cover + from .._clients import SupportsChatGetResponse from .._compaction import group_messages from .._feature_stage import ExperimentalFeature, experimental @@ -72,6 +85,10 @@ - keep the memory list short and high-signal """ _FILE_HISTORY_ENCODED_SESSION_PREFIX = "~session-" +_MEMORY_STORE_DEPRECATION_MESSAGE = ( + "MemoryStore is deprecated and will be removed after December 31, 2026. " + "Use AgentFileStore with FileMemoryProvider for new file-based memory." +) HistoryMessageFilter = Callable[[Message], Message | None] # Match word-like tokens of >=2 characters. ``[^\W_]`` is a Unicode letter or # digit (excluding underscore), so CJK/Cyrillic/etc. text yields keywords too @@ -249,8 +266,16 @@ def _format_search_results(results: Sequence[Mapping[str, Any]]) -> str: @experimental(feature_id=ExperimentalFeature.HARNESS) +@deprecated( + "MemoryIndexEntry is deprecated and will be removed after December 31, 2026. " + "Use FileMemoryProvider for new file-based memory.", + stacklevel=2, +) class MemoryIndexEntry: - """Represent one pointer entry written into ``MEMORY.md``.""" + """Represent one pointer entry written into ``MEMORY.md``. + + This type is deprecated along with :class:`MemoryContextProvider` and will be removed after December 31, 2026. + """ topic: str slug: str @@ -286,7 +311,7 @@ def to_dict(self) -> dict[str, str]: } @classmethod - def from_dict(cls, raw_entry: Mapping[str, Any]) -> MemoryIndexEntry: + def from_dict(cls, raw_entry: Mapping[str, Any]) -> MemoryIndexEntry: # pyright: ignore[reportDeprecated] """Parse one index entry from JSON-compatible data. Args: @@ -310,7 +335,7 @@ def from_dict(cls, raw_entry: Mapping[str, Any]) -> MemoryIndexEntry: return cls(topic=topic, slug=slug, summary=summary, updated_at=updated_at) @classmethod - def from_topic_record(cls, record: MemoryTopicRecord) -> MemoryIndexEntry: + def from_topic_record(cls, record: MemoryTopicRecord) -> MemoryIndexEntry: # pyright: ignore[reportDeprecated] """Create one index entry from a topic record. Args: @@ -340,7 +365,7 @@ def to_pointer_line(self, *, max_length: int = DEFAULT_MEMORY_INDEX_LINE_LENGTH) def __eq__(self, other: object) -> bool: """Compare two index entries by value.""" - if not isinstance(other, MemoryIndexEntry): + if not isinstance(other, MemoryIndexEntry): # pyright: ignore[reportDeprecated] return NotImplemented return self.to_dict() == other.to_dict() @@ -353,8 +378,16 @@ def __repr__(self) -> str: @experimental(feature_id=ExperimentalFeature.HARNESS) +@deprecated( + "MemoryTopicRecord is deprecated and will be removed after December 31, 2026. " + "Use FileMemoryProvider for new file-based memory.", + stacklevel=2, +) class MemoryTopicRecord: - """Represent one topic memory markdown file.""" + """Represent one topic memory markdown file. + + This type is deprecated along with :class:`MemoryContextProvider` and will be removed after December 31, 2026. + """ topic: str slug: str @@ -408,7 +441,7 @@ def to_dict(self) -> dict[str, Any]: } @classmethod - def from_dict(cls, raw_record: Mapping[str, Any]) -> MemoryTopicRecord: + def from_dict(cls, raw_record: Mapping[str, Any]) -> MemoryTopicRecord: # pyright: ignore[reportDeprecated] """Parse one topic record from structured data. Args: @@ -482,7 +515,7 @@ def to_markdown(self) -> str: ]).rstrip() @classmethod - def from_markdown(cls, markdown: str, *, fallback_topic: str | None = None) -> MemoryTopicRecord: + def from_markdown(cls, markdown: str, *, fallback_topic: str | None = None) -> MemoryTopicRecord: # pyright: ignore[reportDeprecated] """Parse one topic record from the canonical markdown format. Args: @@ -549,7 +582,7 @@ def from_markdown(cls, markdown: str, *, fallback_topic: str | None = None) -> M def __eq__(self, other: object) -> bool: """Compare two topic records by value.""" - if not isinstance(other, MemoryTopicRecord): + if not isinstance(other, MemoryTopicRecord): # pyright: ignore[reportDeprecated] return NotImplemented return self.to_dict() == other.to_dict() @@ -563,8 +596,21 @@ def __repr__(self) -> str: @experimental(feature_id=ExperimentalFeature.HARNESS) +@deprecated( + _MEMORY_STORE_DEPRECATION_MESSAGE, + category=None, +) class MemoryStore(ABC): - """Abstract backing store for the memory harness.""" + """Define the deprecated backing store for the legacy memory harness. + + This class will be removed after December 31, 2026. + """ + + def __init_subclass__(cls, **kwargs: Any) -> None: + super().__init_subclass__(**kwargs) + # The built-in store has its own warning and must not warn during import. + if MemoryStore in cls.__bases__ and cls.__module__ != __name__: # pyright: ignore[reportDeprecated] + warnings.warn(_MEMORY_STORE_DEPRECATION_MESSAGE, DeprecationWarning, stacklevel=4) def get_owner_id(self, session: AgentSession) -> str | None: """Return the logical owner ID for one session, if the store uses one.""" @@ -595,15 +641,15 @@ def import_provider_state(self, session: AgentSession, *, state: Mapping[str, An del session, state @abstractmethod - def list_topics(self, session: AgentSession, *, source_id: str) -> list[MemoryTopicRecord]: + def list_topics(self, session: AgentSession, *, source_id: str) -> list[MemoryTopicRecord]: # pyright: ignore[reportDeprecated] """Return all topic memory files visible from the current owner.""" @abstractmethod - def get_topic(self, session: AgentSession, *, source_id: str, topic: str) -> MemoryTopicRecord: + def get_topic(self, session: AgentSession, *, source_id: str, topic: str) -> MemoryTopicRecord: # pyright: ignore[reportDeprecated] """Return one topic memory file by topic name or slug.""" @abstractmethod - def write_topic(self, session: AgentSession, record: MemoryTopicRecord, *, source_id: str) -> None: + def write_topic(self, session: AgentSession, record: MemoryTopicRecord, *, source_id: str) -> None: # pyright: ignore[reportDeprecated] """Persist one topic memory file.""" @abstractmethod @@ -618,7 +664,7 @@ def rebuild_index( source_id: str, line_limit: int, line_length: int, - ) -> list[MemoryIndexEntry]: + ) -> list[MemoryIndexEntry]: # pyright: ignore[reportDeprecated] """Rebuild ``MEMORY.md`` from the current topic files and return its entries.""" @abstractmethod @@ -629,7 +675,7 @@ def get_index_text( source_id: str, line_limit: int, line_length: int, - index_entries: Sequence[MemoryIndexEntry] | None = None, + index_entries: Sequence[MemoryIndexEntry] | None = None, # pyright: ignore[reportDeprecated] ) -> str: """Return the current ``MEMORY.md`` text, rebuilding it when needed.""" @@ -665,9 +711,16 @@ def search_transcripts( @experimental(feature_id=ExperimentalFeature.HARNESS) -class MemoryFileStore(MemoryStore): +@deprecated( + "MemoryFileStore is deprecated and will be removed after December 31, 2026. " + "Use FileSystemAgentFileStore with FileMemoryProvider for new file-based memory.", + stacklevel=2, +) +class MemoryFileStore(MemoryStore): # pyright: ignore[reportDeprecated] """Store memory files under ``MEMORY.md``, ``topics/``, and ``transcripts/``. + This store is deprecated along with :class:`MemoryContextProvider` and will be removed after December 31, 2026. + The storage directory must not be writable by untrusted users, because they could replace the final memory files independently of this store's secure temporary writes. """ @@ -819,30 +872,30 @@ def _transcript_file_stem(session_id: str) -> str: raw_session_id = session_id or FileHistoryProvider.DEFAULT_SESSION_FILE_STEM return _storage_key_segment(raw_session_id, encoded_prefix=_FILE_HISTORY_ENCODED_SESSION_PREFIX) - def list_topics(self, session: AgentSession, *, source_id: str) -> list[MemoryTopicRecord]: + def list_topics(self, session: AgentSession, *, source_id: str) -> list[MemoryTopicRecord]: # pyright: ignore[reportDeprecated] """Return all topic memory files visible from the current owner.""" - topics: list[MemoryTopicRecord] = [] + topics: list[MemoryTopicRecord] = [] # pyright: ignore[reportDeprecated] topics_directory = self._get_topics_directory(session, source_id=source_id) if not topics_directory.exists(): return topics for topic_path in sorted(topics_directory.glob("*.md")): if not topic_path.is_file(): continue - record = MemoryTopicRecord.from_markdown( + record = MemoryTopicRecord.from_markdown( # pyright: ignore[reportDeprecated] topic_path.read_text(encoding="utf-8"), fallback_topic=topic_path.stem.replace("-", " "), ) topics.append(record) return sorted(topics, key=lambda record: (record.topic.lower(), record.updated_at)) - def get_topic(self, session: AgentSession, *, source_id: str, topic: str) -> MemoryTopicRecord: + def get_topic(self, session: AgentSession, *, source_id: str, topic: str) -> MemoryTopicRecord: # pyright: ignore[reportDeprecated] """Return one topic memory file by topic name or slug.""" topic_path = self._topic_path(session, source_id=source_id, topic=topic) if not topic_path.exists(): raise FileNotFoundError(f"No memory topic named '{topic}' was found for this owner.") - return MemoryTopicRecord.from_markdown(topic_path.read_text(encoding="utf-8"), fallback_topic=topic) + return MemoryTopicRecord.from_markdown(topic_path.read_text(encoding="utf-8"), fallback_topic=topic) # pyright: ignore[reportDeprecated] - def write_topic(self, session: AgentSession, record: MemoryTopicRecord, *, source_id: str) -> None: + def write_topic(self, session: AgentSession, record: MemoryTopicRecord, *, source_id: str) -> None: # pyright: ignore[reportDeprecated] """Persist one topic memory file.""" topic_path = self._topic_path(session, source_id=source_id, topic=record.slug) _atomic_write_text(topic_path, f"{record.to_markdown()}\n") @@ -861,10 +914,10 @@ def rebuild_index( source_id: str, line_limit: int, line_length: int, - ) -> list[MemoryIndexEntry]: + ) -> list[MemoryIndexEntry]: # pyright: ignore[reportDeprecated] """Rebuild ``MEMORY.md`` from the current topic files and return its entries.""" topics = self.list_topics(session, source_id=source_id) - entries = [MemoryIndexEntry.from_topic_record(topic) for topic in topics] + entries = [MemoryIndexEntry.from_topic_record(topic) for topic in topics] # pyright: ignore[reportDeprecated] pointer_lines = [entry.to_pointer_line(max_length=line_length) for entry in entries[:line_limit]] index_lines = [ DEFAULT_MEMORY_INDEX_HEADER, @@ -885,7 +938,7 @@ def get_index_text( source_id: str, line_limit: int, line_length: int, - index_entries: Sequence[MemoryIndexEntry] | None = None, + index_entries: Sequence[MemoryIndexEntry] | None = None, # pyright: ignore[reportDeprecated] ) -> str: """Return the current ``MEMORY.md`` text, rebuilding it when needed.""" if index_entries is None: @@ -1029,13 +1082,23 @@ def search_transcripts( @experimental(feature_id=ExperimentalFeature.HARNESS) +@deprecated( + "MemoryContextProvider is deprecated and will be removed after December 31, 2026. " + "Use FileMemoryProvider for new file-based memory.", + stacklevel=2, +) class MemoryContextProvider(HistoryProvider): - """Inject ``MEMORY.md``, topic memory tools, and transcript-backed extraction.""" + """Inject ``MEMORY.md``, topic memory tools, and transcript-backed extraction. + + This provider is deprecated and will be removed after December 31, 2026. + :class:`~agent_framework.FileMemoryProvider` uses a different storage format and does not automatically extract + memories or provide transcript history. + """ _LOCKS_GUARD: ClassVar[threading.Lock] = threading.Lock() _STORE_LOCKS_BY_LOOP: ClassVar[ weakref.WeakKeyDictionary[ - asyncio.AbstractEventLoop, weakref.WeakKeyDictionary[MemoryStore, dict[str, asyncio.Lock]] + asyncio.AbstractEventLoop, weakref.WeakKeyDictionary[MemoryStore, dict[str, asyncio.Lock]] # pyright: ignore[reportDeprecated] ] ] = weakref.WeakKeyDictionary() @@ -1044,7 +1107,7 @@ def __init__( recent_turns: int = 0, load_tool_turns: bool = True, *, - store: MemoryStore, + store: MemoryStore, # pyright: ignore[reportDeprecated] source_id: str = DEFAULT_MEMORY_SOURCE_ID, context_prompt: str | None = None, index_line_limit: int = DEFAULT_MEMORY_INDEX_LINE_LIMIT, @@ -1128,11 +1191,11 @@ def _store_async_lock(self, session: AgentSession, *, kind: str, key: str) -> as owner_id = self.store.get_owner_id(session) or "" lock_key = f"{self.source_id}:{owner_id}:{kind}:{key}" with self._LOCKS_GUARD: - store_locks_by_loop: weakref.WeakKeyDictionary[MemoryStore, dict[str, asyncio.Lock]] | None = ( + store_locks_by_loop: weakref.WeakKeyDictionary[MemoryStore, dict[str, asyncio.Lock]] | None = ( # pyright: ignore[reportDeprecated] self._STORE_LOCKS_BY_LOOP.get(loop) ) if store_locks_by_loop is None: - store_locks_by_loop = weakref.WeakKeyDictionary[MemoryStore, dict[str, asyncio.Lock]]() + store_locks_by_loop = weakref.WeakKeyDictionary[MemoryStore, dict[str, asyncio.Lock]]() # pyright: ignore[reportDeprecated] self._STORE_LOCKS_BY_LOOP[loop] = store_locks_by_loop store_locks = store_locks_by_loop.get(self.store) if store_locks is None: @@ -1181,16 +1244,16 @@ def _chat_client( return None @staticmethod - def _topic_score(entry: MemoryIndexEntry, keywords: set[str]) -> int: + def _topic_score(entry: MemoryIndexEntry, keywords: set[str]) -> int: # pyright: ignore[reportDeprecated] topic_keywords = {match.group(0).lower() for match in _WORD_PATTERN.finditer(f"{entry.topic} {entry.summary}")} return len(topic_keywords & keywords) def _select_topics( self, *, - entries: Sequence[MemoryIndexEntry], + entries: Sequence[MemoryIndexEntry], # pyright: ignore[reportDeprecated] input_messages: Sequence[Message], - ) -> list[MemoryIndexEntry]: + ) -> list[MemoryIndexEntry]: # pyright: ignore[reportDeprecated] if self.selection_limit == 0 or not entries: return [] keywords = _extract_keywords(input_messages) @@ -1514,7 +1577,7 @@ async def _extract_memories( session: AgentSession, context: SessionContext, now: datetime, - ) -> list[MemoryTopicRecord]: + ) -> list[MemoryTopicRecord]: # pyright: ignore[reportDeprecated] if client is None or self.max_extractions == 0 or context.response is None or not context.response.messages: return [] transcript_delta = _format_messages_for_memory_model([*context.input_messages, *context.response.messages]) @@ -1552,7 +1615,7 @@ async def _extract_memories( ) return [] - updated_records: list[MemoryTopicRecord] = [] + updated_records: list[MemoryTopicRecord] = [] # pyright: ignore[reportDeprecated] for raw_item in cast(list[object], raw_items)[: self.max_extractions]: if not isinstance(raw_item, Mapping): LOGGER.warning( @@ -1588,14 +1651,14 @@ async def _merge_memory( topic: str, memory: str, now: datetime, - ) -> MemoryTopicRecord: + ) -> MemoryTopicRecord: # pyright: ignore[reportDeprecated] normalized_topic = _normalize_topic(topic) normalized_memory = _normalize_memory_text(memory) async with self._topic_async_lock(session, normalized_topic): try: existing_record = self.store.get_topic(session, source_id=self.source_id, topic=normalized_topic) except FileNotFoundError: - updated_record = MemoryTopicRecord( + updated_record = MemoryTopicRecord( # pyright: ignore[reportDeprecated] topic=normalized_topic, summary=normalized_memory, memories=[normalized_memory], @@ -1603,7 +1666,7 @@ async def _merge_memory( session_ids=[session.session_id], ) else: - updated_record = MemoryTopicRecord( + updated_record = MemoryTopicRecord( # pyright: ignore[reportDeprecated] topic=existing_record.topic, slug=existing_record.slug, summary=existing_record.summary, @@ -1708,9 +1771,9 @@ async def _consolidate_topic( self, *, client: SupportsChatGetResponse[Any] | None, - record: MemoryTopicRecord, + record: MemoryTopicRecord, # pyright: ignore[reportDeprecated] now: datetime, - ) -> tuple[MemoryTopicRecord, bool]: + ) -> tuple[MemoryTopicRecord, bool]: # pyright: ignore[reportDeprecated] """Return the consolidated record and a flag indicating whether consolidation succeeded. ``succeeded`` is False when the LLM call raises a transient error or returns malformed @@ -1720,7 +1783,7 @@ async def _consolidate_topic( """ if client is None: return ( - MemoryTopicRecord( + MemoryTopicRecord( # pyright: ignore[reportDeprecated] topic=record.topic, slug=record.slug, summary=_coerce_summary(record.summary, record.memories), @@ -1777,7 +1840,7 @@ async def _consolidate_topic( return record, False consolidated_memories = [memory for memory in cast(list[object], raw_memories) if isinstance(memory, str)] return ( - MemoryTopicRecord( + MemoryTopicRecord( # pyright: ignore[reportDeprecated] topic=record.topic, slug=record.slug, summary=summary, diff --git a/python/packages/core/tests/core/test_feature_stage.py b/python/packages/core/tests/core/test_feature_stage.py index 797fc859e8d..335bc48db9e 100644 --- a/python/packages/core/tests/core/test_feature_stage.py +++ b/python/packages/core/tests/core/test_feature_stage.py @@ -10,7 +10,7 @@ import pytest -from agent_framework import ComputerSafetyCheck, Content +from agent_framework import ComputerSafetyCheck, Content, MemoryIndexEntry # ty: ignore[deprecated] from agent_framework import ExperimentalFeature as PublicExperimentalFeature from agent_framework import ReleaseCandidateFeature as PublicReleaseCandidateFeature from agent_framework._feature_stage import ( @@ -135,6 +135,15 @@ def my_function(value: int) -> int: assert warning_index < args_index +def test_deprecated_experimental_class_warnings_point_to_caller() -> None: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + MemoryIndexEntry("topic", "topic", "summary", "2026-01-01") # ty: ignore[deprecated] + + assert {item.category for item in caught} == {ExperimentalWarning, DeprecationWarning} + assert all(item.filename == __file__ for item in caught) + + def test_experimental_class_warns_on_instantiation_and_not_on_definition() -> None: with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") diff --git a/python/packages/core/tests/core/test_harness_file_memory.py b/python/packages/core/tests/core/test_harness_file_memory.py index 5d8f7394be2..77043ddeb10 100644 --- a/python/packages/core/tests/core/test_harness_file_memory.py +++ b/python/packages/core/tests/core/test_harness_file_memory.py @@ -4,6 +4,7 @@ import asyncio import json +import warnings import pytest import regex @@ -55,6 +56,14 @@ async def _prepare( return context, tools +def test_file_memory_provider_does_not_emit_deprecation_warning() -> None: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", DeprecationWarning) + FileMemoryProvider(store=InMemoryAgentFileStore()) + + assert not [item for item in caught if issubclass(item.category, DeprecationWarning)] + + def test_description_file_name_replaces_extension() -> None: """The description sidecar replaces a known extension and appends otherwise.""" assert _description_file_name("notes.md") == "notes_description.md" diff --git a/python/packages/core/tests/core/test_harness_memory.py b/python/packages/core/tests/core/test_harness_memory.py index ff49ec5afb0..ac3e4fbcdd6 100644 --- a/python/packages/core/tests/core/test_harness_memory.py +++ b/python/packages/core/tests/core/test_harness_memory.py @@ -4,6 +4,7 @@ import asyncio import json +import warnings from collections.abc import Mapping, Sequence from datetime import datetime, timedelta, timezone from pathlib import Path @@ -20,17 +21,22 @@ Content, ExperimentalFeature, FileHistoryProvider, - MemoryContextProvider, - MemoryFileStore, - MemoryIndexEntry, - MemoryStore, - MemoryTopicRecord, + MemoryContextProvider, # ty: ignore[deprecated] + MemoryFileStore, # ty: ignore[deprecated] + MemoryIndexEntry, # ty: ignore[deprecated] + MemoryStore, # ty: ignore[deprecated] + MemoryTopicRecord, # ty: ignore[deprecated] Message, ) from agent_framework import _filesystem as filesystem_module from .test_filesystem import COLLIDING_IDENTIFIERS +pytestmark = pytest.mark.filterwarnings( + r"ignore:(MemoryContextProvider|MemoryFileStore|MemoryIndexEntry|MemoryStore|MemoryTopicRecord) " + r"is deprecated\.:DeprecationWarning" +) + def _no_store_options() -> ChatOptions: return {"store": False} @@ -96,6 +102,55 @@ async def get_response( return ChatResponse(messages=[Message(role="assistant", contents=[self.default_text])]) +@pytest.mark.parametrize( + "memory_class", + [MemoryContextProvider, MemoryFileStore, MemoryIndexEntry, MemoryStore, MemoryTopicRecord], # ty: ignore[deprecated] +) +def test_memory_harness_classes_have_deprecation_metadata(memory_class: type[object]) -> None: + message = getattr(memory_class, "__deprecated__", None) + assert isinstance(message, str) + assert memory_class.__name__ in message + assert "FileMemoryProvider" in message + assert "will be removed after December 31, 2026" in message + assert "will be removed after December 31, 2026" in (memory_class.__doc__ or "") + + +def test_memory_harness_classes_warn_when_used(tmp_path: Path) -> None: + with pytest.warns(DeprecationWarning, match="MemoryIndexEntry.*after December 31, 2026.*FileMemoryProvider"): + MemoryIndexEntry("preferences", "preferences", "A summary", "2026-01-01") # ty: ignore[deprecated] + with pytest.warns(DeprecationWarning, match="MemoryTopicRecord.*after December 31, 2026.*FileMemoryProvider"): + MemoryTopicRecord(topic="preferences", summary="A summary", memories=["A memory"], updated_at="2026-01-01") # ty: ignore[deprecated] + with pytest.warns(DeprecationWarning, match="MemoryFileStore.*after December 31, 2026.*FileMemoryProvider"): + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] + with pytest.warns(DeprecationWarning, match="MemoryContextProvider.*after December 31, 2026.*FileMemoryProvider"): + MemoryContextProvider(store=store) # ty: ignore[deprecated] + + +def test_memory_store_warns_when_subclassed() -> None: + with pytest.warns(DeprecationWarning, match="MemoryStore.*after December 31, 2026.*FileMemoryProvider") as caught: + + class CustomMemoryStore(MemoryStore): # ty: ignore[deprecated] + pass + + assert issubclass(CustomMemoryStore, MemoryStore) # ty: ignore[deprecated] + warning = next(item for item in caught if issubclass(item.category, DeprecationWarning)) + assert Path(warning.filename).resolve() == Path(__file__).resolve() + assert str(warning.message) == getattr(MemoryStore, "__deprecated__", None) # ty: ignore[deprecated] + + +def test_memory_file_store_subclass_warns_once() -> None: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", DeprecationWarning) + + class CustomMemoryFileStore(MemoryFileStore): # ty: ignore[deprecated] + pass + + assert issubclass(CustomMemoryFileStore, MemoryFileStore) # ty: ignore[deprecated] + deprecations = [item for item in caught if issubclass(item.category, DeprecationWarning)] + assert len(deprecations) == 1 + assert "MemoryFileStore" in str(deprecations[0].message) + + def test_memory_index_entry_round_trips_and_trims_pointer_lines() -> None: """Memory index entries should preserve value equality and trim pointer lines.""" raw_entry = { @@ -107,9 +162,9 @@ def test_memory_index_entry_round_trips_and_trims_pointer_lines() -> None: "updated_at": "2026-04-21T10:00:00+00:00", } - entry = MemoryIndexEntry.from_dict(raw_entry) + entry = MemoryIndexEntry.from_dict(raw_entry) # ty: ignore[deprecated] - assert entry == MemoryIndexEntry(**raw_entry) + assert entry == MemoryIndexEntry(**raw_entry) # ty: ignore[deprecated] assert entry.to_dict() == raw_entry assert len(entry.to_pointer_line(max_length=80)) <= 80 assert "MemoryIndexEntry(" in repr(entry) @@ -126,10 +181,10 @@ def test_memory_topic_record_round_trips_through_dict_and_markdown() -> None: "session_ids": ["session-1", "session-2"], } - record = MemoryTopicRecord.from_dict(raw_record) - reparsed_record = MemoryTopicRecord.from_markdown(record.to_markdown()) + record = MemoryTopicRecord.from_dict(raw_record) # ty: ignore[deprecated] + reparsed_record = MemoryTopicRecord.from_markdown(record.to_markdown()) # ty: ignore[deprecated] - assert record == MemoryTopicRecord(**raw_record) # type: ignore[arg-type] + assert record == MemoryTopicRecord(**raw_record) # type: ignore[arg-type] # ty: ignore[deprecated] assert record.to_dict() == raw_record assert reparsed_record == record assert "MemoryTopicRecord(" in repr(record) @@ -147,10 +202,10 @@ def test_memory_topic_record_round_trips_through_dict_and_markdown() -> None: ) def test_memory_file_store_preserves_metadata_like_summary_text(tmp_path: Path, summary: str) -> None: """Summary text must not replace metadata when a topic is reloaded from disk.""" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" - record = MemoryTopicRecord( + record = MemoryTopicRecord( # ty: ignore[deprecated] topic="preferences", summary=summary, memories=["Updated: the milestone moved.", "Sessions: retain previous notes."], @@ -158,13 +213,13 @@ def test_memory_file_store_preserves_metadata_like_summary_text(tmp_path: Path, session_ids=["session-1", "session-2"], ) - assert MemoryTopicRecord.from_markdown(record.to_markdown()) == record + assert MemoryTopicRecord.from_markdown(record.to_markdown()) == record # ty: ignore[deprecated] store.write_topic(session, record, source_id=DEFAULT_MEMORY_SOURCE_ID) assert store.get_topic(session, source_id=DEFAULT_MEMORY_SOURCE_ID, topic=record.slug) == record assert store.list_topics(session, source_id=DEFAULT_MEMORY_SOURCE_ID) == [record] entries = store.rebuild_index(session, source_id=DEFAULT_MEMORY_SOURCE_ID, line_limit=200, line_length=150) - assert entries == [MemoryIndexEntry.from_topic_record(record)] + assert entries == [MemoryIndexEntry.from_topic_record(record)] # ty: ignore[deprecated] @pytest.mark.parametrize("summary_line", ["Updated: the release date changed.", "Sessions: keep previous notes."]) @@ -181,7 +236,7 @@ def test_memory_topic_record_preserves_multiline_summary_metadata_text(summary_l "- Sessions: retain previous notes.\n" ) - record = MemoryTopicRecord.from_markdown(markdown) + record = MemoryTopicRecord.from_markdown(markdown) # ty: ignore[deprecated] assert record.summary == f"Keep the release notes. {summary_line}" assert record.updated_at == "2026-04-21T10:05:00+00:00" @@ -191,7 +246,7 @@ def test_memory_topic_record_preserves_multiline_summary_metadata_text(summary_l async def test_memory_file_store_writes_topics_index_state_and_transcripts(tmp_path) -> None: """The file-backed memory store should manage topics, ``MEMORY.md``, state, and transcript search.""" - store = MemoryFileStore( + store = MemoryFileStore( # ty: ignore[deprecated] tmp_path, kind="memories", owner_prefix="user_", @@ -203,14 +258,14 @@ async def test_memory_file_store_writes_topics_index_state_and_transcripts(tmp_p session.state["owner_id"] = "alice" updated_at = datetime(2026, 4, 21, tzinfo=timezone.utc).replace(microsecond=0).isoformat() - preferences_record = MemoryTopicRecord( + preferences_record = MemoryTopicRecord( # ty: ignore[deprecated] topic="preferences", summary="Prefers concise answers.", memories=["Prefers concise answers.", "Prefers aisle seats."], updated_at=updated_at, session_ids=["session-1"], ) - travel_record = MemoryTopicRecord( + travel_record = MemoryTopicRecord( # ty: ignore[deprecated] topic="travel", summary="Planning a Norway trip.", memories=["Visit Oslo in June."], @@ -280,7 +335,7 @@ def test_memory_file_store_quarantines_corrupt_state_file(tmp_path: Path) -> Non the session store's quarantine convention and the next write recreates a clean one. """ - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" store.write_state( @@ -313,7 +368,7 @@ def test_memory_file_store_quarantines_corrupt_state_file(tmp_path: Path) -> Non def test_memory_file_store_quarantines_non_utf8_state_file(tmp_path: Path) -> None: """Non-text bytes follow the same quarantine path as malformed JSON.""" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" state_path = store._get_state_path(session, source_id=DEFAULT_MEMORY_SOURCE_ID) @@ -351,7 +406,7 @@ def racing_loads(text: str | bytes) -> Any: raise json.JSONDecodeError("corrupt", document, 0) return real_loads(text) - store = MemoryFileStore(tmp_path, owner_state_key="owner_id", loads=racing_loads) + store = MemoryFileStore(tmp_path, owner_state_key="owner_id", loads=racing_loads) # ty: ignore[deprecated] session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" state_path.append(store._get_state_path(session, source_id=DEFAULT_MEMORY_SOURCE_ID)) @@ -363,7 +418,7 @@ def racing_loads(text: str | bytes) -> Any: assert not list(state_path[0].parent.glob(".state.json.*.corrupt")) -async def _write_transcript(store: MemoryFileStore, session: AgentSession, session_id: str, text: str) -> None: +async def _write_transcript(store: MemoryFileStore, session: AgentSession, session_id: str, text: str) -> None: # ty: ignore[deprecated] """Append a one-message transcript for ``session_id`` through the real write path.""" provider = FileHistoryProvider(store.get_transcripts_directory(session, source_id=DEFAULT_MEMORY_SOURCE_ID)) await provider.save_messages(session_id, [Message(role="user", contents=[text])]) @@ -373,7 +428,7 @@ async def test_search_transcripts_finds_session_stored_under_digest_stem(tmp_pat """A session ID too long to encode is stored under an irreversible digest stem but stays findable.""" session = AgentSession(session_id="session-1") session.state["owner_id"] = "user-1" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] long_session_id = "a/" + "a" * 108 await _write_transcript(store, session, "short-id", "Short session transcript.") @@ -404,7 +459,7 @@ async def test_search_transcripts_isolates_colliding_session_ids(tmp_path) -> No """Session IDs that normalize alike must each retrieve only their own transcript.""" session = AgentSession(session_id="session-1") session.state["owner_id"] = "user-1" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] for index, candidate in enumerate(COLLIDING_IDENTIFIERS): await _write_transcript(store, session, candidate, f"Transcript {index}.") @@ -421,7 +476,7 @@ async def test_search_transcripts_returns_nothing_for_unknown_session(tmp_path) """Filtering by a session that never wrote a transcript should return no results.""" session = AgentSession(session_id="session-1") session.state["owner_id"] = "user-1" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] await _write_transcript(store, session, "known-id", "Known transcript.") assert ( @@ -436,23 +491,19 @@ async def test_search_transcripts_non_positive_limit_returns_nothing(tmp_path) - """A non-positive limit must return no results, not a single row.""" session = AgentSession(session_id="session-1") session.state["owner_id"] = "user-1" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] await _write_transcript(store, session, "session-1", "Matching transcript.") - assert store.search_transcripts( - session, source_id=DEFAULT_MEMORY_SOURCE_ID, query="transcript", limit=0 - ) == [] - assert store.search_transcripts( - session, source_id=DEFAULT_MEMORY_SOURCE_ID, query="transcript", limit=-1 - ) == [] + assert store.search_transcripts(session, source_id=DEFAULT_MEMORY_SOURCE_ID, query="transcript", limit=0) == [] + assert store.search_transcripts(session, source_id=DEFAULT_MEMORY_SOURCE_ID, query="transcript", limit=-1) == [] def test_memory_file_store_rejects_owner_path_traversal(tmp_path) -> None: """Owner IDs with path traversal segments should not escape ``base_path``.""" session = AgentSession(session_id="session-1") session.state["owner_id"] = "../escape" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") - record = MemoryTopicRecord( + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] + record = MemoryTopicRecord( # ty: ignore[deprecated] topic="preferences", summary="Prefers concise answers.", memories=["Prefers concise answers."], @@ -469,7 +520,7 @@ async def test_memory_file_store_namespaces_topics_state_and_transcripts_by_sour """Providers sharing one file store should not collide when they use different source IDs.""" session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" - store = MemoryFileStore( + store = MemoryFileStore( # ty: ignore[deprecated] tmp_path, owner_state_key="owner_id", dumps=lambda value: json.dumps(value, separators=(",", ":"), sort_keys=True), @@ -479,7 +530,7 @@ async def test_memory_file_store_namespaces_topics_state_and_transcripts_by_sour store.write_topic( session, - MemoryTopicRecord( + MemoryTopicRecord( # ty: ignore[deprecated] topic="preferences", summary="Source A summary.", memories=["Source A memory."], @@ -489,7 +540,7 @@ async def test_memory_file_store_namespaces_topics_state_and_transcripts_by_sour ) store.write_topic( session, - MemoryTopicRecord( + MemoryTopicRecord( # ty: ignore[deprecated] topic="preferences", summary="Source B summary.", memories=["Source B memory."], @@ -527,10 +578,10 @@ async def test_memory_context_provider_does_not_rewrite_unchanged_index(tmp_path """A second before-run pass with unchanged memories should preserve ``MEMORY.md`` mtime.""" session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] agent = Agent( client=_MemoryHarnessClient(), # type: ignore[arg-type] # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type] - context_providers=[MemoryContextProvider(store=store)], + context_providers=[MemoryContextProvider(store=store)], # ty: ignore[deprecated] default_options=_no_store_options(), ) @@ -553,7 +604,7 @@ async def test_memory_context_provider_tools_and_automation(tmp_path) -> None: """The memory provider should expose tools and automate extraction plus consolidation.""" session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" - store = MemoryFileStore( + store = MemoryFileStore( # ty: ignore[deprecated] tmp_path, kind="memories", owner_prefix="user_", @@ -561,7 +612,7 @@ async def test_memory_context_provider_tools_and_automation(tmp_path) -> None: dumps=lambda value: json.dumps(value, separators=(",", ":"), sort_keys=True), loads=json.loads, ) - provider = MemoryContextProvider( + provider = MemoryContextProvider( # ty: ignore[deprecated] store=store, consolidation_min_sessions=1, consolidation_interval=timedelta(0), @@ -613,7 +664,7 @@ async def test_memory_context_provider_injects_recent_turns(tmp_path) -> None: """The memory provider should inject only the configured recent transcript turns.""" session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" - store = MemoryFileStore( + store = MemoryFileStore( # ty: ignore[deprecated] tmp_path, kind="memories", owner_prefix="user_", @@ -621,7 +672,7 @@ async def test_memory_context_provider_injects_recent_turns(tmp_path) -> None: dumps=lambda value: json.dumps(value, separators=(",", ":"), sort_keys=True), loads=json.loads, ) - provider = MemoryContextProvider(store=store, recent_turns=2) + provider = MemoryContextProvider(store=store, recent_turns=2) # ty: ignore[deprecated] provider_state = store.export_provider_state(session) await provider.save_messages( session.session_id, @@ -662,7 +713,7 @@ async def test_memory_context_provider_recent_turns_can_skip_tool_call_groups(tm """Recent-turn loading should follow compaction grouping and optionally skip tool-call groups.""" session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" - store = MemoryFileStore( + store = MemoryFileStore( # ty: ignore[deprecated] tmp_path, kind="memories", owner_prefix="user_", @@ -671,7 +722,7 @@ async def test_memory_context_provider_recent_turns_can_skip_tool_call_groups(tm loads=json.loads, ) provider_state = store.export_provider_state(session) - await MemoryContextProvider(store=store).save_messages( + await MemoryContextProvider(store=store).save_messages( # ty: ignore[deprecated] session.session_id, [ Message(role="user", contents=["First question"]), @@ -693,12 +744,12 @@ async def test_memory_context_provider_recent_turns_can_skip_tool_call_groups(tm ) with_tools_agent = Agent( client=_MemoryHarnessClient(), # type: ignore[arg-type] # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type] - context_providers=[MemoryContextProvider(store=store, recent_turns=2, load_tool_turns=True)], + context_providers=[MemoryContextProvider(store=store, recent_turns=2, load_tool_turns=True)], # ty: ignore[deprecated] default_options=_no_store_options(), ) without_tools_agent = Agent( client=_MemoryHarnessClient(), # type: ignore[arg-type] # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type] - context_providers=[MemoryContextProvider(store=store, recent_turns=2, load_tool_turns=False)], + context_providers=[MemoryContextProvider(store=store, recent_turns=2, load_tool_turns=False)], # ty: ignore[deprecated] default_options=_no_store_options(), ) @@ -743,7 +794,7 @@ async def test_memory_context_provider_marks_cross_session_origins(tmp_path) -> """ session = AgentSession(session_id="session-current") session.state["owner_id"] = "alice" - store = MemoryFileStore( + store = MemoryFileStore( # ty: ignore[deprecated] tmp_path, owner_state_key="owner_id", dumps=lambda value: json.dumps(value, separators=(",", ":"), sort_keys=True), @@ -752,7 +803,7 @@ async def test_memory_context_provider_marks_cross_session_origins(tmp_path) -> updated_at = datetime(2026, 4, 21, tzinfo=timezone.utc).replace(microsecond=0).isoformat() store.write_topic( session, - MemoryTopicRecord( + MemoryTopicRecord( # ty: ignore[deprecated] topic="travel preferences", summary="Loves Oslo trips.", memories=["Prefers Oslo in summer."], @@ -764,7 +815,7 @@ async def test_memory_context_provider_marks_cross_session_origins(tmp_path) -> agent = Agent( client=_MemoryHarnessClient(), # type: ignore[arg-type] # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type] - context_providers=[MemoryContextProvider(store=store)], + context_providers=[MemoryContextProvider(store=store)], # ty: ignore[deprecated] default_options=_no_store_options(), ) @@ -785,7 +836,7 @@ async def test_memory_context_provider_omits_origin_when_only_current_session(tm """When all contributing topics are from the current session, attribution must NOT advertise an origin.""" session = AgentSession(session_id="session-current") session.state["owner_id"] = "alice" - store = MemoryFileStore( + store = MemoryFileStore( # ty: ignore[deprecated] tmp_path, owner_state_key="owner_id", dumps=lambda value: json.dumps(value, separators=(",", ":"), sort_keys=True), @@ -794,7 +845,7 @@ async def test_memory_context_provider_omits_origin_when_only_current_session(tm updated_at = datetime(2026, 4, 21, tzinfo=timezone.utc).replace(microsecond=0).isoformat() store.write_topic( session, - MemoryTopicRecord( + MemoryTopicRecord( # ty: ignore[deprecated] topic="travel preferences", summary="Loves Oslo trips.", memories=["Prefers Oslo in summer."], @@ -806,7 +857,7 @@ async def test_memory_context_provider_omits_origin_when_only_current_session(tm agent = Agent( client=_MemoryHarnessClient(), # type: ignore[arg-type] # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type] - context_providers=[MemoryContextProvider(store=store)], + context_providers=[MemoryContextProvider(store=store)], # ty: ignore[deprecated] default_options=_no_store_options(), ) @@ -827,7 +878,7 @@ async def test_memory_context_provider_uses_explicit_consolidation_client(tmp_pa """The memory provider should use the explicit consolidation client when one is configured.""" session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" - store = MemoryFileStore( + store = MemoryFileStore( # ty: ignore[deprecated] tmp_path, kind="memories", owner_prefix="user_", @@ -842,7 +893,7 @@ async def test_memory_context_provider_uses_explicit_consolidation_client(tmp_pa "memories": ["Visit Oslo in June."], } ) - provider = MemoryContextProvider( + provider = MemoryContextProvider( # ty: ignore[deprecated] store=store, consolidation_client=consolidation_client, # type: ignore[arg-type] # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type] ) @@ -875,8 +926,8 @@ async def test_memory_context_provider_preserves_concurrent_writes_to_same_topic """Concurrent writes to one topic should preserve every memory line.""" session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") - provider = MemoryContextProvider(store=store) + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] + provider = MemoryContextProvider(store=store) # ty: ignore[deprecated] agent = Agent(client=_MemoryHarnessClient(), context_providers=[provider], default_options=_no_store_options()) # type: ignore[arg-type] # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type] _, options = await agent._prepare_session_and_messages( # pyright: ignore[reportPrivateUsage] @@ -930,14 +981,14 @@ async def get_response(self, messages: Sequence[Message], **kwargs: object) -> C return ChatResponse(messages=[Message(role="assistant", contents=["Assistant reply."])]) -def _gated_consolidation_setup(tmp_path: Path, client: _GatedMemoryClient) -> tuple[MemoryFileStore, Agent]: +def _gated_consolidation_setup(tmp_path: Path, client: _GatedMemoryClient) -> tuple[MemoryFileStore, Agent]: # ty: ignore[deprecated] """Seed an Old topic and one pending session so the next finished session triggers consolidation.""" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") - provider = MemoryContextProvider(store=store, consolidation_min_sessions=2, consolidation_interval=timedelta(0)) + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] + provider = MemoryContextProvider(store=store, consolidation_min_sessions=2, consolidation_interval=timedelta(0)) # ty: ignore[deprecated] seed_session = _owned_session("session-a") store.write_topic( seed_session, - MemoryTopicRecord( + MemoryTopicRecord( # ty: ignore[deprecated] topic="Old", summary="Old summary.", memories=["Old fact"], @@ -961,7 +1012,7 @@ def _owned_session(session_id: str) -> AgentSession: return session -def _pending_sessions(store: MemoryFileStore) -> list[str]: +def _pending_sessions(store: MemoryFileStore) -> list[str]: # ty: ignore[deprecated] pending: list[str] = store.read_state(_owned_session("reader"), source_id=DEFAULT_MEMORY_SOURCE_ID)[ "sessions_since_consolidation" ] @@ -1064,12 +1115,12 @@ async def test_automatic_consolidation_keeps_overlapping_turn_of_covered_session topic and register itself while a pass that snapshotted ``session-1`` as pending is still running. """ client = _OrderedConsolidationClient(extraction_marker="Later turn") - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") - provider = MemoryContextProvider(store=store, consolidation_min_sessions=2, consolidation_interval=timedelta(0)) + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] + provider = MemoryContextProvider(store=store, consolidation_min_sessions=2, consolidation_interval=timedelta(0)) # ty: ignore[deprecated] seed_session = _owned_session("session-a") store.write_topic( seed_session, - MemoryTopicRecord( + MemoryTopicRecord( # ty: ignore[deprecated] topic="Old", summary="Old summary.", memories=["Old fact"], @@ -1114,7 +1165,7 @@ class _RegisteringConsolidationClient: additional_properties: dict[str, Any] - def __init__(self, store: MemoryFileStore, session: AgentSession, session_id: str) -> None: + def __init__(self, store: MemoryFileStore, session: AgentSession, session_id: str) -> None: # ty: ignore[deprecated] self.additional_properties = {} self.store = store self.session = session @@ -1145,9 +1196,9 @@ async def test_memory_consolidation_retires_only_turns_in_its_snapshot(tmp_path: ``session-a`` is pending without a turn id, like state written before turn ids were recorded. """ session = _owned_session("session-2") - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] client = _RegisteringConsolidationClient(store, session, later_session_id) - provider = MemoryContextProvider(store=store, consolidation_min_sessions=2, consolidation_interval=timedelta(0)) + provider = MemoryContextProvider(store=store, consolidation_min_sessions=2, consolidation_interval=timedelta(0)) # ty: ignore[deprecated] store.write_state( session, { @@ -1159,7 +1210,7 @@ async def test_memory_consolidation_retires_only_turns_in_its_snapshot(tmp_path: ) store.write_topic( session, - MemoryTopicRecord( + MemoryTopicRecord( # ty: ignore[deprecated] topic="Old", summary="Old summary.", memories=["Old fact"], @@ -1184,32 +1235,35 @@ async def test_memory_consolidation_retires_only_turns_in_its_snapshot(tmp_path: } -class _LegacyStateMemoryStore(MemoryFileStore): - """Custom store that persists only the maintenance fields that existed before ``pending_turn_ids``.""" +with warnings.catch_warnings(): + warnings.filterwarnings("ignore", message=r"MemoryFileStore is deprecated\.", category=DeprecationWarning) - def __init__(self, base_path: Path, *, state: dict[str, Any]) -> None: - super().__init__(base_path, owner_state_key="owner_id") - self.state = state + class _LegacyStateMemoryStore(MemoryFileStore): # ty: ignore[deprecated] + """Custom store that persists only the maintenance fields that existed before ``pending_turn_ids``.""" - def read_state(self, session: AgentSession, *, source_id: str) -> dict[str, Any]: - del session, source_id - return { - "last_consolidated_at": self.state["last_consolidated_at"], - "sessions_since_consolidation": list(self.state["sessions_since_consolidation"]), - } + def __init__(self, base_path: Path, *, state: dict[str, Any]) -> None: + super().__init__(base_path, owner_state_key="owner_id") + self.state = state - def write_state(self, session: AgentSession, state: Mapping[str, Any], *, source_id: str) -> None: - del session, source_id - self.state = { - "last_consolidated_at": state["last_consolidated_at"], - "sessions_since_consolidation": list(state["sessions_since_consolidation"]), - } + def read_state(self, session: AgentSession, *, source_id: str) -> dict[str, Any]: + del session, source_id + return { + "last_consolidated_at": self.state["last_consolidated_at"], + "sessions_since_consolidation": list(self.state["sessions_since_consolidation"]), + } + + def write_state(self, session: AgentSession, state: Mapping[str, Any], *, source_id: str) -> None: + del session, source_id + self.state = { + "last_consolidated_at": state["last_consolidated_at"], + "sessions_since_consolidation": list(state["sessions_since_consolidation"]), + } async def test_memory_provider_accepts_custom_store_state_without_turn_ids(tmp_path: Path) -> None: """A custom store returning state without ``pending_turn_ids`` still registers finished turns.""" store = _LegacyStateMemoryStore(tmp_path, state={"last_consolidated_at": None, "sessions_since_consolidation": []}) - provider = MemoryContextProvider(store=store, consolidation_min_sessions=10) + provider = MemoryContextProvider(store=store, consolidation_min_sessions=10) # ty: ignore[deprecated] client = _MemoryHarnessClient(extraction_payload={"memories": []}) agent = Agent(client=client, context_providers=[provider], default_options=_no_store_options()) # type: ignore[arg-type] # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type] @@ -1226,10 +1280,10 @@ async def test_memory_consolidation_accepts_custom_store_state_without_turn_ids( store = _LegacyStateMemoryStore( tmp_path, state={"last_consolidated_at": None, "sessions_since_consolidation": ["session-a", "session-b"]} ) - provider = MemoryContextProvider(store=store, consolidation_min_sessions=2, consolidation_interval=timedelta(0)) + provider = MemoryContextProvider(store=store, consolidation_min_sessions=2, consolidation_interval=timedelta(0)) # ty: ignore[deprecated] store.write_topic( session, - MemoryTopicRecord( + MemoryTopicRecord( # ty: ignore[deprecated] topic="Old", summary="Old summary.", memories=["Old fact"], @@ -1269,9 +1323,9 @@ async def get_response(self, messages: Sequence[Message], **kwargs: object) -> C return ChatResponse(messages=[Message(role="assistant", contents=["Assistant reply."])]) -def _two_topic_setup(tmp_path: Path) -> tuple[MemoryFileStore, MemoryContextProvider, Agent]: - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") - provider = MemoryContextProvider(store=store, consolidation_min_sessions=10) +def _two_topic_setup(tmp_path: Path) -> tuple[MemoryFileStore, MemoryContextProvider, Agent]: # ty: ignore[deprecated] + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] + provider = MemoryContextProvider(store=store, consolidation_min_sessions=10) # ty: ignore[deprecated] agent = Agent(client=_TwoTopicExtractionClient(), context_providers=[provider], default_options=_no_store_options()) # type: ignore[arg-type] # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type] return store, provider, agent @@ -1286,7 +1340,7 @@ async def test_memory_session_stays_pending_when_extraction_fails_after_a_topic_ original_write_topic = store.write_topic written_topics: list[str] = [] - def write_topic(session: AgentSession, record: MemoryTopicRecord, **kwargs: Any) -> None: + def write_topic(session: AgentSession, record: MemoryTopicRecord, **kwargs: Any) -> None: # ty: ignore[deprecated] if written_topics: raise OSError("disk full") written_topics.append(record.topic) @@ -1296,7 +1350,7 @@ def write_topic(session: AgentSession, record: MemoryTopicRecord, **kwargs: Any) else: original_rebuild_index = store.rebuild_index - def rebuild_index(session: AgentSession, **kwargs: Any) -> list[MemoryIndexEntry]: + def rebuild_index(session: AgentSession, **kwargs: Any) -> list[MemoryIndexEntry]: # ty: ignore[deprecated] # ``before_run`` also rebuilds the index; fail only the rebuild after extraction wrote topics. if store.list_topics(session, source_id=DEFAULT_MEMORY_SOURCE_ID): raise OSError("disk full") @@ -1320,7 +1374,7 @@ async def test_memory_session_stays_pending_when_extraction_is_cancelled_after_a original_merge_memory = provider._merge_memory # pyright: ignore[reportPrivateUsage] second_merge_started = asyncio.Event() - async def merge_memory(**kwargs: Any) -> MemoryTopicRecord: + async def merge_memory(**kwargs: Any) -> MemoryTopicRecord: # ty: ignore[deprecated] if kwargs["topic"] == "Second": second_merge_started.set() await asyncio.Event().wait() @@ -1342,17 +1396,17 @@ async def merge_memory(**kwargs: Any) -> MemoryTopicRecord: def test_memory_harness_classes_are_marked_experimental() -> None: """Memory harness public classes should expose HARNESS experimental metadata.""" - assert MemoryIndexEntry.__feature_id__ == ExperimentalFeature.HARNESS.value # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] - assert MemoryTopicRecord.__feature_id__ == ExperimentalFeature.HARNESS.value # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] - assert MemoryStore.__feature_id__ == ExperimentalFeature.HARNESS.value # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] - assert MemoryFileStore.__feature_id__ == ExperimentalFeature.HARNESS.value # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] - assert MemoryContextProvider.__feature_id__ == ExperimentalFeature.HARNESS.value # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] - assert ".. warning:: Experimental" in MemoryContextProvider.__doc__ # type: ignore[operator] # pyrefly: ignore[not-iterable] # ty: ignore[unsupported-operator] + assert MemoryIndexEntry.__feature_id__ == ExperimentalFeature.HARNESS.value # type: ignore[attr-defined] # ty: ignore[unresolved-attribute, deprecated] + assert MemoryTopicRecord.__feature_id__ == ExperimentalFeature.HARNESS.value # type: ignore[attr-defined] # ty: ignore[unresolved-attribute, deprecated] + assert MemoryStore.__feature_id__ == ExperimentalFeature.HARNESS.value # type: ignore[attr-defined] # ty: ignore[unresolved-attribute, deprecated] + assert MemoryFileStore.__feature_id__ == ExperimentalFeature.HARNESS.value # type: ignore[attr-defined] # ty: ignore[unresolved-attribute, deprecated] + assert MemoryContextProvider.__feature_id__ == ExperimentalFeature.HARNESS.value # type: ignore[attr-defined] # ty: ignore[unresolved-attribute, deprecated] + assert ".. warning:: Experimental" in MemoryContextProvider.__doc__ # type: ignore[operator] # pyrefly: ignore[not-iterable] # ty: ignore[unsupported-operator, deprecated] def test_memory_topic_record_round_trips_when_text_contains_section_markers() -> None: """Embedded ``## Summary``/``## Memories`` markers must not be re-interpreted as headings.""" - record = MemoryTopicRecord( + record = MemoryTopicRecord( # ty: ignore[deprecated] topic="weird", summary="Multi line summary.\n## Summary\nstill summary", memories=[ @@ -1364,7 +1418,7 @@ def test_memory_topic_record_round_trips_when_text_contains_section_markers() -> session_ids=["session-1"], ) - reparsed = MemoryTopicRecord.from_markdown(record.to_markdown()) + reparsed = MemoryTopicRecord.from_markdown(record.to_markdown()) # ty: ignore[deprecated] assert reparsed.summary == record.summary assert reparsed.memories == record.memories @@ -1372,10 +1426,10 @@ def test_memory_topic_record_round_trips_when_text_contains_section_markers() -> async def test_memory_file_store_atomic_write_preserves_prior_topic_on_failure(tmp_path, monkeypatch) -> None: """If ``os.replace`` fails mid-write, the previous topic file must remain intact.""" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" - original = MemoryTopicRecord( + original = MemoryTopicRecord( # ty: ignore[deprecated] topic="preferences", summary="Prefers concise answers.", memories=["Prefers concise answers."], @@ -1393,7 +1447,7 @@ def _boom(*args: object, **kwargs: object) -> None: with pytest.raises(OSError, match="simulated disk-full"): store.write_topic( session, - MemoryTopicRecord( + MemoryTopicRecord( # ty: ignore[deprecated] topic="preferences", summary="Updated.", memories=["Updated."], @@ -1415,7 +1469,7 @@ def _boom(*args: object, **kwargs: object) -> None: async def test_memory_file_store_does_not_mkdir_on_pure_read_paths(tmp_path) -> None: """List/read calls on a never-written session should not create any directories.""" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" @@ -1477,9 +1531,9 @@ async def test_memory_consolidation_transient_failure_preserves_state(tmp_path) """A transient consolidation failure must not advance the maintenance window.""" session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] raising_client = _RaisingMemoryClient() - provider = MemoryContextProvider(store=store, consolidation_client=raising_client) # type: ignore[arg-type] # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type] + provider = MemoryContextProvider(store=store, consolidation_client=raising_client) # type: ignore[arg-type] # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type, deprecated] pre_state = { "last_consolidated_at": "2026-04-20T09:00:00+00:00", "sessions_since_consolidation": ["queued-session"], @@ -1488,7 +1542,7 @@ async def test_memory_consolidation_transient_failure_preserves_state(tmp_path) store.write_state(session, pre_state, source_id=DEFAULT_MEMORY_SOURCE_ID) store.write_topic( session, - MemoryTopicRecord( + MemoryTopicRecord( # ty: ignore[deprecated] topic="preferences", summary="Prefers concise answers.", memories=["Prefers concise answers."], @@ -1516,8 +1570,8 @@ async def test_memory_extraction_propagates_programmer_errors(tmp_path) -> None: """Non-transient errors from the chat client must surface so misconfigurations fail loudly.""" session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") - provider = MemoryContextProvider(store=store) + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] + provider = MemoryContextProvider(store=store) # ty: ignore[deprecated] bad_client = _ProgrammerErrorMemoryClient() from agent_framework import AgentResponse @@ -1566,7 +1620,7 @@ def test_memory_file_store_derives_distinct_roots_for_colliding_owner_ids(tmp_pa same injectivity contract. Owner IDs that trip the independent traversal guard are rejected outright rather than merged. """ - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] roots: dict[str, Path] = {} rejected: set[str] = set() for owner_id in COLLIDING_IDENTIFIERS: @@ -1587,7 +1641,7 @@ def test_memory_file_store_derives_distinct_roots_for_colliding_owner_ids(tmp_pa def test_memory_file_store_encodes_non_ascii_owner_ids(tmp_path) -> None: """NFC and NFD spellings of one word must not share a directory.""" - store = MemoryFileStore(tmp_path, owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_state_key="owner_id") # ty: ignore[deprecated] roots: list[Path] = [] for owner_id in ("caf\u00e9", "cafe\u0301"): session = AgentSession(session_id="session-1") @@ -1601,7 +1655,7 @@ def test_memory_file_store_encodes_non_ascii_owner_ids(tmp_path) -> None: def test_memory_file_store_uses_literal_folders_for_safe_identifiers(tmp_path) -> None: """Safe identifiers are readable on disk rather than opaque encoded segments.""" - store = MemoryFileStore(tmp_path, owner_prefix="user_", owner_state_key="owner_id") + store = MemoryFileStore(tmp_path, owner_prefix="user_", owner_state_key="owner_id") # ty: ignore[deprecated] session = AgentSession(session_id="session-1") session.state["owner_id"] = "alice" diff --git a/python/packages/core/tests/core/test_root_exports.py b/python/packages/core/tests/core/test_root_exports.py index 8b629f68b51..eda5ca6e737 100644 --- a/python/packages/core/tests/core/test_root_exports.py +++ b/python/packages/core/tests/core/test_root_exports.py @@ -3,6 +3,8 @@ from __future__ import annotations import ast +import subprocess +import sys from pathlib import Path import agent_framework @@ -42,3 +44,12 @@ def test_root_from_import_representative_symbols() -> None: assert tool is agent_framework.tool assert FileStoreEntry is agent_framework.FileStoreEntry assert SkillsSourceContext is agent_framework.SkillsSourceContext + + +def test_memory_exports_do_not_warn_on_import() -> None: + code = """ +import warnings +warnings.filterwarnings("error", message=r"Memory.* is deprecated", category=DeprecationWarning) +from agent_framework import MemoryContextProvider, MemoryFileStore, MemoryIndexEntry, MemoryStore, MemoryTopicRecord +""" + subprocess.run([sys.executable, "-c", code], check=True)