Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(memory): preserve code fences in extraction content (#5852)

Lusen Dong4a2909b44f0b
diff --git a/openviking/session/memory/extraction_output_protocol/python_protocol.py b/openviking/session/memory/extraction_output_protocol/python_protocol.py
index 87b60ba2d..0b44a3dac 100644
--- a/openviking/session/memory/extraction_output_protocol/python_protocol.py
+++ b/openviking/session/memory/extraction_output_protocol/python_protocol.py
@@ -5,9 +5,11 @@
from __future__ import annotations
import ast
+import io
import json
import keyword
import re
+import tokenize
from dataclasses import dataclass, field
from typing import Any, get_args, get_origin
@@ -33,7 +35,7 @@ from openviking.session.memory.utils.line_numbers import (
strip_line_numbers,
)
-_PYTHON_FENCE_RE = re.compile(r"```python[ \t]*\r?\n(?P<code>[\s\S]*?)```", re.IGNORECASE)
+_PYTHON_FENCE_RE = re.compile(r"```python[ \t]*\r?\n(?P<code>[\s\S]*)```", re.IGNORECASE)
_PYTHON_FENCE_START_RE = re.compile(r"```python[ \t]*\r?\n", re.IGNORECASE)
_HIDDEN_MEMORY_FIELDS = {
"source_extraction_id",
@@ -1453,20 +1455,54 @@ class _PythonProgramCompiler:
def _extract_python_code(content: str) -> str:
stripped = str(content or "").strip()
- matches = list(_PYTHON_FENCE_RE.finditer(stripped))
- if len(matches) == 1:
- match = matches[0]
+ if "```" not in stripped:
+ return stripped
+ # A bare program may contain Markdown fences inside its string literals.
+ try:
+ ast.parse(stripped, mode="exec")
+ except SyntaxError:
+ pass
+ else:
+ return stripped
+ match = _PYTHON_FENCE_RE.search(stripped)
+ if match:
+ if _fence_is_python_content(stripped, match.start()):
+ return stripped
surrounding_text = stripped[: match.start()] + stripped[match.end() :]
if "```" not in surrounding_text:
- return match.group("code").rstrip()
+ code = match.group("code").rstrip()
+ if "```" not in code:
+ return code
+ # Match through content fences, but reject separate output blocks.
+ try:
+ ast.parse(code, mode="exec")
+ except SyntaxError:
+ pass
+ else:
+ return code
starts = list(_PYTHON_FENCE_START_RE.finditer(stripped))
if len(starts) == 1 and stripped.count("```") == 1:
return stripped[starts[0].end() :].strip()
- if "```" in stripped:
- raise ExtractionOutputProtocolError(
- "Python output may contain only one complete ```python code fence"
- )
- return stripped
+ raise ExtractionOutputProtocolError(
+ "Python output may contain only one complete ```python code fence"
+ )
+
+
+def _fence_is_python_content(source: str, offset: int) -> bool:
+ """Recognize a fence in a string/comment even when later Python is invalid."""
+ position = (source.count("\n", 0, offset) + 1, offset - source.rfind("\n", 0, offset) - 1)
+ try:
+ for token in tokenize.generate_tokens(io.StringIO(source).readline):
+ if token.start <= position < token.end:
+ # Standalone backticks are individual tokens; strings, f-string
+ # text and comments contain the marker within a larger token.
+ return token.string != "`"
+ if token.start > position:
+ break
+ except (tokenize.TokenError, SyntaxError):
+ # Surrounding explanation is not required to be valid Python.
+ pass
+ return False
def _is_string_literal_syntax_error(error: str) -> bool:
diff --git a/tests/session/memory/test_extraction_output_protocol.py b/tests/session/memory/test_extraction_output_protocol.py
index b3745f68d..95ddce247 100644
--- a/tests/session/memory/test_extraction_output_protocol.py
+++ b/tests/session/memory/test_extraction_output_protocol.py
@@ -782,6 +782,24 @@ def test_python_syntax_error_includes_offending_source_line():
assert "^" in error
[email protected]("ending", ["sdk.commit(", "sdk.commit())"])
+ "wrapper", ["{}", "```python\n{}\n```", "Explanation\n```python\n{}\n```\nDone."]
+)
+def test_python_rejects_invalid_program_containing_fenced_example(ending, wrapper):
+ context = _context([_profile_schema()])
+ protocol = create_extraction_output_protocol("python")
+ program = (
+ 'sdk.set_profile(content="""Example:\n```python\nsdk.commit()\n```\n'
+ f'Keep this example.""")\n{ending}'
+ )
+
+ operations, error = protocol.parse(wrapper.format(program), context)
+
+ assert operations is None
+ assert error is not None
+
+
def test_memory_schema_identity_fields_follow_scope_and_uri_template():
entities = MemoryTypeSchema(
memory_type="entities",
@@ -829,17 +847,31 @@ def test_memory_schema_identity_fields_ignore_jinja_token_collisions():
assert events.identity_fields() == ("peer_id", "event_name", "ranges")
-def test_python_set_single_file_memory_compiles_to_same_operations_as_json():
+ "content",
+ [
+ "Engineer",
+ 'Config:\n```nginx\nadd_header Cache-Control "no-cache";\n```\nDone.',
+ "Example:\n```python\nsdk.commit()\n```\nKeep this example.",
+ "Use the literal ``` marker.",
+ "```text\nfirst\n```\n```python\nsdk.commit()\n```",
+ ],
+)
+ "wrapper",
+ ["{}", "```python\n{}\n```", "Explanation\n```python\n{}\n```\nDone."],
+)
+def test_python_set_single_file_memory_compiles_to_same_operations_as_json(content, wrapper):
context = _context([_profile_schema()])
python_protocol = create_extraction_output_protocol("python")
json_protocol = create_extraction_output_protocol("json")
python_operations, python_error = python_protocol.parse(
- "sdk.set_profile(content='Engineer')\nsdk.commit()",
+ wrapper.format(f'sdk.set_profile(content="""{content}""")\nsdk.commit()'),
context,
)
json_operations, json_error = json_protocol.parse(
- '{"profile":[{"page_id":100,"content":"Engineer"}],"delete_ids":[]}',
+ json.dumps({"profile": [{"page_id": 100, "content": content}], "delete_ids": []}),
context,
)