Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(memory): keep frontmatter when the closing fence ends the text (#3345)
Zhu Leif2bedf3e5e3b
diff --git a/src/agentscope/middleware/_longterm_memory/_agentic_memory/_middleware.py b/src/agentscope/middleware/_longterm_memory/_agentic_memory/_middleware.pyindex 814d6e85e..320bda688 100644--- a/src/agentscope/middleware/_longterm_memory/_agentic_memory/_middleware.py+++ b/src/agentscope/middleware/_longterm_memory/_agentic_memory/_middleware.py@@ -861,8 +861,11 @@ class AgenticMemoryMiddleware(MiddlewareBase):errors="replace",)+ # ``$`` covers a fence that ends the string. The discovery scan only+ # reads a byte-capped prefix, so the newline after ``---`` is often+ # outside that prefix; requiring it drops every field._FRONTMATTER_RE = re.compile(- r"^\s*---\s*\n(?P<body>.*?)\n---\s*\n",+ r"^\s*---\s*\n(?P<body>.*?)\n---\s*(?:\n|$)",re.DOTALL,)_FIELD_RE = re.compile(r"^(?P<key>\w+)\s*:\s*(?P<value>.+)$", re.MULTILINE)@@ -871,7 +874,8 @@ class AgenticMemoryMiddleware(MiddlewareBase):def _parse_frontmatter_fields(cls, content: str) -> dict[str, str]:"""Return a dict of YAML-like key/value pairs from the firstfrontmatter block. Only scalar ``key: value`` lines are parsed;- nested structures are intentionally ignored.+ nested structures are intentionally ignored. The closing fence+ may end the string.Args:content (`str`):diff --git a/tests/middleware_filesystem_memory_test.py b/tests/middleware_filesystem_memory_test.pyindex 892267277..8a9be6034 100644--- a/tests/middleware_filesystem_memory_test.py+++ b/tests/middleware_filesystem_memory_test.py@@ -5,6 +5,7 @@ import osimport shutilimport tempfilefrom typing import Any, Type+from unittest import TestCasefrom unittest.async_case import IsolatedAsyncioTestCasefrom pydantic import BaseModel@@ -825,3 +826,34 @@ class AgenticMemoryMiddlewareTest(IsolatedAsyncioTestCase):"structured_call_count": 0,},)+++class FrontmatterParseTest(TestCase):+ """Parsing of memory-file frontmatter."""++ def test_closing_fence_at_end_of_text_keeps_fields(self) -> None:+ """Keep fields when the closing fence is the last line.++ Discovery reads a byte-capped prefix, and that prefix often ends+ on the closing ``---``. A file can end there too. Both must still+ expose ``description`` and ``type``.+ """+ fields = {+ "name": "tea.md",+ "description": "User likes tea",+ "type": "user",+ }+ ending_on_fence = (+ "---\n"+ "name: tea.md\n"+ "description: User likes tea\n"+ "type: user\n"+ "---"+ )+ # pylint: disable-next=protected-access+ parse = AgenticMemoryMiddleware._parse_frontmatter_fields+ self.assertDictEqual(parse(ending_on_fence), fields)+ self.assertDictEqual(+ parse(ending_on_fence + "\n\nThey drink tea daily.\n"),+ fields,+ )