Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
Add Memory Bridge: bidirectional sync between markdown files and Headroom memory
chopratejasdf1f53efe72b
diff --git a/headroom/memory/__init__.py b/headroom/memory/__init__.pyindex efc0799fa..f64d0b986 100644--- a/headroom/memory/__init__.py+++ b/headroom/memory/__init__.py@@ -61,6 +61,12 @@ from headroom.memory.adapters.graph import InMemoryGraphStore# =============================================================================# LocalBackend is always available (no optional dependencies)from headroom.memory.backends.local import LocalBackend, LocalBackendConfig++# =============================================================================+# Memory Bridge (markdown <-> Headroom bidirectional sync)+# =============================================================================+from headroom.memory.bridge import ImportStats, MemoryBridge, SyncStats+from headroom.memory.bridge_config import BridgeConfig, MarkdownFormatfrom headroom.memory.config import (EmbedderBackend,MemoryConfig,@@ -275,4 +281,12 @@ __all__ = [# Use with optimized=True in with_memory_tools() for best performance"DirectMem0Adapter","DirectMem0Config",+ # =========================================================================+ # Memory Bridge (markdown <-> Headroom bidirectional sync)+ # =========================================================================+ "MemoryBridge",+ "BridgeConfig",+ "MarkdownFormat",+ "ImportStats",+ "SyncStats",]diff --git a/headroom/memory/bridge.py b/headroom/memory/bridge.pynew file mode 100644index 000000000..7ea081d16--- /dev/null+++ b/headroom/memory/bridge.py@@ -0,0 +1,661 @@+"""Memory Bridge: bidirectional bridge between markdown files and Headroom memory.++Imports markdown memory files (Claude Code MEMORY.md, ChatGPT facts, etc.)+into Headroom's semantic memory system, and exports Headroom memories back+to organized markdown files. Supports bidirectional sync with hash-based+change detection.++Usage:+ from headroom.memory.bridge import MemoryBridge+ from headroom.memory.bridge_config import BridgeConfig+ from pathlib import Path++ config = BridgeConfig(+ md_paths=[Path("~/.claude/.../memory/MEMORY.md")],+ user_id="alice",+ )+ bridge = MemoryBridge(config, backend)++ # Import markdown -> Headroom+ stats = await bridge.import_from_markdown()++ # Export Headroom -> markdown+ markdown = await bridge.export_to_markdown()++ # Bidirectional sync+ stats = await bridge.sync()+"""++from __future__ import annotations++import json+import logging+from collections import defaultdict+from dataclasses import dataclass, field+from datetime import datetime, timezone+from pathlib import Path+from typing import TYPE_CHECKING, Any++from headroom.memory.bridge_config import BridgeConfig, MarkdownFormat+from headroom.memory.bridge_parsers import (+ ParsedFile,+ ParsedSection,+ extract_relationships_from_section,+ parse_markdown,+)++if TYPE_CHECKING:+ from headroom.memory.backends.local import LocalBackend+ from headroom.memory.models import Memory++logger = logging.getLogger(__name__)+++# ---------------------------------------------------------------------------+# Stats dataclasses+# ---------------------------------------------------------------------------+++@dataclass+class ImportStats:+ """Statistics from an import operation."""++ files_processed: int = 0+ files_skipped_unchanged: int = 0+ sections_imported: int = 0+ sections_skipped_duplicate: int = 0+ sections_failed: int = 0+ entities_extracted: int = 0+ total_facts: int = 0+++@dataclass+class SyncStats:+ """Statistics from a sync operation."""++ import_stats: ImportStats = field(default_factory=ImportStats)+ memories_exported: int = 0+ files_unchanged: int = 0+ files_updated: int = 0+++# ---------------------------------------------------------------------------+# MemoryBridge+# ---------------------------------------------------------------------------+++class MemoryBridge:+ """Bidirectional bridge between markdown memory files and Headroom's+ semantic memory system.++ Supports import (md -> Headroom), export (Headroom -> md), and+ bidirectional sync with hash-based change detection.+ """++ def __init__(+ self,+ config: BridgeConfig,+ backend: LocalBackend | Any,+ ) -> None:+ self._config = config+ self._backend = backend+ self._sync_state: dict[str, Any] = {}+ self._load_sync_state()++ # =========================================================================+ # Sync State Management+ # =========================================================================++ def _load_sync_state(self) -> None:+ """Load sync state from disk."""+ path = self._config.sync_state_path+ if path.exists():+ try:+ self._sync_state = json.loads(path.read_text(encoding="utf-8"))+ except (json.JSONDecodeError, OSError) as e:+ logger.warning(f"Bridge: Failed to load sync state from {path}: {e}")+ self._sync_state = {}+ if "version" not in self._sync_state:+ self._sync_state = {"version": 1, "last_sync": None, "files": {}}++ def _save_sync_state(self) -> None:+ """Persist sync state to disk."""+ path = self._config.sync_state_path+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ json.dumps(self._sync_state, indent=2, default=str),+ encoding="utf-8",+ )+ except OSError as e:+ logger.warning(f"Bridge: Failed to save sync state to {path}: {e}")++ def _get_stored_file_hash(self, file_path: str) -> str | None:+ """Get the stored hash for a file, or None if not tracked."""+ files = self._sync_state.get("files", {})+ file_state = files.get(file_path, {})+ result = file_state.get("hash")+ return str(result) if result is not None else None++ def _get_stored_section_hashes(self, file_path: str) -> dict[str, str]:+ """Get stored section hash -> memory_id mapping for a file."""+ files = self._sync_state.get("files", {})+ file_state = files.get(file_path, {})+ sections: dict[str, str] = file_state.get("sections", {})+ return sections++ def _update_file_state(+ self,+ file_path: str,+ file_hash: str,+ section_mapping: dict[str, str],+ ) -> None:+ """Update sync state for a file."""+ if "files" not in self._sync_state:+ self._sync_state["files"] = {}+ self._sync_state["files"][file_path] = {+ "hash": file_hash,+ "last_imported": datetime.now(timezone.utc).isoformat(),+ "sections": section_mapping,+ }+ self._sync_state["last_sync"] = datetime.now(timezone.utc).isoformat()++ # =========================================================================+ # Import: Markdown -> Headroom+ # =========================================================================++ async def import_from_markdown(+ self,+ paths: list[Path] | None = None,+ user_id: str | None = None,+ force: bool = False,+ ) -> ImportStats:+ """Import markdown memory files into Headroom's vector store.++ Args:+ paths: Files to import (uses config.md_paths if None).+ user_id: User ID for imported memories (uses config.user_id if None).+ force: If True, import even if file hash hasn't changed.++ Returns:+ ImportStats with counts.+ """+ paths = paths or self._config.md_paths+ user_id = user_id or self._config.user_id+ total_stats = ImportStats()++ for path in paths:+ path = Path(path).expanduser()+ if not path.exists():+ logger.warning(f"Bridge: File not found: {path}")+ total_stats.files_skipped_unchanged += 1+ continue++ file_stats = await self._import_file(path, user_id, force)+ total_stats.files_processed += file_stats.files_processed+ total_stats.files_skipped_unchanged += file_stats.files_skipped_unchanged+ total_stats.sections_imported += file_stats.sections_imported+ total_stats.sections_skipped_duplicate += file_stats.sections_skipped_duplicate+ total_stats.sections_failed += file_stats.sections_failed+ total_stats.entities_extracted += file_stats.entities_extracted+ total_stats.total_facts += file_stats.total_facts++ self._save_sync_state()+ logger.info(+ f"Bridge: Import complete — {total_stats.sections_imported} sections imported, "+ f"{total_stats.sections_skipped_duplicate} duplicates skipped"+ )+ return total_stats++ async def _import_file(+ self,+ path: Path,+ user_id: str,+ force: bool = False,+ ) -> ImportStats:+ """Import a single markdown file."""+ stats = ImportStats()+ file_path_str = str(path)++ # Parse file+ try:+ content = path.read_text(encoding="utf-8")+ except OSError as e:+ logger.error(f"Bridge: Failed to read {path}: {e}")+ stats.sections_failed += 1+ return stats++ parsed = self._parse_content(content, file_path_str)++ # Check if file has changed+ stored_hash = self._get_stored_file_hash(file_path_str)+ if not force and stored_hash == parsed.file_hash:+ logger.debug(f"Bridge: File unchanged, skipping: {path}")+ stats.files_skipped_unchanged += 1+ return stats++ stats.files_processed = 1+ stored_sections = self._get_stored_section_hashes(file_path_str)+ new_section_mapping: dict[str, str] = {}++ for section in parsed.sections:+ if not section.content.strip():+ continue++ # Skip sections that haven't changed (by content hash)+ if not force and section.content_hash in stored_sections:+ memory_id = stored_sections[section.content_hash]+ new_section_mapping[section.content_hash] = memory_id+ stats.sections_skipped_duplicate += 1+ continue++ try:+ imported_id = await self._import_section(section, user_id, file_path_str)+ if imported_id:+ new_section_mapping[section.content_hash] = imported_id+ stats.sections_imported += 1+ stats.entities_extracted += len(section.entities)+ stats.total_facts += len(section.facts)+ else:+ stats.sections_skipped_duplicate += 1+ except Exception as e:+ logger.error(f"Bridge: Failed to import section '{section.heading}': {e}")+ stats.sections_failed += 1++ self._update_file_state(file_path_str, parsed.file_hash, new_section_mapping)+ return stats++ async def _import_section(+ self,+ section: ParsedSection,+ user_id: str,+ file_path: str,+ ) -> str | None:+ """Import a single parsed section into Headroom.++ Returns the memory ID if imported, None if skipped as duplicate.+ """+ # Check for semantic duplicates+ if await self._check_duplicate(section.content, user_id):+ return None++ # Compute importance from heading level+ importance = self._config.heading_importance_map.get(+ section.heading_level, self._config.default_importance+ )++ # Build metadata+ metadata: dict[str, Any] = {+ "source": self._config.source_tag,+ "source_file": file_path,+ "content_hash": section.content_hash,+ "imported_at": datetime.now(timezone.utc).isoformat(),+ }+ if section.heading:+ metadata["section_heading"] = section.heading++ # Extract entities and relationships+ entities = section.entities if self._config.extract_entities else None+ relationships = None+ if self._config.extract_entities and section.entities:+ relationships = extract_relationships_from_section(section)++ # Store via backend+ # If we have individual facts and chunk_by_section is True, store as facts+ if self._config.chunk_by_section and section.facts:+ memory = await self._backend.save_memory(+ content=section.content,+ user_id=user_id,+ importance=importance,+ entities=entities,+ relationships=relationships if relationships else None,+ metadata=metadata,+ facts=section.facts,+ )+ else:+ memory = await self._backend.save_memory(+ content=section.content,+ user_id=user_id,+ importance=importance,+ entities=entities,+ relationships=relationships if relationships else None,+ metadata=metadata,+ )++ return memory.id++ def _parse_content(self, content: str, file_path: str) -> ParsedFile:+ """Parse markdown content using configured or auto-detected format."""+ fmt = self._config.md_format+ if fmt == MarkdownFormat.AUTO:+ return parse_markdown(content, file_path, format=None)+ return parse_markdown(content, file_path, format=fmt.value)++ async def _check_duplicate(self, content: str, user_id: str) -> bool:+ """Check if similar content already exists in memory.++ Uses semantic search with high similarity threshold.+ """+ threshold = self._config.dedup_similarity_threshold+ try:+ results = await self._backend.search_memories(+ query=content[:500], # Limit query length+ user_id=user_id,+ top_k=3,+ min_similarity=threshold,+ )+ return len(results) > 0+ except Exception:+ # If search fails, don't block import+ return False++ # =========================================================================+ # Export: Headroom -> Markdown+ # =========================================================================++ async def export_to_markdown(+ self,+ path: Path | None = None,+ user_id: str | None = None,+ format: MarkdownFormat | None = None,+ top_k: int = 200,+ ) -> str:+ """Export Headroom memories to a markdown file.++ Args:+ path: Output file path (uses config.export_path if None).+ user_id: User to export (uses config.user_id if None).+ format: Output format (uses config.export_format if None).+ top_k: Maximum memories to export.++ Returns:+ The generated markdown string.+ """+ path = path or self._config.export_path+ user_id = user_id or self._config.user_id+ format = format or self._config.export_format++ memories = await self._fetch_all_memories(user_id, top_k)+ if not memories:+ markdown = "# Memories\n\nNo memories stored yet.\n"+ elif format == MarkdownFormat.CHATGPT:+ markdown = self._format_chatgpt_style(memories)+ elif format == MarkdownFormat.CLAUDE_CODE:+ grouped = self._group_memories_by_topic(memories)+ markdown = self._format_claude_code_style(grouped)+ else:+ grouped = self._group_memories_by_topic(memories)+ markdown = self._format_generic_style(grouped)++ if path:+ path = Path(path).expanduser()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(markdown, encoding="utf-8")+ logger.info(f"Bridge: Exported {len(memories)} memories to {path}")++ # Update sync state to avoid re-importing our own export+ import hashlib++ file_hash = hashlib.sha256(markdown.encode()).hexdigest()+ self._update_file_state(str(path), file_hash, {})+ self._save_sync_state()++ return markdown++ async def _fetch_all_memories(+ self,+ user_id: str,+ top_k: int = 200,+ ) -> list[Memory]:+ """Fetch all memories for a user, sorted by importance then recency."""+ if hasattr(self._backend, "get_user_memories"):+ memories = await self._backend.get_user_memories(user_id, limit=top_k)+ else:+ # Fallback: search with broad query+ results = await self._backend.search_memories(+ query="*",+ user_id=user_id,+ top_k=top_k,+ )+ memories = [r.memory for r in results]++ # Sort: importance descending, then recency descending+ memories.sort(key=lambda m: (-m.importance, -m.created_at.timestamp()))+ return memories++ def _group_memories_by_topic(+ self,+ memories: list[Memory],+ ) -> dict[str, list[Memory]]:+ """Group memories by topic using metadata and entity clustering."""+ groups: dict[str, list[Memory]] = defaultdict(list)++ for memory in memories:+ metadata = memory.metadata or {}++ # Priority 1: section_heading from import+ heading = metadata.get("section_heading")+ if heading:+ groups[heading].append(memory)+ continue++ # Priority 2: topic from metadata+ topic = metadata.get("topic")+ if topic:+ groups[topic].append(memory)+ continue++ # Priority 3: most common entity+ if memory.entity_refs:+ groups[memory.entity_refs[0]].append(memory)+ continue++ # Fallback+ groups["General"].append(memory)++ return dict(groups)++ def _format_claude_code_style(+ self,+ grouped: dict[str, list[Memory]],+ ) -> str:+ """Format memories as Claude Code MEMORY.md style."""+ lines = ["# Memory\n"]++ for topic, memories in grouped.items():+ lines.append(f"## {topic}")+ for memory in memories:+ content = memory.content.strip()+ # If content has multiple lines, use first line as the bullet+ first_line = content.split("\n")[0].strip()+ if first_line.startswith("- "):+ lines.append(first_line)+ else:+ lines.append(f"- {first_line}")+ lines.append("")++ return "\n".join(lines)++ def _format_chatgpt_style(+ self,+ memories: list[Memory],+ ) -> str:+ """Format as ChatGPT flat fact list."""+ lines = []+ for memory in memories:+ content = memory.content.strip()+ first_line = content.split("\n")[0].strip()+ if first_line.startswith("- "):+ first_line = first_line[2:]+ lines.append(first_line)+ return "\n".join(lines) + "\n"++ def _format_generic_style(+ self,+ grouped: dict[str, list[Memory]],+ ) -> str:+ """Format as generic structured markdown."""+ lines = ["# Memories\n"]++ for topic, memories in grouped.items():+ lines.append(f"## {topic}")+ for memory in memories:+ content = memory.content.strip()+ first_line = content.split("\n")[0].strip()+ if first_line.startswith("- "):+ lines.append(first_line)+ else:+ lines.append(f"- {first_line}")+ lines.append("")++ return "\n".join(lines)++ # =========================================================================+ # Sync: Bidirectional+ # =========================================================================++ async def sync(+ self,+ paths: list[Path] | None = None,+ user_id: str | None = None,+ ) -> SyncStats:+ """Bidirectional sync between markdown files and Headroom.++ 1. Import new/changed sections from md files.+ 2. Export new organic Headroom memories back to md files.+ """+ paths = paths or self._config.md_paths+ user_id = user_id or self._config.user_id+ stats = SyncStats()++ # Phase 1: Import from markdown+ stats.import_stats = await self.import_from_markdown(paths=paths, user_id=user_id)++ # Phase 2: Export new organic memories to markdown+ last_sync_str = self._sync_state.get("last_sync")+ since = None+ if last_sync_str:+ try:+ since = datetime.fromisoformat(last_sync_str)+ except (ValueError, TypeError):+ pass++ new_memories = await self._get_new_organic_memories(user_id, since)++ if new_memories and paths:+ # Append to the first configured file+ primary_path = Path(paths[0]).expanduser()+ count = await self._append_to_markdown(primary_path, new_memories)+ stats.memories_exported = count+ if count > 0:+ stats.files_updated = 1++ self._sync_state["last_sync"] = datetime.now(timezone.utc).isoformat()+ self._save_sync_state()++ logger.info(+ f"Bridge: Sync complete — imported {stats.import_stats.sections_imported}, "+ f"exported {stats.memories_exported}"+ )+ return stats++ async def _get_new_organic_memories(+ self,+ user_id: str,+ since: datetime | None = None,+ ) -> list[Memory]:+ """Get memories created since last sync that didn't come from bridge import.++ Filters out memories with metadata source == source_tag.+ """+ if hasattr(self._backend, "get_user_memories"):+ all_memories = await self._backend.get_user_memories(user_id, limit=500)+ else:+ results = await self._backend.search_memories(query="*", user_id=user_id, top_k=500)+ all_memories = [r.memory for r in results]++ organic: list[Memory] = []+ for memory in all_memories:+ # Skip memories created by the bridge itself+ metadata = memory.metadata or {}+ if metadata.get("source") == self._config.source_tag:+ continue++ # Skip memories from before last sync+ if since:+ # Handle timezone-naive vs timezone-aware comparison+ mem_time = memory.created_at+ cmp_time = since+ if mem_time.tzinfo is None and cmp_time.tzinfo is not None:+ mem_time = mem_time.replace(tzinfo=timezone.utc)+ elif mem_time.tzinfo is not None and cmp_time.tzinfo is None:+ cmp_time = cmp_time.replace(tzinfo=timezone.utc)+ if mem_time < cmp_time:+ continue++ organic.append(memory)++ return organic++ async def _append_to_markdown(+ self,+ path: Path,+ memories: list[Memory],+ ) -> int:+ """Append new memories to an existing markdown file.++ Reads the file, appends memories under appropriate sections,+ writes back. Returns count of memories appended.+ """+ if not memories:+ return 0++ # Read existing content+ existing_content = ""+ if path.exists():+ try:+ existing_content = path.read_text(encoding="utf-8")+ except OSError:+ pass++ # Group new memories by topic+ grouped = self._group_memories_by_topic(memories)+ lines_to_append: list[str] = []++ for topic, topic_memories in grouped.items():+ # Check if section already exists in the file+ section_exists = f"## {topic}" in existing_content++ if not section_exists:+ lines_to_append.append(f"\n## {topic}")++ for memory in topic_memories:+ content = memory.content.strip()+ first_line = content.split("\n")[0].strip()+ if first_line.startswith("- "):+ lines_to_append.append(first_line)+ else:+ lines_to_append.append(f"- {first_line}")++ if not lines_to_append:+ return 0++ # Append to file+ append_text = "\n".join(lines_to_append) + "\n"+ new_content = existing_content.rstrip() + "\n" + append_text++ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(new_content, encoding="utf-8")+ except OSError as e:+ logger.error(f"Bridge: Failed to write {path}: {e}")+ return 0++ # Update file hash in sync state+ import hashlib++ file_hash = hashlib.sha256(new_content.encode()).hexdigest()+ stored_sections = self._get_stored_section_hashes(str(path))+ self._update_file_state(str(path), file_hash, stored_sections)++ return len(memories)diff --git a/headroom/memory/bridge_config.py b/headroom/memory/bridge_config.pynew file mode 100644index 000000000..5d69ff247--- /dev/null+++ b/headroom/memory/bridge_config.py@@ -0,0 +1,73 @@+"""Configuration for the Memory Bridge.++The Memory Bridge provides bidirectional sync between markdown memory files+(used by Claude Code, ChatGPT, etc.) and Headroom's semantic memory system.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from enum import Enum+from pathlib import Path+++class MarkdownFormat(Enum):+ """Supported markdown memory formats."""++ CLAUDE_CODE = "claude_code" # ~/.claude/projects/<project>/memory/MEMORY.md+ CHATGPT = "chatgpt" # Flat fact list, one per line+ GENERIC = "generic" # Structured markdown with headers+ AUTO = "auto" # Auto-detect from content+++@dataclass+class BridgeConfig:+ """Configuration for the Memory Bridge.++ Attributes:+ md_paths: List of markdown file paths to bridge.+ md_format: Format of the markdown files (auto-detected if AUTO).+ user_id: Default user_id for imported memories.+ default_importance: Base importance for imported memories.+ heading_importance_map: Map heading depth to importance score.+ sync_state_path: Path to store sync state (hashes, timestamps).+ auto_import_on_startup: Whether to import on proxy startup.+ export_path: Where to write exported markdown.+ export_format: Format for exported markdown.+ extract_entities: Whether to extract entities during import.+ chunk_by_section: Split markdown by section headers for granular memories.+ dedup_similarity_threshold: Similarity above which a memory is a duplicate.+ source_tag: Metadata tag added to all bridged memories for tracking.+ """++ md_paths: list[Path] = field(default_factory=list)+ md_format: MarkdownFormat = MarkdownFormat.AUTO+ user_id: str = "default"+ default_importance: float = 0.6+ heading_importance_map: dict[int, float] = field(+ default_factory=lambda: {1: 0.9, 2: 0.8, 3: 0.7, 4: 0.6, 5: 0.5, 6: 0.4}+ )+ sync_state_path: Path = field(+ default_factory=lambda: Path.home() / ".headroom" / "bridge_state.json"+ )+ auto_import_on_startup: bool = False+ export_path: Path | None = None+ export_format: MarkdownFormat = MarkdownFormat.GENERIC+ extract_entities: bool = True+ chunk_by_section: bool = True+ dedup_similarity_threshold: float = 0.92+ source_tag: str = "memory_bridge"++ def __post_init__(self) -> None:+ """Validate configuration."""+ if not 0.0 <= self.default_importance <= 1.0:+ raise ValueError(f"default_importance must be 0.0-1.0, got {self.default_importance}")+ if not 0.0 <= self.dedup_similarity_threshold <= 1.0:+ raise ValueError(+ f"dedup_similarity_threshold must be 0.0-1.0, got {self.dedup_similarity_threshold}"+ )+ self.md_paths = [Path(p) if isinstance(p, str) else p for p in self.md_paths]+ if isinstance(self.sync_state_path, str):+ self.sync_state_path = Path(self.sync_state_path)+ if self.export_path and isinstance(self.export_path, str):+ self.export_path = Path(self.export_path)diff --git a/headroom/memory/bridge_parsers.py b/headroom/memory/bridge_parsers.pynew file mode 100644index 000000000..bc9f85eeb--- /dev/null+++ b/headroom/memory/bridge_parsers.py@@ -0,0 +1,472 @@+"""Markdown memory file parsers for various foundational model formats.++Parses markdown files into structured sections that can be imported into+Headroom's semantic memory system. Supports:+- Claude Code MEMORY.md format (## headers + bullet facts)+- ChatGPT flat fact list (one fact per line)+- Generic structured markdown (any # headers + content)++All parsers are pure functions with no external dependencies.+"""++from __future__ import annotations++import hashlib+import re+from dataclasses import dataclass, field+from typing import Any+++@dataclass+class ParsedSection:+ """A section parsed from a markdown memory file.++ Represents one logical chunk: a heading and its bullet content.+ """++ heading: str # The heading text (empty for top-level/no heading)+ heading_level: int # 1-6, or 0 for no heading+ content: str # The full text content of this section+ facts: list[str] # Individual facts (one per bullet)+ entities: list[str] = field(default_factory=list)+ metadata: dict[str, Any] = field(default_factory=dict)+ content_hash: str = ""++ def __post_init__(self) -> None:+ if not self.content_hash and self.content:+ self.content_hash = hashlib.sha256(self.content.encode()).hexdigest()+++@dataclass+class ParsedFile:+ """Complete parsed representation of a memory file."""++ path: str+ format: str # "claude_code", "chatgpt", "generic"+ sections: list[ParsedSection]+ file_hash: str+ raw_content: str+++# ---------------------------------------------------------------------------+# Entity extraction (lightweight, no LLM)+# ---------------------------------------------------------------------------++# Common words to skip when extracting capitalized phrases+_STOP_WORDS = frozenset(+ {+ "The",+ "This",+ "That",+ "These",+ "Those",+ "When",+ "Where",+ "What",+ "Which",+ "Who",+ "How",+ "Why",+ "And",+ "But",+ "For",+ "Not",+ "With",+ "From",+ "Into",+ "Over",+ "Under",+ "After",+ "Before",+ "Between",+ "Through",+ "During",+ "About",+ "Against",+ "Each",+ "Every",+ "Some",+ "Any",+ "All",+ "Most",+ "Other",+ "Such",+ "Only",+ "Also",+ "Very",+ "Just",+ "Then",+ "Than",+ "Both",+ "Even",+ "Still",+ "Here",+ "There",+ "Once",+ "Note",+ "See",+ "Use",+ "New",+ "Key",+ "Important",+ "Direct",+ "Native",+ "Managed",+ "Full",+ "Main",+ "Relevant",+ }+)+++def extract_entities_from_text(text: str) -> list[str]:+ """Extract likely entity names from text using heuristics.++ Looks for:+ - Bold text (**entity**)+ - Capitalized multi-word sequences (Proper Nouns)+ - Text before colons in "Key: Value" patterns++ Returns deduplicated list of entity names.+ """+ entities: set[str] = set()++ # 1. Bold text: **entity**+ for match in re.finditer(r"\*\*([^*]+)\*\*", text):+ entity = match.group(1).strip()+ if entity and len(entity) < 100:+ entities.add(entity)++ # 2. Capitalized multi-word sequences (2+ words, both capitalized)+ for match in re.finditer(r"\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)+)\b", text):+ phrase = match.group(1).strip()+ words = phrase.split()+ # Skip if first word is a stop word+ if words[0] not in _STOP_WORDS and len(phrase) < 80:+ entities.add(phrase)++ # 3. Single capitalized words that look like proper nouns / tech names+ # Must be at least 2 chars, not at start of sentence+ for match in re.finditer(r"(?<=[a-z.,;:]\s)([A-Z][a-zA-Z0-9]+)\b", text):+ word = match.group(1)+ if word not in _STOP_WORDS and len(word) >= 2:+ entities.add(word)++ # 4. CamelCase or ALL_CAPS identifiers (tech/code names)+ for match in re.finditer(r"\b([A-Z][a-z]+[A-Z][a-zA-Z]*)\b", text):+ entities.add(match.group(1))+ for match in re.finditer(r"\b([A-Z][A-Z_]{2,})\b", text):+ word = match.group(1)+ if word not in {"THE", "AND", "BUT", "FOR", "NOT", "WITH", "FROM"}:+ entities.add(word)++ return sorted(entities)+++def extract_relationships_from_section(+ section: ParsedSection,+) -> list[dict[str, str]]:+ """Extract relationships from a parsed section using pattern matching.++ Looks for patterns like:+ - "X: Y" -> (X, "is", Y)+ - "X uses Y" -> (X, "uses", Y)+ - "X at Y" -> (X, "located_at", Y)++ Returns list of {"source": ..., "relationship": ..., "destination": ...}+ """+ relationships: list[dict[str, str]] = []++ # Pattern: **Key**: Value (common in Claude Code MEMORY.md)+ for match in re.finditer(r"\*\*([^*]+)\*\*:\s*(.+?)(?:\n|$)", section.content):+ key = match.group(1).strip()+ value = match.group(2).strip()+ if key and value and len(key) < 80 and len(value) < 200:+ relationships.append({"source": key, "relationship": "is", "destination": value})++ # Pattern: "X uses Y", "X with Y", "X via Y"+ verb_patterns = [+ (r"(\w+(?:\s+\w+)?)\s+uses\s+(\w+(?:\s+\w+)?)", "uses"),+ (r"(\w+(?:\s+\w+)?)\s+requires\s+(\w+(?:\s+\w+)?)", "requires"),+ (r"(\w+(?:\s+\w+)?)\s+integrates\s+with\s+(\w+(?:\s+\w+)?)", "integrates_with"),+ (r"(\w+(?:\s+\w+)?)\s+depends\s+on\s+(\w+(?:\s+\w+)?)", "depends_on"),+ ]+ for pattern, rel_type in verb_patterns:+ for match in re.finditer(pattern, section.content, re.IGNORECASE):+ source = match.group(1).strip()+ dest = match.group(2).strip()+ if source and dest:+ relationships.append(+ {"source": source, "relationship": rel_type, "destination": dest}+ )++ return relationships+++# ---------------------------------------------------------------------------+# Format detection+# ---------------------------------------------------------------------------+++def detect_format(content: str) -> str:+ """Auto-detect the markdown memory format.++ Returns:+ "claude_code", "chatgpt", or "generic"+ """+ lines = content.strip().splitlines()+ if not lines:+ return "generic"++ has_h2_headers = False+ has_bullets = False+ short_line_count = 0+ total_lines = 0++ for line in lines:+ stripped = line.strip()+ if not stripped:+ continue+ total_lines += 1++ if stripped.startswith("## "):+ has_h2_headers = True+ if stripped.startswith("- "):+ has_bullets = True+ if len(stripped) < 120:+ short_line_count += 1++ # Claude Code: ## headers + bullets, often with **bold** keys+ if has_h2_headers and has_bullets:+ return "claude_code"++ # ChatGPT: mostly short lines, no headers, looks like flat facts+ if total_lines > 0 and not has_h2_headers:+ short_ratio = short_line_count / total_lines+ if short_ratio > 0.8 and total_lines >= 2:+ return "chatgpt"++ return "generic"+++# ---------------------------------------------------------------------------+# Parsers+# ---------------------------------------------------------------------------+++def _compute_file_hash(content: str) -> str:+ """Compute SHA-256 hash of file content."""+ return hashlib.sha256(content.encode()).hexdigest()+++def parse_claude_code_memory(content: str, file_path: str = "") -> ParsedFile:+ """Parse Claude Code MEMORY.md format.++ Structure: markdown with # and ## headers, bullet lists with optional **bold** keys.++ Example:+ # Project Memory++ ## Project Overview+ - **Headroom**: Context optimization layer+ - **Repos**: OSS at ~/claude-projects/headroom++ ## Key Architecture+ - 186 Python files, 34 packages+ """+ file_hash = _compute_file_hash(content)+ sections: list[ParsedSection] = []++ current_heading = ""+ current_level = 0+ current_lines: list[str] = []++ def flush_section() -> None:+ if not current_lines and not current_heading:+ return+ section_content = "\n".join(current_lines).strip()+ if not section_content and not current_heading:+ return++ facts = []+ for line in current_lines:+ stripped = line.strip()+ if stripped.startswith("- "):+ fact = stripped[2:].strip()+ if fact:+ facts.append(fact)++ entities = extract_entities_from_text(section_content) if section_content else []++ sections.append(+ ParsedSection(+ heading=current_heading,+ heading_level=current_level,+ content=section_content,+ facts=facts,+ entities=entities,+ metadata={"source_format": "claude_code"},+ )+ )++ for line in content.splitlines():+ header_match = re.match(r"^(#{1,6})\s+(.+)$", line)+ if header_match:+ flush_section()+ current_level = len(header_match.group(1))+ current_heading = header_match.group(2).strip()+ current_lines = []+ else:+ current_lines.append(line)++ flush_section()++ return ParsedFile(+ path=file_path,+ format="claude_code",+ sections=sections,+ file_hash=file_hash,+ raw_content=content,+ )+++def parse_chatgpt_facts(content: str, file_path: str = "") -> ParsedFile:+ """Parse ChatGPT-style flat fact list.++ Structure: one fact per line, optionally prefixed with -.++ Example:+ User prefers Python+ User works at Netflix+ - User likes dark mode+ """+ file_hash = _compute_file_hash(content)+ facts: list[str] = []++ for line in content.splitlines():+ stripped = line.strip()+ if not stripped:+ continue+ # Strip optional bullet prefix+ if stripped.startswith("- "):+ stripped = stripped[2:].strip()+ if stripped:+ facts.append(stripped)++ all_content = "\n".join(facts)+ entities = extract_entities_from_text(all_content) if facts else []++ sections = (+ [+ ParsedSection(+ heading="",+ heading_level=0,+ content=all_content,+ facts=facts,+ entities=entities,+ metadata={"source_format": "chatgpt"},+ )+ ]+ if facts+ else []+ )++ return ParsedFile(+ path=file_path,+ format="chatgpt",+ sections=sections,+ file_hash=file_hash,+ raw_content=content,+ )+++def parse_generic_markdown(content: str, file_path: str = "") -> ParsedFile:+ """Parse generic structured markdown.++ Handles any markdown with #-###### headers and content below.+ Groups content by nearest heading.+ """+ file_hash = _compute_file_hash(content)+ sections: list[ParsedSection] = []++ current_heading = ""+ current_level = 0+ current_lines: list[str] = []++ def flush_section() -> None:+ if not current_lines and not current_heading:+ return+ section_content = "\n".join(current_lines).strip()+ if not section_content and not current_heading:+ return++ facts = []+ for line in current_lines:+ stripped = line.strip()+ if stripped.startswith("- "):+ fact = stripped[2:].strip()+ if fact:+ facts.append(fact)+ elif stripped and not stripped.startswith("#"):+ # Non-bullet, non-empty lines are also facts in generic mode+ facts.append(stripped)++ entities = extract_entities_from_text(section_content) if section_content else []++ sections.append(+ ParsedSection(+ heading=current_heading,+ heading_level=current_level,+ content=section_content,+ facts=facts,+ entities=entities,+ metadata={"source_format": "generic"},+ )+ )++ for line in content.splitlines():+ header_match = re.match(r"^(#{1,6})\s+(.+)$", line)+ if header_match:+ flush_section()+ current_level = len(header_match.group(1))+ current_heading = header_match.group(2).strip()+ current_lines = []+ else:+ current_lines.append(line)++ flush_section()++ return ParsedFile(+ path=file_path,+ format="generic",+ sections=sections,+ file_hash=file_hash,+ raw_content=content,+ )+++def parse_markdown(+ content: str,+ file_path: str = "",+ format: str | None = None,+) -> ParsedFile:+ """Parse a markdown memory file, auto-detecting format if not specified.++ Args:+ content: The markdown file content.+ file_path: Path to the source file (for metadata).+ format: Force a specific format ("claude_code", "chatgpt", "generic").+ If None, auto-detects.++ Returns:+ ParsedFile with structured sections.+ """+ if format is None or format == "auto":+ format = detect_format(content)++ if format == "claude_code":+ return parse_claude_code_memory(content, file_path)+ elif format == "chatgpt":+ return parse_chatgpt_facts(content, file_path)+ else:+ return parse_generic_markdown(content, file_path)diff --git a/headroom/proxy/memory_handler.py b/headroom/proxy/memory_handler.pyindex 4be8beed1..d09bf6693 100644--- a/headroom/proxy/memory_handler.py+++ b/headroom/proxy/memory_handler.py@@ -26,7 +26,7 @@ from __future__ import annotationsimport jsonimport logging-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literal@@ -68,6 +68,12 @@ class MemoryConfig:neo4j_uri: str = "neo4j://localhost:7687"neo4j_user: str = "neo4j"neo4j_password: str = "password"+ # Memory Bridge (bidirectional markdown <-> Headroom sync)+ bridge_enabled: bool = False+ bridge_md_paths: list[str] = field(default_factory=list)+ bridge_md_format: str = "auto"+ bridge_auto_import: bool = False+ bridge_export_path: str = ""class MemoryHandler:@@ -93,6 +99,8 @@ class MemoryHandler:self._native_memory_dir: Path | None = Noneif config.use_native_tool:self._init_native_memory_dir()+ # Memory Bridge+ self._bridge: Any = None # MemoryBridge, lazy importeddef _init_native_memory_dir(self) -> None:"""Initialize native memory directory."""@@ -163,6 +171,35 @@ class MemoryHandler:self._initialized = True+ # Auto-import from Memory Bridge if configured+ if self.config.bridge_enabled and self.config.bridge_auto_import:+ await self._init_and_import_bridge()++ async def _init_and_import_bridge(self) -> None:+ """Initialize the Memory Bridge and run auto-import."""+ if self._bridge is not None:+ return+ try:+ from headroom.memory.bridge import MemoryBridge+ from headroom.memory.bridge_config import BridgeConfig, MarkdownFormat++ bridge_config = BridgeConfig(+ md_paths=[Path(p) for p in self.config.bridge_md_paths],+ md_format=MarkdownFormat(self.config.bridge_md_format),+ auto_import_on_startup=True,+ export_path=Path(self.config.bridge_export_path)+ if self.config.bridge_export_path+ else None,+ )+ self._bridge = MemoryBridge(bridge_config, self._backend)+ stats = await self._bridge.import_from_markdown()+ logger.info(+ f"Memory Bridge: Auto-imported {stats.sections_imported} sections "+ f"({stats.sections_skipped_duplicate} duplicates skipped)"+ )+ except Exception as e:+ logger.warning(f"Memory Bridge: Auto-import failed: {e}")+def _get_memory_tools(self) -> list[dict[str, Any]]:"""Get memory tool definitions (cached)."""if self._memory_tools is None:diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex cb2fa4334..64f3b46f9 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -33,7 +33,7 @@ import randomimport sysimport timefrom collections import OrderedDict, defaultdict, deque-from dataclasses import asdict, dataclass+from dataclasses import asdict, dataclass, fieldfrom datetime import datetime, timedeltafrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literal@@ -314,6 +314,12 @@ class ProxyConfig:memory_neo4j_uri: str = "neo4j://localhost:7687"memory_neo4j_user: str = "neo4j"memory_neo4j_password: str = "password"+ # Memory Bridge (bidirectional markdown <-> Headroom sync)+ memory_bridge_enabled: bool = False+ memory_bridge_md_paths: list[str] = field(default_factory=list)+ memory_bridge_md_format: str = "auto"+ memory_bridge_auto_import: bool = False+ memory_bridge_export_path: str = ""# Compression Hooks (for SaaS and advanced customization)hooks: Any = None # CompressionHooks instance, or None for default behavior@@ -1241,6 +1247,11 @@ class HeadroomProxy:neo4j_uri=config.memory_neo4j_uri,neo4j_user=config.memory_neo4j_user,neo4j_password=config.memory_neo4j_password,+ bridge_enabled=config.memory_bridge_enabled,+ bridge_md_paths=config.memory_bridge_md_paths,+ bridge_md_format=config.memory_bridge_md_format,+ bridge_auto_import=config.memory_bridge_auto_import,+ bridge_export_path=config.memory_bridge_export_path,)self.memory_handler = MemoryHandler(memory_config)diff --git a/tests/test_memory_bridge.py b/tests/test_memory_bridge.pynew file mode 100644index 000000000..3d698eccb--- /dev/null+++ b/tests/test_memory_bridge.py@@ -0,0 +1,520 @@+"""Tests for the Memory Bridge (markdown <-> Headroom bidirectional sync).++Parser tests are pure functions (no backend needed).+Bridge tests use a temp LocalBackend with a temporary database.++Run with: pytest tests/test_memory_bridge.py -v+"""++from __future__ import annotations++import json+import uuid++import pytest++from headroom.memory.bridge_config import BridgeConfig, MarkdownFormat+from headroom.memory.bridge_parsers import (+ ParsedSection,+ detect_format,+ extract_entities_from_text,+ extract_relationships_from_section,+ parse_chatgpt_facts,+ parse_claude_code_memory,+ parse_generic_markdown,+ parse_markdown,+)++# Sample content for testing+CLAUDE_CODE_MEMORY = """\+# Project Memory++## Project Overview+- **Headroom**: Context optimization layer for LLM applications+- **Repos**: OSS at ~/claude-projects/headroom++## Key Architecture+- 186 Python files, 34 packages, 100K+ lines+- 6 compression algorithms: SmartCrusher, CacheAligner, ContentRouter++## Competitors+- Direct: Compresr (YC W26), Token Company+- Gateways: Portkey, Helicone, LiteLLM+"""++CHATGPT_FACTS = """\+User prefers Python over JavaScript+User works at Netflix+User likes dark mode+- User has a cat named Luna+"""++GENERIC_MARKDOWN = """\+# Notes++## Architecture+The system uses FastAPI for the proxy layer.+- SQLite for storage+- HNSW for vector search++## TODO+- Add caching layer+- Improve error handling+"""+++# =============================================================================+# Parser Tests (pure functions, no backend)+# =============================================================================+++class TestClaudeCodeParser:+ def test_parse_sections(self):+ parsed = parse_claude_code_memory(CLAUDE_CODE_MEMORY)+ # H1 + 3 H2 sections+ assert len(parsed.sections) >= 3+ assert parsed.format == "claude_code"++ def test_heading_levels(self):+ parsed = parse_claude_code_memory(CLAUDE_CODE_MEMORY)+ headings = {s.heading: s.heading_level for s in parsed.sections if s.heading}+ assert headings.get("Project Overview") == 2+ assert headings.get("Key Architecture") == 2+ assert headings.get("Competitors") == 2++ def test_bullets_become_facts(self):+ parsed = parse_claude_code_memory(CLAUDE_CODE_MEMORY)+ overview = next(s for s in parsed.sections if s.heading == "Project Overview")+ assert len(overview.facts) == 2+ assert any("Headroom" in f for f in overview.facts)+ assert any("Repos" in f for f in overview.facts)++ def test_bold_text_extracted_as_entities(self):+ parsed = parse_claude_code_memory(CLAUDE_CODE_MEMORY)+ overview = next(s for s in parsed.sections if s.heading == "Project Overview")+ assert "Headroom" in overview.entities+ assert "Repos" in overview.entities++ def test_content_hash_computed(self):+ parsed = parse_claude_code_memory(CLAUDE_CODE_MEMORY)+ for section in parsed.sections:+ if section.content:+ assert section.content_hash+ assert len(section.content_hash) == 64 # SHA-256++ def test_content_hash_deterministic(self):+ parsed1 = parse_claude_code_memory(CLAUDE_CODE_MEMORY)+ parsed2 = parse_claude_code_memory(CLAUDE_CODE_MEMORY)+ for s1, s2 in zip(parsed1.sections, parsed2.sections):+ assert s1.content_hash == s2.content_hash++ def test_file_hash_computed(self):+ parsed = parse_claude_code_memory(CLAUDE_CODE_MEMORY)+ assert parsed.file_hash+ assert len(parsed.file_hash) == 64+++class TestChatGPTParser:+ def test_parse_flat_facts(self):+ parsed = parse_chatgpt_facts(CHATGPT_FACTS)+ assert parsed.format == "chatgpt"+ assert len(parsed.sections) == 1+ assert len(parsed.sections[0].facts) == 4++ def test_bullet_prefix_stripped(self):+ parsed = parse_chatgpt_facts(CHATGPT_FACTS)+ facts = parsed.sections[0].facts+ assert "User has a cat named Luna" in facts++ def test_empty_lines_skipped(self):+ content = "Fact 1\n\n\nFact 2\n\n"+ parsed = parse_chatgpt_facts(content)+ assert len(parsed.sections[0].facts) == 2++ def test_empty_content(self):+ parsed = parse_chatgpt_facts("")+ assert len(parsed.sections) == 0+++class TestGenericParser:+ def test_parse_multi_level_headers(self):+ parsed = parse_generic_markdown(GENERIC_MARKDOWN)+ assert parsed.format == "generic"+ headings = [s.heading for s in parsed.sections if s.heading]+ assert "Architecture" in headings+ assert "TODO" in headings++ def test_non_bullet_lines_are_facts(self):+ parsed = parse_generic_markdown(GENERIC_MARKDOWN)+ arch = next(s for s in parsed.sections if s.heading == "Architecture")+ # "The system uses FastAPI..." and bullets should all be facts+ assert len(arch.facts) >= 3+++class TestFormatDetection:+ def test_detect_claude_code(self):+ assert detect_format(CLAUDE_CODE_MEMORY) == "claude_code"++ def test_detect_chatgpt(self):+ assert detect_format(CHATGPT_FACTS) == "chatgpt"++ def test_detect_generic(self):+ content = "Some long paragraph without headers or bullet points that goes on and on describing things in great detail.\nAnother very long line that describes more things in this generic format."+ assert detect_format(content) in ("generic", "chatgpt")++ def test_empty_content(self):+ assert detect_format("") == "generic"+++class TestAutoParser:+ def test_auto_parses_claude_code(self):+ parsed = parse_markdown(CLAUDE_CODE_MEMORY)+ assert parsed.format == "claude_code"++ def test_auto_parses_chatgpt(self):+ parsed = parse_markdown(CHATGPT_FACTS)+ assert parsed.format == "chatgpt"++ def test_force_format(self):+ parsed = parse_markdown(CLAUDE_CODE_MEMORY, format="generic")+ assert parsed.format == "generic"+++class TestEntityExtraction:+ def test_bold_text(self):+ entities = extract_entities_from_text("I use **Python** and **FastAPI**")+ assert "Python" in entities+ assert "FastAPI" in entities++ def test_camel_case(self):+ entities = extract_entities_from_text("Using SmartCrusher and CacheAligner")+ assert "SmartCrusher" in entities+ assert "CacheAligner" in entities++ def test_no_false_positives_on_stop_words(self):+ entities = extract_entities_from_text("The system is very important and useful")+ # "The" and other stop words should not appear+ assert "The" not in entities++ def test_all_caps(self):+ entities = extract_entities_from_text("Using HNSW and SQLite")+ assert "HNSW" in entities+++class TestRelationshipExtraction:+ def test_bold_colon_pattern(self):+ section = ParsedSection(+ heading="Test",+ heading_level=2,+ content="- **Headroom**: Context optimization layer",+ facts=["**Headroom**: Context optimization layer"],+ )+ rels = extract_relationships_from_section(section)+ assert len(rels) >= 1+ assert rels[0]["source"] == "Headroom"+ assert rels[0]["relationship"] == "is"++ def test_verb_patterns(self):+ section = ParsedSection(+ heading="Test",+ heading_level=2,+ content="Headroom uses SQLite for storage",+ facts=["Headroom uses SQLite for storage"],+ )+ rels = extract_relationships_from_section(section)+ uses_rels = [r for r in rels if r["relationship"] == "uses"]+ assert len(uses_rels) >= 1+++# =============================================================================+# Bridge Tests (require backend)+# =============================================================================+++def tmp_dir(tmp_path):+ """Provide a temporary directory for test files."""+ return tmp_path+++def user_id():+ """Unique user ID for test isolation."""+ return f"test_bridge_{uuid.uuid4().hex[:8]}"+++def bridge_config(tmp_dir):+ """Create a BridgeConfig with test paths."""+ return BridgeConfig(+ user_id="test_user",+ sync_state_path=tmp_dir / "bridge_state.json",+ dedup_similarity_threshold=0.95,+ )+++async def backend(tmp_dir):+ """Create a LocalBackend with temp database."""+ from headroom.memory.backends.local import LocalBackend, LocalBackendConfig++ config = LocalBackendConfig(db_path=str(tmp_dir / "test_memory.db"))+ backend = LocalBackend(config)+ await backend._ensure_initialized()+ yield backend+ await backend.close()+++def bridge(bridge_config, backend):+ """Create a MemoryBridge."""+ from headroom.memory.bridge import MemoryBridge++ return MemoryBridge(bridge_config, backend)+++class TestMemoryBridgeImport:+ @pytest.mark.asyncio+ async def test_import_claude_code_memory(self, bridge, tmp_dir, backend):+ """Import a MEMORY.md file and verify memories are stored."""+ md_path = tmp_dir / "MEMORY.md"+ md_path.write_text(CLAUDE_CODE_MEMORY, encoding="utf-8")++ stats = await bridge.import_from_markdown(paths=[md_path], user_id="test_user")++ assert stats.files_processed == 1+ assert stats.sections_imported > 0+ assert stats.total_facts > 0++ # Verify memories exist in backend+ memories = await backend.get_user_memories("test_user", limit=100)+ assert len(memories) > 0++ @pytest.mark.asyncio+ async def test_import_skips_unchanged_file(self, bridge, tmp_dir):+ """Second import of same file should skip (hash unchanged)."""+ md_path = tmp_dir / "MEMORY.md"+ md_path.write_text(CLAUDE_CODE_MEMORY, encoding="utf-8")++ stats1 = await bridge.import_from_markdown(paths=[md_path], user_id="test_user")+ assert stats1.sections_imported > 0++ stats2 = await bridge.import_from_markdown(paths=[md_path], user_id="test_user")+ assert stats2.files_skipped_unchanged == 1+ assert stats2.sections_imported == 0++ @pytest.mark.asyncio+ async def test_import_detects_changes(self, bridge, tmp_dir):+ """Modified file should re-import changed sections."""+ md_path = tmp_dir / "MEMORY.md"+ md_path.write_text(CLAUDE_CODE_MEMORY, encoding="utf-8")++ await bridge.import_from_markdown(paths=[md_path], user_id="test_user")++ # Modify file+ modified = CLAUDE_CODE_MEMORY + "\n## New Section\n- Brand new fact\n"+ md_path.write_text(modified, encoding="utf-8")++ stats = await bridge.import_from_markdown(paths=[md_path], user_id="test_user")+ assert stats.files_processed == 1+ assert stats.sections_imported >= 1 # At least the new section++ @pytest.mark.asyncio+ async def test_import_force(self, bridge, tmp_dir):+ """Force import should re-import even if unchanged."""+ md_path = tmp_dir / "MEMORY.md"+ md_path.write_text(CLAUDE_CODE_MEMORY, encoding="utf-8")++ await bridge.import_from_markdown(paths=[md_path], user_id="test_user")++ stats = await bridge.import_from_markdown(paths=[md_path], user_id="test_user", force=True)+ # Force should process the file, though sections may be deduped by semantic search+ assert stats.files_processed == 1++ @pytest.mark.asyncio+ async def test_import_chatgpt_facts(self, bridge, tmp_dir, backend):+ """Import ChatGPT-style facts."""+ md_path = tmp_dir / "chatgpt.txt"+ md_path.write_text(CHATGPT_FACTS, encoding="utf-8")++ bridge._config.md_format = MarkdownFormat.CHATGPT+ stats = await bridge.import_from_markdown(paths=[md_path], user_id="test_user")+ assert stats.sections_imported > 0++ @pytest.mark.asyncio+ async def test_import_missing_file(self, bridge, tmp_dir):+ """Missing file should be skipped gracefully."""+ from pathlib import Path++ stats = await bridge.import_from_markdown(+ paths=[Path(tmp_dir / "nonexistent.md")], user_id="test_user"+ )+ assert stats.files_processed == 0++ @pytest.mark.asyncio+ async def test_metadata_preserved(self, bridge, tmp_dir, backend):+ """Imported memories should have bridge metadata."""+ md_path = tmp_dir / "MEMORY.md"+ md_path.write_text(CLAUDE_CODE_MEMORY, encoding="utf-8")++ await bridge.import_from_markdown(paths=[md_path], user_id="test_user")++ memories = await backend.get_user_memories("test_user", limit=100)+ for memory in memories:+ metadata = memory.metadata or {}+ assert metadata.get("source") == "memory_bridge"+ assert "source_file" in metadata+++class TestMemoryBridgeExport:+ @pytest.mark.asyncio+ async def test_export_claude_code_style(self, bridge, tmp_dir, backend):+ """Export memories as Claude Code style markdown."""+ # Add some memories+ await backend.save_memory(+ content="Headroom is a context optimization layer",+ user_id="test_user",+ importance=0.8,+ metadata={"section_heading": "Overview"},+ )+ await backend.save_memory(+ content="Uses SQLite for storage",+ user_id="test_user",+ importance=0.7,+ metadata={"section_heading": "Architecture"},+ )++ export_path = tmp_dir / "export.md"+ markdown = await bridge.export_to_markdown(+ path=export_path,+ user_id="test_user",+ format=MarkdownFormat.CLAUDE_CODE,+ )++ assert "# Memory" in markdown+ assert "## Overview" in markdown+ assert "## Architecture" in markdown+ assert "Headroom" in markdown+ assert export_path.exists()++ @pytest.mark.asyncio+ async def test_export_chatgpt_style(self, bridge, backend):+ """Export as flat facts."""+ await backend.save_memory(+ content="User prefers Python",+ user_id="test_user",+ importance=0.7,+ )++ markdown = await bridge.export_to_markdown(+ user_id="test_user",+ format=MarkdownFormat.CHATGPT,+ )++ assert "User prefers Python" in markdown+ # Should NOT have headers+ assert "## " not in markdown++ @pytest.mark.asyncio+ async def test_export_empty(self, bridge):+ """Export with no memories should produce placeholder."""+ markdown = await bridge.export_to_markdown(user_id="nonexistent_user")+ assert "No memories" in markdown+++class TestMemoryBridgeSync:+ @pytest.mark.asyncio+ async def test_sync_imports_and_exports(self, bridge, tmp_dir, backend):+ """Full sync: import from file, add organic memory, sync exports it."""+ md_path = tmp_dir / "MEMORY.md"+ md_path.write_text("## Facts\n- User likes Python\n", encoding="utf-8")+ bridge._config.md_paths = [md_path]++ # First sync: imports from file+ stats = await bridge.sync(user_id="test_user")+ assert stats.import_stats.sections_imported > 0++ # Add an organic memory (not from bridge)+ await backend.save_memory(+ content="User also likes Rust",+ user_id="test_user",+ importance=0.7,+ metadata={}, # No source tag = organic+ )++ # Second sync: should export the organic memory+ stats2 = await bridge.sync(user_id="test_user")+ assert stats2.memories_exported >= 1++ # Verify the file now contains the new memory+ updated_content = md_path.read_text(encoding="utf-8")+ assert "Rust" in updated_content++ @pytest.mark.asyncio+ async def test_source_tag_prevents_reexport(self, bridge, tmp_dir, backend):+ """Memories imported via bridge should not be re-exported."""+ md_path = tmp_dir / "MEMORY.md"+ md_path.write_text("## Facts\n- Imported fact\n", encoding="utf-8")+ bridge._config.md_paths = [md_path]++ # Import+ await bridge.sync(user_id="test_user")++ # Sync again - nothing should be exported (all memories have source tag)+ stats = await bridge.sync(user_id="test_user")+ assert stats.memories_exported == 0+++class TestSyncStatePersistence:+ @pytest.mark.asyncio+ async def test_state_saved_and_loaded(self, tmp_dir, backend):+ """Sync state should persist across bridge instances."""+ from headroom.memory.bridge import MemoryBridge++ state_path = tmp_dir / "state.json"+ config = BridgeConfig(+ user_id="test_user",+ sync_state_path=state_path,+ )++ md_path = tmp_dir / "MEMORY.md"+ md_path.write_text(CLAUDE_CODE_MEMORY, encoding="utf-8")++ # First bridge instance: import+ bridge1 = MemoryBridge(config, backend)+ await bridge1.import_from_markdown(paths=[md_path], user_id="test_user")++ # Verify state file exists+ assert state_path.exists()+ state = json.loads(state_path.read_text())+ assert "files" in state+ assert str(md_path) in state["files"]++ # Second bridge instance: should detect unchanged file+ bridge2 = MemoryBridge(config, backend)+ stats = await bridge2.import_from_markdown(paths=[md_path], user_id="test_user")+ assert stats.files_skipped_unchanged == 1+++class TestRoundTrip:+ @pytest.mark.asyncio+ async def test_import_export_preserves_facts(self, bridge, tmp_dir, backend):+ """Import a MEMORY.md, export it, verify all facts are present."""+ md_path = tmp_dir / "MEMORY.md"+ md_path.write_text(CLAUDE_CODE_MEMORY, encoding="utf-8")++ # Import+ await bridge.import_from_markdown(paths=[md_path], user_id="test_user")++ # Export+ export_path = tmp_dir / "exported.md"+ markdown = await bridge.export_to_markdown(+ path=export_path,+ user_id="test_user",+ format=MarkdownFormat.CLAUDE_CODE,+ )++ # Key facts should survive the round trip+ assert "Headroom" in markdown+ assert "compression" in markdown.lower() or "SmartCrusher" in markdown+ assert "Compresr" in markdown or "Portkey" in markdown