Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(memory): keep dynamic URI values in one path segment (#4587)
Jiajie - He/him/hisda2aaa0ed00a
diff --git a/openviking/session/memory/utils/uri.py b/openviking/session/memory/utils/uri.pyindex 947c64743..70e0faf39 100644--- a/openviking/session/memory/utils/uri.py+++ b/openviking/session/memory/utils/uri.py@@ -17,6 +17,7 @@ from openviking.session.memory.utils.template_utils import TemplateUtils_PORTABLE_SEGMENT_MARKER = "~ov~"_PORTABLE_SEGMENT_HASH_LENGTH = 16_WINDOWS_INVALID_CHARS = frozenset('<>:"\\|?*')+_TRUSTED_PATH_SEGMENT_TEMPLATE = re.compile(r"^\{\{\s*user_space\s*\}\}$")_WINDOWS_RESERVED_STEMS = frozenset({"CON",@@ -100,23 +101,42 @@ def _portable_uri_segment(segment: str) -> str:return f"{stem}{suffix}{extension}"-def _make_uri_path_segments_portable(uri: str) -> str:- """Make every rendered memory URI segment portable on supported filesystems.+def _render_portable_uri_template(+ template: str,+ context: Dict[str, Any],+ extract_context: Any,+) -> str:+ """Render template-defined path segments without treating field data as hierarchy.- Clean segments remain byte-identical. A non-portable segment keeps a readable- safe prefix and receives a deterministic digest of its original value, so- values such as ``Desktop``, ``Desktop ``, and ``Desktop.`` stay distinct.+ ``user_space`` is an internal path fragment that may contain the explicit+ ``peers/<peer_id>`` namespace. Other expressions render into exactly one path+ segment. A slash in dynamic data aliases an underscore because both spellings+ identify the same memory name."""scheme_separator = "://"- if scheme_separator in uri:- scheme, _, path = uri.partition(scheme_separator)+ if scheme_separator in template:+ scheme, _, path_template = template.partition(scheme_separator)prefix = f"{scheme}{scheme_separator}"else:- prefix, path = "", uri-- if not path:- return uri- return prefix + "/".join(_portable_uri_segment(segment) for segment in path.split("/"))+ prefix, path_template = "", template++ if not path_template:+ return prefix++ segments = []+ for segment_template in path_template.split("/"):+ rendered = TemplateUtils.render(+ segment_template,+ context,+ extract_context=extract_context,+ debug_undefined=True,+ strip=False,+ )+ if _TRUSTED_PATH_SEGMENT_TEMPLATE.fullmatch(segment_template):+ segments.extend(rendered.split("/"))+ else:+ segments.append(rendered.replace("/", "_"))+ return prefix + "/".join(_portable_uri_segment(segment) for segment in segments)def render_template(@@ -175,18 +195,15 @@ def generate_uri(uri_template = f"{dir_template.rstrip('/')}/{filename_template.lstrip('/')}"else:uri_template = dir_template or filename_template- context = {"user_space": user_space}- # Add all fields to context (uri_fields with actual values)- context.update(fields)+ context = dict(fields)+ context["user_space"] = user_spacetemplate_vars = set(re.findall(r"\{\{\s*(\w+)\s*\}\}", uri_template))for var in template_vars:if var not in context:raise ValueError(f"Missing template variable: {var}")if context[var] is None:raise ValueError(f"Template variable '{var}' has None value")- # Render using unified render_template method (same as content_template)- uri = render_template(uri_template, context, extract_context)- return _make_uri_path_segments_portable(uri)+ return _render_portable_uri_template(uri_template, context, extract_context)def validate_uri_template(memory_type: MemoryTypeSchema) -> bool:diff --git a/tests/session/memory/test_memory_utils.py b/tests/session/memory/test_memory_utils.pyindex dcd3cce60..693691afe 100644--- a/tests/session/memory/test_memory_utils.py+++ b/tests/session/memory/test_memory_utils.py@@ -140,30 +140,22 @@ class TestUriGeneration:with pytest.raises(ValueError, match="has None value"):generate_uri(memory_type, {"topic": None})- def test_generate_uri_makes_windows_unsafe_directory_segment_collision_resistant(self):- """The exact #4308 shape is portable without changing the LLM field."""+ def test_generate_uri_normalizes_dynamic_slash_without_new_hierarchy(self):memory_type = MemoryTypeSchema(memory_type="events",- description="Event memory",directory="viking://user/{{ user_space }}/memories/events",filename_template="2026/07/30/{{ event_name }}.md",- fields=[- MemoryField(- name="event_name",- field_type=FieldType.STRING,- merge_op=MergeOp.IMMUTABLE,- )- ],)- fields = {"event_name": "Desktop /new report"}+ fields = {"event_name": "alpha/beta"}uri = generate_uri(memory_type, fields, user_space="default")- assert uri == (- "viking://user/default/memories/events/2026/07/30/"- "Desktop~ov~02970756851a43cf/new report.md"+ assert (+ uri+ == generate_uri(memory_type, {"event_name": "alpha_beta"}, user_space="default")+ == "viking://user/default/memories/events/2026/07/30/alpha_beta.md")- assert fields == {"event_name": "Desktop /new report"}+ assert fields == {"event_name": "alpha/beta"}def test_generate_uri_keeps_colliding_windows_names_distinct(self):memory_type = MemoryTypeSchema(diff --git a/tests/session/memory/test_streaming_memory_updater.py b/tests/session/memory/test_streaming_memory_updater.pyindex 43d18cdf6..8750206bc 100644--- a/tests/session/memory/test_streaming_memory_updater.py+++ b/tests/session/memory/test_streaming_memory_updater.py@@ -987,9 +987,7 @@ def test_enforce_merge_group_reapplies_portable_uri_without_changing_memory_name)assert op.memory_fields["note_name"] == "Desktop /new"- assert op.uris == [- "viking://user/u/peers/conv-42/memories/notes/Desktop~ov~02970756851a43cf/new.md"- ]+ assert op.uris == ["viking://user/u/peers/conv-42/memories/notes/Desktop _new.md"]def test_enforce_merge_group_self_scope_removes_peer_id():