Python
feat(sdk): import semantic memories exactly (#131)
feitianxiang6113e2351e2c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4ea6ae2..cced2c4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,9 @@ Hy Memory and MemHub are versioned and released independently.## Unreleased+- Added `import_memory_exact` for idempotent migration of an existing semantic+ memory with its canonical ID, lifecycle and supersession links, without+ extraction or reconciliation.- Added SDK-authoritative lifecycle listing with explicit status filters,idempotent durable write outcomes, exact raw import/get/list APIs, andquiesced local data-plane snapshot/restore contracts for the MemHubdiff --git a/hy_memory/client.py b/hy_memory/client.pyindex 62cc96c..94b4192 100644--- a/hy_memory/client.py+++ b/hy_memory/client.py@@ -2936,6 +2936,49 @@ class HyMemoryClient:include_runtime_diag=True,)+ def import_memory_exact(+ self,+ content: str,+ *,+ memory_id: str,+ user_id: str,+ agent_id: str = "default_agent",+ session_id: str = "default_session",+ source: str = "default",+ layer: Any = "l2_fact",+ status: Any = "active",+ owner: Optional[str] = None,+ tags: Optional[List[str]] = None,+ supersedes: Optional[List[str]] = None,+ superseded_by: Optional[List[str]] = None,+ is_latest: bool = True,+ memory_at: Optional[datetime] = None,+ metadata: Optional[Dict[str, Any]] = None,+ request_id: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Import one existing semantic memory without extraction/reconcile."""+ return self._loop_thread.run(+ self.async_import_memory_exact(+ content,+ memory_id=memory_id,+ user_id=user_id,+ agent_id=agent_id,+ session_id=session_id,+ source=source,+ layer=layer,+ status=status,+ owner=owner,+ tags=tags,+ supersedes=supersedes,+ superseded_by=superseded_by,+ is_latest=is_latest,+ memory_at=memory_at,+ metadata=metadata,+ request_id=request_id,+ ),+ include_runtime_diag=True,+ )+def get_raw(self, raw_id: str) -> Optional[Dict[str, Any]]:"""Read one SDK raw record through the explicit raw API."""return self._loop_thread.run(self.async_get_raw(raw_id))@@ -3223,6 +3266,157 @@ class HyMemoryClient:raise RuntimeError("raw import changed the requested identity")return {"success": True, "raw_id": node_id, "request_id": request_id}+ @_ensure_internal_loop+ async def async_import_memory_exact(+ self,+ content: str,+ *,+ memory_id: str,+ user_id: str,+ agent_id: str = "default_agent",+ session_id: str = "default_session",+ source: str = "default",+ layer: Any = "l2_fact",+ status: Any = "active",+ owner: Optional[str] = None,+ tags: Optional[List[str]] = None,+ supersedes: Optional[List[str]] = None,+ superseded_by: Optional[List[str]] = None,+ is_latest: bool = True,+ memory_at: Optional[datetime] = None,+ metadata: Optional[Dict[str, Any]] = None,+ request_id: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Import a canonical memory node exactly, with no model invocation."""+ from .models.memory import MemoryLayer, MemoryStatus+ from .utils.source_filter import normalize_source++ if not content or not memory_id or not user_id:+ raise ValueError("content, memory_id and user_id are required")+ normalized_layer = (+ layer if isinstance(layer, MemoryLayer) else MemoryLayer.from_string(str(layer))+ )+ if normalized_layer == MemoryLayer.L1_RAW:+ raise ValueError("use import_raw for L1_RAW")+ normalized_status = (+ status if isinstance(status, MemoryStatus) else MemoryStatus(str(status).lower())+ )+ request_id = request_id or str(uuid.uuid4())+ replay = await self._claim_write_outcome(+ request_id=request_id,+ user_id=user_id,+ agent_id=agent_id,+ session_id=session_id,+ operation="import_memory_exact",+ )+ if replay is not None:+ return replay+ try:+ result = await self._async_import_memory_exact_impl(+ content,+ memory_id=memory_id,+ user_id=user_id,+ agent_id=agent_id,+ session_id=session_id,+ source=normalize_source(source),+ layer=normalized_layer,+ status=normalized_status,+ owner=owner,+ tags=tags or [],+ supersedes=supersedes or [],+ superseded_by=superseded_by or [],+ is_latest=is_latest,+ memory_at=memory_at,+ metadata=metadata,+ request_id=request_id,+ )+ except BaseException:+ await self._mark_write_outcome_unknown(request_id)+ raise+ await self._finish_write_outcome(request_id, "succeeded", result)+ return result++ async def _async_import_memory_exact_impl(+ self,+ content: str,+ *,+ memory_id: str,+ user_id: str,+ agent_id: str,+ session_id: str,+ source: str,+ layer,+ status,+ owner: Optional[str],+ tags: List[str],+ supersedes: List[str],+ superseded_by: List[str],+ is_latest: bool,+ memory_at: Optional[datetime],+ metadata: Optional[Dict[str, Any]],+ request_id: str,+ ) -> Dict[str, Any]:+ from .models.memory import MemoryNode, SourceType++ existing = await self._vector_store.get_by_id(memory_id)+ if existing is not None:+ identity = (+ existing.content == content,+ existing.user_id == user_id,+ existing.agent_id == agent_id,+ existing.session_id == session_id,+ existing.source == source,+ existing.layer == layer,+ existing.status == status,+ existing.owner == owner,+ list(existing.tags or []) == tags,+ list(existing.supersedes or []) == supersedes,+ list(existing.superseded_by or []) == superseded_by,+ existing.is_latest == is_latest,+ )+ if not all(identity):+ raise ValueError("memory_id is already bound to different memory content")+ return {+ "success": True,+ "memory_id": memory_id,+ "memory_ids": [memory_id],+ "request_id": request_id,+ "replayed": True,+ }++ custom = dict(metadata or {})+ custom["request_id"] = request_id+ custom["input_kind"] = "memory_exact_import"+ embedding = await self._embed_service.embed(content)+ node = MemoryNode(+ node_id=memory_id,+ user_id=user_id,+ agent_id=agent_id,+ session_id=session_id,+ source=source,+ layer=layer,+ content=content,+ source_type=SourceType.EXPLICIT,+ status=status,+ owner=owner,+ tags=list(tags),+ supersedes=list(supersedes),+ superseded_by=list(superseded_by),+ is_latest=is_latest,+ embedding=embedding,+ memory_at=memory_at,+ custom=custom,+ )+ stored_id = await self._vector_store.upsert(node)+ if stored_id != memory_id:+ raise RuntimeError("exact memory import changed the requested identity")+ return {+ "success": True,+ "memory_id": memory_id,+ "memory_ids": [memory_id],+ "request_id": request_id,+ }+@_ensure_internal_loopasync def async_get_raw(self, raw_id: str) -> Optional[Dict[str, Any]]:from .models.memory import MemoryLayerdiff --git a/tests/test_raw_public_api.py b/tests/test_raw_public_api.pyindex 20d71f5..822ef80 100644--- a/tests/test_raw_public_api.py+++ b/tests/test_raw_public_api.py@@ -5,7 +5,7 @@ from unittest.mock import AsyncMockimport pytestfrom hy_memory.client import HyMemoryClient-from hy_memory.models.memory import MemoryLayer+from hy_memory.models.memory import MemoryLayer, MemoryStatusclass OutcomeCache:@@ -160,3 +160,68 @@ async def test_raw_get_and_list_use_explicit_api():)assert page["total"] == 1assert [item["raw_id"] for item in page["raw"]] == ["raw-2"]+++async def test_exact_memory_import_preserves_id_lifecycle_and_chain():+ client = _client()+ result = await HyMemoryClient.async_import_memory_exact.__wrapped__(+ client,+ "older preference",+ memory_id="memory-1",+ user_id="u1",+ agent_id="a1",+ session_id="s1",+ source="cursor",+ layer="l2_fact",+ status="superseded",+ owner="user",+ tags=["preference"],+ superseded_by=["memory-2"],+ is_latest=False,+ request_id="request-memory-1",+ )++ assert result["memory_ids"] == ["memory-1"]+ node = client._vector_store.nodes["memory-1"]+ assert node.content == "older preference"+ assert node.layer == MemoryLayer.L2_FACT+ assert node.status == MemoryStatus.SUPERSEDED+ assert node.superseded_by == ["memory-2"]+ assert node.is_latest is False+ assert node.custom["input_kind"] == "memory_exact_import"+++async def test_exact_memory_import_refuses_same_id_with_different_body():+ client = _client()+ await HyMemoryClient.async_import_memory_exact.__wrapped__(+ client,+ "first",+ memory_id="memory-1",+ user_id="u1",+ request_id="request-memory-1",+ )++ with pytest.raises(ValueError, match="different memory content"):+ await HyMemoryClient.async_import_memory_exact.__wrapped__(+ client,+ "changed",+ memory_id="memory-1",+ user_id="u1",+ request_id="request-memory-2",+ )+++async def test_exact_memory_import_rejects_raw_layer():+ client = _client()+ with pytest.raises(ValueError, match="use import_raw"):+ await HyMemoryClient.async_import_memory_exact.__wrapped__(+ client,+ "raw",+ memory_id="memory-1",+ user_id="u1",+ layer="l1_raw",+ request_id="request-memory-1",+ )