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): reject ambiguous search replacements (#3386)
teacup80d63f508d82
diff --git a/openviking/session/memory/extract_loop.py b/openviking/session/memory/extract_loop.pyindex 27c57f971..e4c08ec11 100644--- a/openviking/session/memory/extract_loop.py+++ b/openviking/session/memory/extract_loop.py@@ -922,6 +922,8 @@ The final output of the model must strictly follow the JSON Schema format shownreturn ("SEARCH/REPLACE patch could not be applied to the target memory file. ""The SEARCH text must be copied exactly from the read result of the file bound to that operation's page_id. "+ "The SEARCH text must occur exactly once in the target file. "+ "If it occurs more than once, include enough contiguous surrounding context to make the SEARCH text unique. ""Do not use SEARCH text from the conversation or from another page. ""If you copy from numbered read output, exclude the `line_number<TAB>` prefix from SEARCH and REPLACE text. ""If found_in_other_uris is non-empty, diagnose this as a possible page_id mismatch and choose the correct target page_id or rewrite the patch for the current page_id; do not silently move the patch. "diff --git a/openviking/session/memory/merge_op/patch.py b/openviking/session/memory/merge_op/patch.pyindex 06b46c95f..f10e808ba 100644--- a/openviking/session/memory/merge_op/patch.py+++ b/openviking/session/memory/merge_op/patch.py@@ -75,8 +75,8 @@ class PatchOp(MergeOpBase):# Case 2: dict form of StrPatch (from JSON parsing)if isinstance(patch_value, dict):- try:- if "blocks" in patch_value:+ if "blocks" in patch_value:+ try:blocks = []for block_dict in patch_value["blocks"]:if isinstance(block_dict, dict):@@ -85,13 +85,15 @@ class PatchOp(MergeOpBase):blocks.append(block_dict)# Filter out empty-search blocks when there's existing contentvalid_blocks = [b for b in blocks if b.search]- if valid_blocks:- return apply_str_patch(current_str, StrPatch(blocks=valid_blocks))- # All blocks have empty search → keep original- return current_value- except Exception:- # If conversion fails, treat as simple replacement- return str(patch_value) if patch_value is not None else ""+ converted_patch = StrPatch(blocks=valid_blocks) if valid_blocks else None+ except Exception:+ # If conversion fails, treat as simple replacement+ return str(patch_value) if patch_value is not None else ""++ if converted_patch is not None:+ return apply_str_patch(current_str, converted_patch)+ # All blocks have empty search → keep original+ return current_value# Case 3: Simple full replacement# 空字符串和 None 都保持原值diff --git a/openviking/session/memory/merge_op/patch_handler.py b/openviking/session/memory/merge_op/patch_handler.pyindex 88b6ad04a..13bb4b97d 100644--- a/openviking/session/memory/merge_op/patch_handler.py+++ b/openviking/session/memory/merge_op/patch_handler.py@@ -880,7 +880,15 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:all_applied = Falsebreak- result_content = result_content.replace(search_content, replace_content)+ match_count = result_content.count(search_content)+ if match_count > 1:+ raise PatchParseError(+ f"SEARCH content matched {match_count} locations; "+ "The re-generated SEARCH string may contain additional lines "+ "to make sure it is unique."+ )++ result_content = result_content.replace(search_content, replace_content, 1)if all_applied:return result_contentdiff --git a/tests/session/memory/test_compressor_v2.py b/tests/session/memory/test_compressor_v2.pyindex 68c6340e1..c17f0e9dd 100644--- a/tests/session/memory/test_compressor_v2.py+++ b/tests/session/memory/test_compressor_v2.py@@ -899,6 +899,8 @@ class TestExtractLoopPatchRepair:assert len(vlm.messages) == 2second_call_content = "\n".join(message["content"] for message in vlm.messages[1])assert "SEARCH/REPLACE patch could not be applied" in second_call_content+ assert "The SEARCH text must occur exactly once" in second_call_content+ assert "include enough contiguous surrounding context" in second_call_contentassert "Regenerate the complete operations JSON" in second_call_contentassert target_uri in second_call_contentassert other_uri in second_call_contentdiff --git a/tests/session/memory/test_merge_ops.py b/tests/session/memory/test_merge_ops.pyindex a74f9d44c..865b21b5d 100644--- a/tests/session/memory/test_merge_ops.py+++ b/tests/session/memory/test_merge_ops.py@@ -4,6 +4,8 @@Tests for MergeOp architecture - type-safe merge operations."""+import pytest+from openviking.session.memory.dataclass import (MemoryField,)@@ -12,6 +14,7 @@ from openviking.session.memory.merge_op import (MergeOp,MergeOpFactory,PatchOp,+ PatchParseError,SearchReplaceBlock,StrPatch,SumOp,@@ -81,6 +84,30 @@ class TestPatchOp:op_int = PatchOp(FieldType.INT64)assert op_int.apply(100, 200) == 200+ def test_apply_dict_patch(self):+ """Dict-form string patches should be converted and applied."""+ op = PatchOp(FieldType.STRING)+ patch = {"blocks": [{"search": "hello world", "replace": "hello there"}]}++ assert op.apply("hello world", patch) == "hello there"++ def test_apply_invalid_dict_patch_falls_back_to_string_replacement(self):+ """Invalid dict-form patches should preserve the compatibility fallback."""+ op = PatchOp(FieldType.STRING)+ patch = {"blocks": [{"search": "hello world"}]}++ assert op.apply("hello world", patch) == str(patch)++ def test_apply_dict_patch_propagates_patch_parse_error(self):+ """Patch errors raised after dict conversion must reach the caller."""+ op = PatchOp(FieldType.STRING)+ patch = {+ "blocks": [{"search": "status: pending", "replace": "status: done"}]+ }++ with pytest.raises(PatchParseError, match="matched 2 locations"):+ op.apply("status: pending\nstatus: pending", patch)+class TestSumOp:"""Tests for SumOp."""@@ -269,6 +296,32 @@ class TestApplyStrPatch:# Directly test apply_str_patchassert result == "hello there"+ def test_duplicate_search_is_rejected(self):+ """Ambiguous SEARCH content must fail instead of replacing globally."""+ original = "status: pending\nstatus: pending"+ patch = StrPatch(+ blocks=[SearchReplaceBlock(search="status: pending", replace="status: done")]+ )++ with pytest.raises(+ PatchParseError,+ match="additional lines to make sure it is unique",+ ):+ apply_str_patch(original, patch)++ def test_duplicate_search_after_prior_block_is_rejected(self):+ """A later ambiguous block must not return a partially applied patch."""+ original = "title\nstatus: pending\nstatus: pending"+ patch = StrPatch(+ blocks=[+ SearchReplaceBlock(search="title", replace="updated title"),+ SearchReplaceBlock(search="status: pending", replace="status: done"),+ ]+ )++ with pytest.raises(PatchParseError, match="matched 2 locations"):+ apply_str_patch(original, patch)+def test_numbered_multiline_patch_uses_inferred_start_line(self):"""Tab-prefixed read output should target the numbered range."""original = "keep\nsame\nkeep\nsame"