diff --git a/deeptutor/services/memory/document.py b/deeptutor/services/memory/document.py index e10b528f0..505f03742 100644 --- a/deeptutor/services/memory/document.py +++ b/deeptutor/services/memory/document.py @@ -38,6 +38,8 @@ from __future__ import annotations from dataclasses import dataclass, field import re +from deeptutor.services.memory.ids import new_entry_id + _ENTRY_ID_RE = r"m_[0-9A-HJKMNP-TV-Z]{26}" _TITLE_RE = re.compile(r"^#\s+(.+?)\s*$") @@ -236,4 +238,37 @@ def serialize(doc: Document) -> str: return "\n".join(lines).rstrip() + "\n" -__all__ = ["Document", "Entry", "parse", "serialize"] +# A bullet typed by hand in the workbench editor: no id anchor yet. +_UNANCHORED_BULLET_RE = re.compile(r"^\s*-\s+\S") + + +def anchor_new_entries(md: str) -> str: + """Give hand-written bullets an entry-id anchor so ``parse`` keeps them. + + ``parse`` only reads bullets that carry an id, and every write path + re-serializes the parsed document. A bullet saved from the editor without + an anchor would therefore vanish on the next write. Only bullets inside a + section are anchored; every other line is returned unchanged. + """ + out: list[str] = [] + title_seen = False + in_section = False + for raw in md.splitlines(keepends=True): + line = raw.rstrip("\r\n") + stripped = line.rstrip() + if not title_seen and _TITLE_RE.match(stripped): + title_seen = True + elif _SECTION_RE.match(stripped): + in_section = True + elif ( + in_section + and _UNANCHORED_BULLET_RE.match(stripped) + and not _NEW_BULLET_RE.match(stripped) + and not _OLD_BULLET_RE.match(stripped) + ): + raw = f"{stripped} {raw[len(line) :]}" + out.append(raw) + return "".join(out) + + +__all__ = ["Document", "Entry", "anchor_new_entries", "parse", "serialize"] diff --git a/deeptutor/services/memory/store.py b/deeptutor/services/memory/store.py index 65775a363..a82a7c3d9 100644 --- a/deeptutor/services/memory/store.py +++ b/deeptutor/services/memory/store.py @@ -19,7 +19,7 @@ from typing import Literal from deeptutor.services.file_io import atomic_write_text from deeptutor.services.memory import consolidator, paths, trace from deeptutor.services.memory.consolidator import ConsolidateResult, OnEvent -from deeptutor.services.memory.document import Document, parse, serialize +from deeptutor.services.memory.document import Document, anchor_new_entries, parse, serialize from deeptutor.services.memory.ops import AddOp, ApplyReport, EditOp, OpResult from deeptutor.services.memory.ops import apply as ops_apply from deeptutor.services.memory.paths import L3Slot, Surface @@ -108,7 +108,7 @@ class MemoryStore: """Direct user-driven save from the workbench editor.""" path = self._path(layer, key) async with self._lock_for(path): - await asyncio.to_thread(atomic_write_text, path, md) + await asyncio.to_thread(atomic_write_text, path, anchor_new_entries(md)) async def delete_entry(self, layer: Layer, key: str, entry_id: str) -> bool: path = self._path(layer, key) diff --git a/tests/services/memory/test_document.py b/tests/services/memory/test_document.py index 6bceb3940..0203b724c 100644 --- a/tests/services/memory/test_document.py +++ b/tests/services/memory/test_document.py @@ -1,6 +1,12 @@ from __future__ import annotations -from deeptutor.services.memory.document import Document, Entry, parse, serialize +from deeptutor.services.memory.document import ( + Document, + Entry, + anchor_new_entries, + parse, + serialize, +) _SAMPLE = """\ # Chat memory @@ -262,3 +268,35 @@ def test_serialize_omits_marker_when_entry_has_no_refs() -> None: assert "- t " in rendered # No footnote definitions block at all when nothing has refs. assert "---" not in rendered + + +def test_anchor_new_entries_keeps_hand_written_bullets() -> None: + md = """# X + +- before any section + +## S +- typed by hand [^1] +- kept + +some prose + +--- + +[^1]: chat:01 +""" + anchored = anchor_new_entries(md) + entries = parse(anchored).all_entries() + assert [(e.text, e.refs) for e in entries] == [ + ("typed by hand", ["chat:01"]), + ("kept", []), + ] + assert entries[1].id == "m_01HZK1ABCDEFGHJKMNPQRSTVWX" + # Only the unanchored bullet inside a section changes. + changed = [line for line in anchored.splitlines() if line not in md.splitlines()] + assert len(changed) == 1 and changed[0].startswith("- typed by hand [^1] \n" + ) + _run(s.overwrite_doc("L3", "preferences", md)) + saved = s.read_raw("L3", "preferences") + assert "- Kept entry \n" in saved + + report = _run( + s.write_preference( + op="add", text="Prefers short answers", trace_id="chat:01HZK4AAAAAAAAAAAAAAAAAAAA" + ) + ) + + assert report.accepted + texts = [entry.text for entry in s.read_doc("L3", "preferences").all_entries()] + assert texts == ["Explain with worked examples", "Kept entry", "Prefers short answers"] + + def test_write_preference_add(tmp_memory: Path) -> None: s = MemoryStore() report = _run(