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): avoid nesting rendered links (#3085)
AITree69a1792de59e14
diff --git a/openviking/session/memory/utils/link_renderer.py b/openviking/session/memory/utils/link_renderer.pyindex 55d2a0d01..86ca42638 100644--- a/openviking/session/memory/utils/link_renderer.py+++ b/openviking/session/memory/utils/link_renderer.py@@ -7,7 +7,11 @@ from openviking.core.namespace import uri_partsclass LinkRenderer:"""Renders and strips local markdown links in memory file content based on StoredLink metadata."""- _RELATIVE_LINK_RE = re.compile(r"\[(?P<text>[^\]]+)\]\((?P<target>[^)\s]+)\)")+ # Target may contain spaces (e.g. `[Frank Ocean](entities/frank ocean.md)`).+ # Markdown permits literal spaces in destinations, though they are not portable+ # across renderers; `render_links` therefore percent-encodes spaces in generated+ # targets so they round-trip cleanly. We accept both forms when matching.+ _RELATIVE_LINK_RE = re.compile(r"\[(?P<text>[^\]]+)\]\((?P<target>[^)]+)\)")_MEMORY_FIELDS_RE = re.compile(r"(\n\n<!--\s*MEMORY_FIELDS\s*\n)", re.DOTALL)_CJK_RE = re.compile(r"[㐀-䶿一-鿿豈-]")_ASCII_WORD_CHAR_RE = re.compile(r"[A-Za-z0-9_]")@@ -23,15 +27,29 @@ class LinkRenderer:@staticmethoddef _find_match_span(content: str, match_text: str) -> Optional[tuple[int, int]]:escaped = re.escape(match_text)+ # Character spans already covered by an existing [text](target) link. A match+ # inside one is already linked, so wrapping it again would produce a broken+ # nested link like "[[Frank](..) Ocean](..)"; skip those candidates.+ linked_spans = [+ (m.start(), m.end()) for m in LinkRenderer._RELATIVE_LINK_RE.finditer(content)+ ]++ def _inside_existing_link(start: int, end: int) -> bool:+ return any(ls <= start and end <= le for ls, le in linked_spans)+if LinkRenderer._contains_cjk(match_text):- match = re.search(escaped, content)- if not match:- return None- return match.start(), match.end()+ for match in re.finditer(escaped, content):+ start, end = match.start(), match.end()+ if _inside_existing_link(start, end):+ continue+ return start, end+ return Nonepattern = re.compile(escaped, re.IGNORECASE)for match in pattern.finditer(content):start, end = match.start(), match.end()+ if _inside_existing_link(start, end):+ continueleft_char = content[start - 1] if start > 0 else ""right_char = content[end] if end < len(content) else ""if LinkRenderer._is_ascii_word_char(left_char) or LinkRenderer._is_ascii_word_char(@@ -76,7 +94,13 @@ class LinkRenderer:if any(not (end <= rs or start >= re_) for rs, re_, _ in replacements):continue- rendered = f"[{content[start:end]}]({link_target})"+ # Percent-encode spaces in the rendered target so the link is portable+ # across markdown renderers (e.g. `[Frank](entities/frank ocean.md)`+ # would otherwise be ambiguous). We accept the literal-space form when+ # matching existing links, but always emit the encoded form when+ # generating new ones.+ encoded_target = link_target.replace(" ", "%20")+ rendered = f"[{content[start:end]}]({encoded_target})"replacements.append((start, end, rendered))# Apply in reverse order to preserve indicesdiff --git a/tests/test_link_renderer.py b/tests/test_link_renderer.pyindex 429a25438..c924197fc 100644--- a/tests/test_link_renderer.py+++ b/tests/test_link_renderer.py@@ -292,6 +292,105 @@ class TestRenderLinks:)assert result == "她喜欢[角色扮演游戏](entities/games/rpg.md),也喜欢开放世界游戏。"+ def test_skip_match_inside_existing_link(self):+ content = "Worked with [Frank Ocean](../../../../entities/personal/frank.md)."+ links = [+ {+ "from_uri": "viking://user/Calvin/memories/profile.md",+ "to_uri": "viking://user/Calvin/memories/entities/personal/frank.md",+ "weight": 1.0,+ "match_text": "Frank",+ }+ ]+ result = LinkRenderer.render_links(+ content,+ "viking://user/Calvin/memories/profile.md",+ links,+ )+ assert result == content++ def test_skip_match_inside_existing_link_with_space_in_target(self):+ # Reviewer feedback: existing links with literal spaces in their target+ # (e.g. `[Frank Ocean](entities/frank ocean.md)`) must still be detected+ # as an existing link span so the match inside is not double-wrapped.+ content = "Worked with [Frank Ocean](entities/frank ocean.md)."+ links = [+ {+ "from_uri": "viking://user/Calvin/memories/profile.md",+ "to_uri": "viking://user/Calvin/memories/entities/personal/frank ocean.md",+ "weight": 1.0,+ "match_text": "Frank",+ }+ ]+ result = LinkRenderer.render_links(+ content,+ "viking://user/Calvin/memories/profile.md",+ links,+ )+ assert result == content++ def test_render_link_with_space_in_target_is_percent_encoded(self):+ # Generated links should escape spaces in their target so the markdown+ # link is portable across renderers. We always emit `%20`, while still+ # accepting the literal-space form when matching existing links.+ content = "Saw Frank Ocean last night."+ links = [+ {+ "from_uri": "viking://user/Calvin/memories/events/2023/08/22/collab.md",+ "to_uri": "viking://user/Calvin/memories/entities/personal/frank ocean.md",+ "weight": 1.0,+ "match_text": "Frank Ocean",+ }+ ]+ result = LinkRenderer.render_links(+ content,+ "viking://user/Calvin/memories/events/2023/08/22/collab.md",+ links,+ )+ assert (+ result+ == "Saw [Frank Ocean](../../../../entities/personal/frank%20ocean.md) last night."+ )++ def test_render_link_with_percent_encoded_target_does_not_double_wrap(self):+ # An existing link with a `%20`-encoded target is also recognized as an+ # existing link span (since the regex matches any non-`)` chars).+ content = "Worked with [Frank Ocean](entities/frank%20ocean.md)."+ links = [+ {+ "from_uri": "viking://user/Calvin/memories/profile.md",+ "to_uri": "viking://user/Calvin/memories/entities/personal/frank ocean.md",+ "weight": 1.0,+ "match_text": "Frank",+ }+ ]+ result = LinkRenderer.render_links(+ content,+ "viking://user/Calvin/memories/profile.md",+ links,+ )+ assert result == content++ def test_use_later_unlinked_match_when_first_match_is_already_linked(self):+ content = "[Frank Ocean](../../../../entities/personal/frank.md) performed. Frank stayed."+ links = [+ {+ "from_uri": "viking://user/Calvin/memories/profile.md",+ "to_uri": "viking://user/Calvin/memories/entities/personal/frank.md",+ "weight": 1.0,+ "match_text": "Frank",+ }+ ]+ result = LinkRenderer.render_links(+ content,+ "viking://user/Calvin/memories/profile.md",+ links,+ )+ assert (+ result == "[Frank Ocean](../../../../entities/personal/frank.md) performed. "+ "[Frank](entities/personal/frank.md) stayed."+ )+class TestStripLinks:def test_strip_relative_link(self):@@ -299,6 +398,16 @@ class TestStripLinks:result = LinkRenderer.strip_links(content)assert result == "See support for details."+ def test_strip_relative_link_with_space_in_target(self):+ content = "See [Frank Ocean](entities/frank ocean.md) for details."+ result = LinkRenderer.strip_links(content)+ assert result == "See Frank Ocean for details."++ def test_strip_relative_link_with_percent_encoded_target(self):+ content = "See [Frank Ocean](entities/frank%20ocean.md) for details."+ result = LinkRenderer.strip_links(content)+ assert result == "See Frank Ocean for details."+def test_keep_absolute_link(self):content = "Visit [docs](https://example.com/docs) for more."result = LinkRenderer.strip_links(content)@@ -388,6 +497,52 @@ class TestRoundTrip:stripped = LinkRenderer.strip_links(rendered)assert stripped == original+ def test_render_then_strip_with_space_in_target(self):+ # End-to-end round-trip: a generated link whose target has spaces+ # (encoded as `%20`) should still strip back to the original text.+ original = "Saw Frank Ocean last night."+ links = [+ {+ "from_uri": "viking://user/Calvin/memories/events/2023/08/22/collab.md",+ "to_uri": "viking://user/Calvin/memories/entities/personal/frank ocean.md",+ "weight": 1.0,+ "match_text": "Frank Ocean",+ }+ ]+ rendered = LinkRenderer.render_links(+ original,+ "viking://user/Calvin/memories/events/2023/08/22/collab.md",+ links,+ )+ stripped = LinkRenderer.strip_links(rendered)+ assert stripped == original++ def test_render_twice_with_space_in_target_does_not_nest(self):+ # Repeated render calls must be idempotent even when an existing link+ # already uses a literal-space target. Without the regex fix, the+ # second render would re-wrap the inner match_text.+ original = "Worked with [Frank Ocean](entities/frank ocean.md)."+ links = [+ {+ "from_uri": "viking://user/Calvin/memories/profile.md",+ "to_uri": "viking://user/Calvin/memories/entities/personal/frank ocean.md",+ "weight": 1.0,+ "match_text": "Frank",+ }+ ]+ first = LinkRenderer.render_links(+ original,+ "viking://user/Calvin/memories/profile.md",+ links,+ )+ second = LinkRenderer.render_links(+ first,+ "viking://user/Calvin/memories/profile.md",+ links,+ )+ assert first == original+ assert second == original+def test_memory_file_plain_content_strips_markdown_links(self):memory_file = MemoryFile(uri="viking://user/Calvin/memories/events/2023/08/22/collab_with_frank_ocean.md",