DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(memory): make write_memory preference add idempotent (#647)
Bingxi Zhao (Frank)630041a1cda9
diff --git a/deeptutor/services/memory/store.py b/deeptutor/services/memory/store.pyindex 4696fc048..79ec2886f 100644--- a/deeptutor/services/memory/store.py+++ b/deeptutor/services/memory/store.py@@ -19,7 +19,7 @@ from typing import Literalfrom deeptutor.services.memory import consolidator, paths, tracefrom deeptutor.services.memory.consolidator import ConsolidateResult, OnEventfrom deeptutor.services.memory.document import Document, parse, serialize-from deeptutor.services.memory.ops import AddOp, ApplyReport, EditOp+from deeptutor.services.memory.ops import AddOp, ApplyReport, EditOp, OpResultfrom deeptutor.services.memory.ops import apply as ops_applyfrom deeptutor.services.memory.paths import L3Slot, Surfacefrom deeptutor.services.memory.trace import TraceEvent@@ -29,6 +29,25 @@ logger = logging.getLogger(__name__)Layer = Literal["L2", "L3"]_V1_FILES = ("PROFILE.md", "SUMMARY.md")+++def _normalize_pref_text(text: str) -> str:+ """Whitespace/case-insensitive key for duplicate-preference detection."""+ return " ".join(str(text or "").split()).casefold()+++def _find_duplicate_preference(doc: Document, section: str, text: str):+ """Return an existing entry in ``section`` whose text matches ``text``.++ Read-only — does not create the section if it is absent.+ """+ target = _normalize_pref_text(text)+ if not target:+ return None+ for entry in doc.all_entries():+ if entry.section == section and _normalize_pref_text(entry.text) == target:+ return entry+ return None_NO_MEMORY = ("(No memory available — interact with DeepTutor and update from the Memory page to build one.)")@@ -191,6 +210,26 @@ class MemoryStore:)section = "Preferences"if op == "add":+ # Idempotent add: preferences.md is never auto-consolidated+ # (see update_l3), so an identical bullet added again would+ # persist forever as a duplicate. Guided-learning turns are+ # highly tool-driven and long-running, so the model tends to+ # re-issue the same write_memory across turns (issue #647).+ # Short-circuit to a no-op that reports the existing entry as+ # already saved instead of appending a duplicate.+ duplicate = _find_duplicate_preference(doc, section, text)+ if duplicate is not None:+ return ApplyReport(+ accepted=True,+ results=[+ OpResult(+ op=AddOp(section=section, text=text, refs=[trace_id]),+ status="applied",+ entry_id=duplicate.id,+ detail="duplicate",+ )+ ],+ )report = ops_apply(doc,[AddOp(section=section, text=text, refs=[trace_id])],diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.pyindex 75423ba87..34d60d174 100644--- a/deeptutor/tools/builtin/__init__.py+++ b/deeptutor/tools/builtin/__init__.py@@ -746,10 +746,22 @@ class WriteMemoryTool(_PromptHintsMixin, BaseTool):success=False,metadata={"op": op},)- entry_id = report.results[0].entry_id if report.results else None+ result0 = report.results[0] if report.results else None+ entry_id = result0.entry_id if result0 else None+ deduplicated = bool(result0 and result0.detail == "duplicate")+ if deduplicated:+ # Give the model an explicit "already saved" signal so it stops+ # re-issuing the same write_memory in later turns (issue #647).+ content = f"preference already saved (entry={entry_id}); skipped duplicate."+ else:+ content = f"preference {op}ed (entry={entry_id or target_id})."return ToolResult(- content=f"preference {op}ed (entry={entry_id or target_id}).",- metadata={"op": op, "entry_id": entry_id or target_id},+ content=content,+ metadata={+ "op": op,+ "entry_id": entry_id or target_id,+ "deduplicated": deduplicated,+ },)diff --git a/tests/services/memory/test_store.py b/tests/services/memory/test_store.pyindex ae16396a9..dae848560 100644--- a/tests/services/memory/test_store.py+++ b/tests/services/memory/test_store.py@@ -95,6 +95,33 @@ def test_write_preference_add(tmp_memory: Path) -> None:assert doc.all_entries()[0].text == "prefers concise answers"+def test_write_preference_add_is_idempotent(tmp_memory: Path) -> None:+ # Issue #647: re-adding an identical preference (even with different case /+ # whitespace) must not create a duplicate record, since preferences.md is+ # never auto-consolidated.+ s = MemoryStore()+ first = _run(+ s.write_preference(+ op="add",+ text="prefers concise answers",+ trace_id="chat:01HZK4AAAAAAAAAAAAAAAAAAAA",+ )+ )+ first_id = first.results[0].entry_id+ second = _run(+ s.write_preference(+ op="add",+ text=" Prefers concise answers ",+ trace_id="chat:01HZK5BBBBBBBBBBBBBBBBBBBB",+ )+ )+ assert second.accepted+ assert second.results[0].detail == "duplicate"+ assert second.results[0].entry_id == first_id # points at the original+ doc = s.read_doc("L3", "preferences")+ assert len(doc.all_entries()) == 1 # no duplicate appended++def test_write_preference_edit(tmp_memory: Path) -> None:s = MemoryStore()add_report = _run(