### Development Installation Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/installation.md Clones the repository and installs dependencies in editable mode with pre-commit hooks. ```bash # Clone the repository git clone https://github.com/zhangfengcdt/memoir.git cd memoir # Install in development mode with all dependencies pip install -e ".[dev,docs]" # Install pre-commit hooks make pre-commit ``` -------------------------------- ### Run Versioning Control Examples Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/examples.md Execute the provided example scripts to observe versioning control behavior. ```bash python examples/versioning_control_example.py python examples/versioning_control.py ``` -------------------------------- ### Initialize development environment Source: https://github.com/zhangfengcdt/memoir/blob/main/CLAUDE.md Activate the virtual environment and install dependencies for the first time. ```bash source venv/bin/activate # or `python -m venv venv && source venv/bin/activate` make install-dev # first time only ``` -------------------------------- ### Install for development Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/quickstart.md Install the package in editable mode with development dependencies. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Verify Installation Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/installation.md Checks the installed version and imports core components to ensure the environment is set up correctly. ```python import memoir print(f"Memoir version: {memoir.__version__}") # Test basic components from memoir import ProllyTreeStore, SemanticClassifier print("Installation successful!") ``` -------------------------------- ### Install Memoir via uv Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/installation.md Installs Memoir as a persistent tool or runs it ephemerally without installation. ```bash # Persistent install (recommended for daily use) uv tool install memoir-ai # OR — try without installing (one-shot, ephemeral venv) uvx --from memoir-ai memoir --help ``` -------------------------------- ### Install Memoir CLI Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/quickstart.md Options for installing the Memoir CLI tool using uv or pip. ```bash # 1. Try without installing (one-shot, ephemeral venv managed by uv) uvx --from memoir-ai memoir --help # 2. Persistent install with uv — faster than pip, isolates the CLI uv tool install memoir-ai # 3. Universal fallback (only if you can't or don't want to use uv) pip install memoir-ai ``` -------------------------------- ### Install Memoir Watch Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/watch.md Install the required dependencies for the watch feature using pip. ```bash pip install 'memoir-ai[watch]' ``` -------------------------------- ### Complete Memoir Setup and Usage Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/basic_usage.md Demonstrates the full lifecycle of initializing Memoir components, storing semantic memories, and performing intelligent searches. ```python import asyncio import os import tempfile from langchain_openai import ChatOpenAI from memoir import ProllyTreeMemoryStoreManager from memoir.classifier.intelligent import IntelligentClassifier from memoir.search.intelligent import IntelligentSearchEngine from memoir.taxonomy.taxonomy import TaxonomyVersion async def main(): # 1. Set up LLM llm = ChatOpenAI( model="gpt-4o-mini", temperature=0, max_tokens=500 ) # 2. Create components in dependency order # Step 1: Storage layer (pure storage, no business logic) from memoir.store.prolly_adapter import ProllyTreeStore prolly_store = ProllyTreeStore( path="/tmp/memory_store", enable_versioning=True, cache_size=10000 ) # Step 2: Classification layer (depends on LLM) classifier = IntelligentClassifier( llm=llm, taxonomy_version=TaxonomyVersion.GENERAL, confidence_thresholds={ "high": 0.8, # High confidence - store immediately "medium": 0.5, # Medium confidence - good memories "low": 0.0 # Low threshold - reject below this } ) # Step 3: Search engine (depends on LLM + store) search_engine = IntelligentSearchEngine( llm=llm, store=prolly_store ) # Step 4: Memory manager (orchestrates all components) memory_manager = ProllyTreeMemoryStoreManager( prolly_store=prolly_store, classifier=classifier, search_engine=search_engine, enable_versioning=True ) # 3. Store memories with semantic classification user_id = "user123" memories_to_store = [ "My name is Sarah Johnson and I'm 32 years old.", "I work as a senior software engineer at TechCorp in San Francisco.", "I prefer dark mode in all my development environments.", "My primary programming language is Python, but I also use JavaScript.", "I drink coffee every morning, specifically a double espresso with oat milk.", "I have 8 years of experience in machine learning and data science.", "My favorite IDE is VS Code with the Monokai Pro theme.", "I graduated from Stanford University with a Computer Science degree in 2014.", ] for memory_text in memories_to_store: semantic_key = await memory_manager.store_memory( content=memory_text, namespace=user_id, metadata={"source": "demo"}, auto_classify=True ) print(f"Stored: {memory_text[:40]}...") print(f"Path: {semantic_key}") # 4. Search for memories queries = [ "What is the user's name and age?", "Where does the user work and what is their role?", "What are the user's IDE and theme preferences?", "What does the user drink in the morning?", ] for query in queries: results = await memory_manager.search_memories( query=query, namespace=user_id, limit=5 ) print(f"\nQuery: '{query}'") if results: best_result = results[0] print(f"Found: {best_result.content}") print(f"Path: {best_result.id}") else: print("No matches found") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install and Configure Memoir Plugin Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/openclaw.md Install the plugin from a remote repository or a local path, and manually set the memory slot. ```bash openclaw plugins install https://github.com/zhangfengcdt/openclaw-memoir # …or link a local checkout while developing openclaw plugins install --link /path/to/openclaw-memoir ``` ```bash openclaw config set plugins.slots.memory memory-memoir ``` -------------------------------- ### Install Memoir via pip Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/installation.md Standard installation method using the pip package manager. ```bash pip install memoir-ai ``` -------------------------------- ### Execute Context Branching Example Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/examples/context_branching.md Run the provided Python script to initiate the context branching demonstration. ```bash python examples/context_branching.py ``` -------------------------------- ### Execute Debugging Example Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/examples/production_debugging.md Command to run the production debugging demonstration script. ```bash python examples/production_debugging.py ``` -------------------------------- ### Install uv Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/installation.md Installs the uv package manager for faster CLI installation and environment isolation. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Install Hermes Plugin Source: https://github.com/zhangfengcdt/memoir/blob/main/README.md Commands to install and configure the Memoir plugin for the Hermes agent. ```bash hermes plugins install zhangfengcdt/memoir/plugins/hermes # or: cp -r plugins/hermes ~/.hermes/plugins/memoir hermes memory setup # choose "memoir" ``` -------------------------------- ### Install Memoir Dependencies Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/examples.md Install the required langchain-openai and memoir-ai packages via pip. ```bash pip install langchain-openai memoir-ai ``` -------------------------------- ### Install OpenClaw Plugin Source: https://github.com/zhangfengcdt/memoir/blob/main/README.md Commands to install the Memoir plugin into OpenClaw and configure gateway access. ```bash openclaw plugins install https://github.com/zhangfengcdt/openclaw-memoir # or: --link /path/to/openclaw-memoir openclaw config set plugins.entries.memory-memoir.hooks.allowConversationAccess true systemctl --user restart openclaw-gateway ``` -------------------------------- ### Setup LoCoMo Benchmark Environment Source: https://github.com/zhangfengcdt/memoir/blob/main/benchmarks/locomo/README.md Clone the benchmark repository and configure the required environment variables. ```bash git clone https://github.com/xjtuleeyf/Locomo-Plus.git /tmp/locomo-bench/Locomo-Plus source venv/bin/activate export OPENAI_API_KEY=... # or: set -a && . .env.local && set +a ``` -------------------------------- ### Smoke-test installation Source: https://github.com/zhangfengcdt/memoir/blob/main/RELEASING.md Commands to verify the package installation from TestPyPI in a clean virtual environment. ```bash python -m venv /tmp/memoir-test /tmp/memoir-test/bin/pip install \ -i https://test.pypi.org/simple/ \ --extra-index-url https://pypi.org/simple/ \ memoir-ai==X.Y.Z /tmp/memoir-test/bin/memoir --help /tmp/memoir-test/bin/python -c "import memoir; print(memoir.__version__)" ``` -------------------------------- ### Install the plugin via Hermes CLI Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/hermes.md Install the plugin directly from the repository using the Hermes command-line interface. ```bash hermes plugins install zhangfengcdt/memoir/plugins/hermes ``` -------------------------------- ### Handle Namespaces Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/theory/search.md Examples of defining and converting between string and tuple namespace formats. ```python # String format namespace = "user:alice" # Tuple format namespace = ("user", "alice") # Conversion namespace_tuple = tuple(namespace.split(":")) ``` -------------------------------- ### Execute Memoir Examples Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/examples.md Run the provided Python scripts to demonstrate core Memoir capabilities. ```bash # Fast demos (no LLM required) python examples/context_branching.py python examples/memory_state_debugging.py python examples/reproducible_testing.py python examples/production_debugging.py python examples/versioning_control_example.py python examples/versioning_control.py ``` -------------------------------- ### Install and Run Memoir MCP Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/mcp.md Commands to install the package via pip or run it on-demand using uvx. ```bash pip install "memoir-ai[mcp]" # or: pipx install "memoir-ai[mcp]" ``` ```bash MEMOIR_STORE=~/.memoir/mcp memoir-mcp ``` ```bash uvx --from "memoir-ai[mcp]" memoir-mcp ``` -------------------------------- ### Run Reproducible Testing Example Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/examples/reproducible_testing.md Execute the provided Python script to initiate the reproducible testing demonstration. ```bash python examples/reproducible_testing.py ``` -------------------------------- ### Install Optional Dependencies Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/installation.md Installs specific extras for terminal UI, memory storage, or all features. ```bash pip install 'memoir-ai[tui]' # Terminal UI (textual-based) pip install 'memoir-ai[langmem]' # ProllyTreeMemoryStoreManager (LangMem drop-in) pip install 'memoir-ai[all]' # tui + langmem + litellm ``` -------------------------------- ### Launch the Memoir UI Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/ui.md Commands to start the UI server with various configuration options like semantic search and custom ports. ```bash # Connect to an existing store memoir ui /path/to/store # Enable semantic search in the UI's command input memoir ui /path/to/store --usellm # Custom port (default: 8080) memoir ui /path/to/store --port 8081 ``` -------------------------------- ### Install Memoir via pipx Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/installation.md Installs the Memoir CLI using pipx for isolated environment management. ```bash pipx install memoir-ai ``` -------------------------------- ### Install the plugin by manual copy Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/hermes.md Manually copy the plugin directory from a local checkout to the Hermes plugins folder. ```bash cp -r plugins/hermes ~/.hermes/plugins/memoir rm -rf ~/.hermes/plugins/memoir/tests ~/.hermes/plugins/memoir/__pycache__ ``` -------------------------------- ### Launch the memoir UI Source: https://github.com/zhangfengcdt/memoir/blob/main/plugins/claude-code/commands/ui.md Executes the control script to start or reuse the memoir web server. ```bash bash "${CLAUDE_PLUGIN_ROOT}/scripts/memoir-ui-ctl.sh" start "" ``` -------------------------------- ### Profile Summary Generation Examples Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/theory/memento.md Examples of structured and narrative summary formats for user profile data. ```text === USER PROFILE SUMMARY === Personal Information: Identity: - Name: John Smith - Age: 25 - Gender Identity: Male Professional Profile: Current: - Company Name: Google - Position Title: Software Engineer ``` ```text John Smith is a 25-year-old software engineer currently working at Google. His professional journey reflects a strong technical background... ``` -------------------------------- ### Run Memory State Debugging Example Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/examples/memory_debugging.md Execute the provided Python script to demonstrate memory state tracking and debugging. ```bash python examples/memory_state_debugging.py ``` -------------------------------- ### Install and Uninstall Plugin Hooks Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/codex.md Use the provided script to install or uninstall Memoir's bundled hooks into the user hooks file. ```bash PLUGIN_ROOT=$(find "${CODEX_HOME:-$HOME/.codex}/plugins/cache" \ -path '*/memoir/memoir/*/.codex-plugin/plugin.json' -print -quit \ | sed 's#/.codex-plugin/plugin.json$##') bash "$PLUGIN_ROOT/scripts/install-codex-hooks.sh" ``` ```bash bash "$PLUGIN_ROOT/scripts/install-codex-hooks.sh" uninstall ``` -------------------------------- ### Start Memoir MCP Server with HTTP Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/mcp.md Run the server using Streamable HTTP to allow remote connections from web-based tiers. ```bash memoir-mcp --http --host 0.0.0.0 --port 8000 # serves at /mcp ``` -------------------------------- ### Visualize the directory structure Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/openclaw.md An example of the directory layout for an agent named 'main' and a second agent named 'research'. ```text ~/.openclaw/memoir/main # agent "main" (store) ├── profile-main # scope=profile (your facts) ├── default # shared across scopes └── taxonomy # built-in ~/.openclaw/memoir/research # a second agent → separate store ``` -------------------------------- ### Activate the memoir provider Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/hermes.md Use the interactive setup command to configure Hermes to use Memoir as the active memory provider. ```bash hermes memory setup # interactive picker — choose "memoir" ``` -------------------------------- ### Install Claude Code Plugin Source: https://github.com/zhangfengcdt/memoir/blob/main/README.md Commands to add and install the Memoir plugin within a Claude Code session. ```bash /plugin marketplace add zhangfengcdt/memoir /plugin install memoir@memoir ``` -------------------------------- ### Semantic Path Classification Example Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/basic_usage.md Demonstrates how input text is mapped to a hierarchical semantic path for storage. ```python # Input: "My name is Sarah Johnson" # Classification: profile.identity.name.full # Storage: Aggregated with other name-related memories ``` -------------------------------- ### Construct LLM Path Selection Prompt Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/theory/search.md Generates a prompt containing query and path context to guide the LLM in selecting relevant memory paths. ```python prompt = f"""Given this search query: "{query}" Please select the most relevant memory paths from: - profile.personal.identity (5 memories): John Smith, age 28... - preferences.technology.programming (3 memories): Loves Python... - context.conversation.history (10 memories): Discussed AI... Instructions: - Select 1-3 paths most relevant to query - Return ONLY path names, one per line - If no paths relevant, return "NONE" """ ``` -------------------------------- ### Initialize Development Environment Source: https://github.com/zhangfengcdt/memoir/blob/main/CONTRIBUTING.md Commands to clone the repository and set up the virtual environment with dependencies. ```bash git clone https://github.com/zhangfengcdt/memoir.git cd memoir python -m venv venv && source venv/bin/activate make install-dev ``` -------------------------------- ### Execute /memoir commands Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/hermes.md Examples of slash commands available for inspecting memory state directly within the chat session. ```text /memoir status /memoir summarize --depth 3 /memoir recall "travel plans" /memoir branch /memoir blame profile.personal.identity ``` -------------------------------- ### UI control script output format Source: https://github.com/zhangfengcdt/memoir/blob/main/plugins/claude-code/commands/ui.md Example of the single-line JSON document printed to stdout by the UI control script. ```json {"pid": 12345, "port": 62891, "url": "http://localhost:62891/?store=…&readonly=1&usellm=0", "store": "/abs/path", "started": "...", "log": "/tmp/...", "reused": false} ``` -------------------------------- ### Classification Bug Fix Example Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/faq.md A complete walkthrough of identifying a conflict, creating a fix branch, applying a rule, and validating the result. ```python # Scenario: Agent incorrectly classifies "I love Python programming" # 1. Instant time-travel to bug occurrence memory.branch.checkout("classification_bug_2024_01_15_14_30") # 2. Claude Code analyzes: "I see the issue!" bug_analysis = await memory.recall("programming AND personal") # Finds conflicting memories: # - "programming is hobby" (personal.hobbies.programming) # - "Python for work" (profile.professional.skills.python) # 3. Create fix branch and test solution memory.branch.create("fix_programming_context") # 4. Claude Code applies nuanced fix: await memory.remember( "Context: 'I love X programming' indicates professional skill when discussing career", namespace="classification.rules.programming_context" ) # 5. Test fix immediately on same memory state test_result = agent.classify("I love Python programming") assert test_result.path == "profile.professional.skills.python" # Fixed! # 6. Validate doesn't break other classifications # 7. Merge fix to main - total time: minutes instead of hours! ``` -------------------------------- ### Initialize Memory System Components Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/quickstart.md Sets up the storage layer, classifier, search engine, and the main memory manager. ```python from memoir.store.prolly_adapter import ProllyTreeStore from memoir.classifier.intelligent import IntelligentClassifier from memoir.search.intelligent import IntelligentSearchEngine from memoir import ProllyTreeMemoryStoreManager # Create storage layer store = ProllyTreeStore( path="./memory_store", enable_versioning=True ) # Create intelligent classifier classifier = IntelligentClassifier( llm=llm, confidence_thresholds={ "high": 0.8, "medium": 0.5, "low": 0.0 } ) # Create search engine search_engine = IntelligentSearchEngine( llm=llm, store=store ) # Assemble memory manager memory_manager = ProllyTreeMemoryStoreManager( prolly_store=store, classifier=classifier, search_engine=search_engine ) ``` -------------------------------- ### Current Workflow Pain Points Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/faq.md An example of the manual, time-consuming process required to debug classification agents without Memoir. ```text # Current workflow when Claude Code finds a classification bug: 1. Agent classifies "I love Python programming" → wrong path: "personal.hobbies.python" 2. Claude Code identifies the issue 3. Must rebuild ALL memories from scratch (hours of work) 4. Or write complex test cases that may miss edge cases 5. Hard to reproduce exact memory state that caused the bug 6. Risk breaking other correctly working classifications ``` -------------------------------- ### Perform direct memory lookups Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/cli.md Use the get command for fast, exact key retrieval. Missing keys return a found: false status, making it suitable for batch operations. ```bash # Single lookup memoir get preferences.coding.style # Batched lookup in one call memoir get preferences.coding.style profile.professional.skills # Scope to a namespace, JSON output memoir --json get preferences.coding.style -n default ``` -------------------------------- ### Initialize ProllyTreeStore with Versioning Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/examples/memory_debugging.md Sets up the store in a temporary directory with versioning enabled and a defined cache size. ```python import asyncio import os import tempfile import time from datetime import datetime from memoir.store.prolly_adapter import ProllyTreeStore # Initialize store with versioning temp_dir = tempfile.mkdtemp() prolly_path = os.path.join(temp_dir, "memory_store") prolly_store = ProllyTreeStore( path=prolly_path, enable_versioning=True, cache_size=10000, ) # Track commit history with timestamps commit_history = [] ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/installation.md Commands for building, serving, and cleaning the documentation site. ```bash # Build the static site into ./site make docs # Start the live-reload dev server make docs-live # Clean the build output make docs-clean ``` -------------------------------- ### Initialize Production Memory Store Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/examples/production_debugging.md Sets up a ProllyTreeStore with versioning enabled and populates it with initial user memories. ```python import asyncio import os import tempfile import time from datetime import datetime, timedelta from memoir.store.prolly_adapter import ProllyTreeStore # Initialize production memory store temp_dir = tempfile.mkdtemp() prolly_path = os.path.join(temp_dir, "memory_store") prolly_store = ProllyTreeStore( path=prolly_path, enable_versioning=True, cache_size=10000, ) namespace = "production_user" # Simulate 6 months of accumulated memories base_memories = [ ("User prefers dark theme for all interfaces", "preferences.ui.theme"), ("User typically works 9-5 PST timezone", "profile.schedule.work_hours"), ("User has accessibility needs for high contrast", "preferences.accessibility.contrast"), # ... 144 total memories accumulated over 6 months ] for content, path in base_memories: await prolly_store.store_memory_async(namespace, content, path) # Create checkpoint at 145 memories initial_checkpoint = f"checkpoint_{int(time.time())}" prolly_store.create_time_snapshot(initial_checkpoint) ``` -------------------------------- ### Initialize Plugin Environment Variables Source: https://github.com/zhangfengcdt/memoir/blob/main/plugins/codex/skills/memoir-onboard/SKILL.md Sets up the PLUGIN_ROOT, STORE_PATH, and MEMOIR variables required for consistent CLI execution. ```bash PLUGIN_ROOT="${PLUGIN_ROOT:-}" if [ -z "$PLUGIN_ROOT" ]; then PLUGIN_ROOT=$(find "${CODEX_HOME:-$HOME/.codex}/plugins" -path '*/.codex-plugin/plugin.json' -print 2>/dev/null \ | while IFS= read -r manifest; do python3 - "$manifest" <<'PY' import json, sys from pathlib import Path path = Path(sys.argv[1]) try: data = json.loads(path.read_text()) except Exception: raise SystemExit(0) if data.get("name") == "memoir": print(path.parent.parent) PY done | head -n 1) fi STORE_PATH="${MEMOIR_STORE:-$(bash "${PLUGIN_ROOT}/scripts/derive-store-path.sh")}" MEMOIR="${PLUGIN_ROOT}/scripts/memoir-cli.sh" ``` -------------------------------- ### Initialize and Use Memoir Memory Manager Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/index.md Demonstrates setting up the memory store, classifier, and search engine, followed by storing and searching for memories. ```python from memoir import ProllyTreeMemoryStoreManager from memoir.classifier.intelligent import IntelligentClassifier from memoir.search.intelligent import IntelligentSearchEngine # Initialize components with dependency injection store = ProllyTreeStore(path="./memory_store") classifier = IntelligentClassifier(llm=llm) search_engine = IntelligentSearchEngine(llm=llm, store=store) # Create memory manager memory_manager = ProllyTreeMemoryStoreManager( prolly_store=store, classifier=classifier, search_engine=search_engine ) # Store memories with automatic classification await memory_manager.store_memory( content="I work as a senior software engineer at TechCorp", namespace="user123", auto_classify=True ) # Search with intelligent path selection results = await memory_manager.search_memories( query="What is the user's job?", namespace="user123" ) ``` -------------------------------- ### Initialize IntelligentSearchEngine Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/architecture.md Configures the search engine using an LLM and the existing storage instance. ```python # Intelligent LLM-powered search from memoir.search.intelligent import IntelligentSearchEngine search_engine = IntelligentSearchEngine(llm=llm, store=store) ``` -------------------------------- ### Initialize Memory Store with Versioning Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/examples/context_branching.md Sets up the ProllyTreeStore with versioning enabled to support branching features. ```python import asyncio import os import tempfile import time from memoir.store.prolly_adapter import ProllyTreeStore # Create memory store with versioning enabled temp_dir = tempfile.mkdtemp() prolly_path = os.path.join(temp_dir, "memory_store") prolly_store = ProllyTreeStore( path=prolly_path, enable_versioning=True, # Enable Git-like features cache_size=10000, ) ``` -------------------------------- ### Extract Location Events Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/theory/classifier.md Example of capturing geographic references from content. ```python Captures geographic references: - "The support group in Los Angeles" → location: "Los Angeles", description: "support group attendance" ``` -------------------------------- ### memoir get Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/theory/search.md Performs a batched exact-path lookup for memory keys. ```APIDOC ## memoir get ### Description Performs a batched exact-path lookup. If a key is missing, it returns 'found: false' instead of an error. ### Parameters - **key** (string) - Required - One or more keys to retrieve. - **-n** (string) - Optional - The namespace to search within. ``` -------------------------------- ### Initialize ProllyTreeStore Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/architecture.md Configures the storage layer with versioning and cache settings. ```python from memoir.store.prolly_adapter import ProllyTreeStore store = ProllyTreeStore( path="./memory_store", enable_versioning=True, cache_size=10000 ) ``` -------------------------------- ### Execute Cold Path Onboarding Extraction and Storage Source: https://github.com/zhangfengcdt/memoir/blob/main/plugins/codex/skills/memoir-onboard/SKILL.md Performs project analysis using extractors and stores the resulting data into the Memoir system. Ensure the environment variables like STORE_PATH and MEMOIR are correctly set before execution. ```bash ROOT="$(pwd)" WALK_JSON=$(python3 ${PLUGIN_ROOT}/skills/memoir-onboard/extractors.py walk "$ROOT") SNAPSHOT_HASH=$(python3 -c "import json,sys; print(json.loads(sys.argv[1])['snapshot_hash'])" "$WALK_JSON") SHAPE_JSON=$(python3 ${PLUGIN_ROOT}/skills/memoir-onboard/extractors.py shape "$ROOT") SHAPE=$(python3 -c "import json,sys; print(json.loads(sys.argv[1])['shape'])" "$SHAPE_JSON") OVERVIEW=$(python3 -c "import json,sys; print(json.loads(sys.argv[1])['overview'])" "$SHAPE_JSON") TREE=$(python3 ${PLUGIN_ROOT}/skills/memoir-onboard/extractors.py tree "$ROOT") FILE_COUNT=$(python3 -c "import json,sys; print(len(json.loads(sys.argv[1])['files']))" "$WALK_JSON") # Every memoir write below is wrapped in `( cd "$STORE_PATH" && ... )` — # without this the prollytree backend reads cwd for git ops and the writes # silently land in memoir's connected default store. See "CRITICAL: how to # invoke memoir from this skill" at the top of Branch B. ( cd "$STORE_PATH" && "$MEMOIR" -s "$STORE_PATH" remember "$OVERVIEW" -p summary.overview -n project:onboard ) ( cd "$STORE_PATH" && "$MEMOIR" -s "$STORE_PATH" remember "$SHAPE" -p structure.shape -n project:onboard ) ( cd "$STORE_PATH" && "$MEMOIR" -s "$STORE_PATH" remember "$TREE" -p structure.tree -n project:onboard ) # For each entry in WALK_JSON.files, drive the loop with bash. Sanitize each # relative path with `/` → `_` and `.` → `_` (matches extractors.sanitize_path). python3 -c "import json,sys; print('\n'.join(e['path'] for e in json.loads(sys.argv[1])['files']))" "$WALK_JSON" \ | while IFS= read -r rel; do sanitized=$(printf '%s' "$rel" | tr '/.' '__') meta_blob=$(python3 -c "import json,sys; files=json.loads(sys.argv[1])['files']; e=next(f for f in files if f['path']==sys.argv[2]); print('\n'.join(f'{k}={v}' for k,v in sorted(e.items())))" "$WALK_JSON" "$rel") summary_blob=$(python3 ${PLUGIN_ROOT}/skills/memoir-onboard/extractors.py extract "$ROOT/$rel") ( cd "$STORE_PATH" && "$MEMOIR" -s "$STORE_PATH" remember "$meta_blob" -p "files.${sanitized}.meta" -n project:onboard ) >/dev/null ( cd "$STORE_PATH" && "$MEMOIR" -s "$STORE_PATH" remember "$summary_blob" -p "files.${sanitized}.summary" -n project:onboard ) >/dev/null done ``` -------------------------------- ### Generate Hierarchical Summary Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/theory/memento.md Example output format for the hierarchical timeline summary. ```text === USER TIMELINE === 2023: December: 01: Promoted to senior engineer June: 20: Attended AI conference | Met Dr. Smith as mentor March: 15: Started new job at Google 14: Last day at previous company ``` -------------------------------- ### Extract Timeline Events Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/theory/classifier.md Example of temporal event extraction with date calculation. ```python Extracts temporal events with date calculation: - "Yesterday was my first day" (session: 2023-03-15) → date: "20230314", description: "first day at new job" ``` -------------------------------- ### Initialize LLM Client Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/quickstart.md Configures the LLM client using environment variables and the get_llm helper. ```python import os from memoir.llm import get_llm os.environ["ANTHROPIC_API_KEY"] = "your-api-key-here" # memoir.llm.get_llm() routes through litellm (a default dep as of v0.1.7). llm = get_llm(model="claude-haiku-4-5", temperature=0) ``` -------------------------------- ### get Source: https://github.com/zhangfengcdt/memoir/blob/main/plugins/claude-code/skills/memory-recall/SKILL.md Retrieves specific memory items based on provided paths. ```APIDOC ## CLI Command: get ### Description Queries memory items by path. Batching multiple paths is supported. ### Usage `$MEMOIR --json -s $STORE get [...] -n default` ### Response Returns an array of items, each containing: `key`, `namespace`, `full_key`, `found`, and `value`. ``` -------------------------------- ### GET /api/recall Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/theory/search.md Retrieves memory data based on a query and a specified retrieval mode. ```APIDOC ## GET /api/recall ### Description Retrieves memory information using a specified retrieval mode. The mode parameter is whitelisted to 'single' or 'tiered'. ### Method GET ### Endpoint /api/recall ### Parameters #### Query Parameters - **path** (string) - Required - The path context for the recall. - **query** (string) - Required - The search query string. - **mode** (string) - Required - The retrieval mode, either 'single' or 'tiered'. ``` -------------------------------- ### summarize Source: https://github.com/zhangfengcdt/memoir/blob/main/plugins/claude-code/skills/memory-recall/SKILL.md Provides a summary of the memory store, typically used as a starting point for queries. ```APIDOC ## CLI Command: summarize ### Description Performs a single-shot summary of the memory store. It returns a taxonomy listing and total memory count. ### Usage `$MEMOIR --json -s $STORE summarize --depth 3 -n default` ### Response Returns `total_memories` and `prefix_counts` (a listing of full L1.L2.L3 key paths). ``` -------------------------------- ### Execute Cold Path Onboarding Data Extraction and Storage Source: https://github.com/zhangfengcdt/memoir/blob/main/plugins/claude-code/skills/memoir-onboard/SKILL.md Performs project directory analysis and stores the resulting metadata and summaries into the Memoir store. Ensure the environment variables CLAUDE_PLUGIN_ROOT, STORE_PATH, and MEMOIR are correctly set before execution. ```bash ROOT="$(pwd)" WALK_JSON=$(python3 ${CLAUDE_PLUGIN_ROOT}/skills/memoir-onboard/extractors.py walk "$ROOT") SNAPSHOT_HASH=$(python3 -c "import json,sys; print(json.loads(sys.argv[1])['snapshot_hash'])" "$WALK_JSON") SHAPE_JSON=$(python3 ${CLAUDE_PLUGIN_ROOT}/skills/memoir-onboard/extractors.py shape "$ROOT") SHAPE=$(python3 -c "import json,sys; print(json.loads(sys.argv[1])['shape'])" "$SHAPE_JSON") OVERVIEW=$(python3 -c "import json,sys; print(json.loads(sys.argv[1])['overview'])" "$SHAPE_JSON") TREE=$(python3 ${CLAUDE_PLUGIN_ROOT}/skills/memoir-onboard/extractors.py tree "$ROOT") FILE_COUNT=$(python3 -c "import json,sys; print(len(json.loads(sys.argv[1])['files']))" "$WALK_JSON") # Every memoir write below is wrapped in `( cd "$STORE_PATH" && ... )` — # without this the prollytree backend reads cwd for git ops and the writes # silently land in memoir's connected default store. See "CRITICAL: how to # invoke memoir from this skill" at the top of Branch B. ( cd "$STORE_PATH" && "$MEMOIR" -s "$STORE_PATH" remember "$OVERVIEW" -p summary.overview -n project:onboard ) ( cd "$STORE_PATH" && "$MEMOIR" -s "$STORE_PATH" remember "$SHAPE" -p structure.shape -n project:onboard ) ( cd "$STORE_PATH" && "$MEMOIR" -s "$STORE_PATH" remember "$TREE" -p structure.tree -n project:onboard ) # For each entry in WALK_JSON.files, drive the loop with bash. Sanitize each # relative path with `/` → `_` and `.` → `_` (matches extractors.sanitize_path). python3 -c "import json,sys; print('\n'.join(e['path'] for e in json.loads(sys.argv[1])['files']))" "$WALK_JSON" \ | while IFS= read -r rel; do sanitized=$(printf '%s' "$rel" | tr '/.' '__') meta_blob=$(python3 -c "import json,sys; files=json.loads(sys.argv[1])['files']; e=next(f for f in files if f['path']==sys.argv[2]); print('\n'.join(f'{k}={v}' for k,v in sorted(e.items())))" "$WALK_JSON" "$rel") summary_blob=$(python3 ${CLAUDE_PLUGIN_ROOT}/skills/memoir-onboard/extractors.py extract "$ROOT/$rel") ( cd "$STORE_PATH" && "$MEMOIR" -s "$STORE_PATH" remember "$meta_blob" -p "files.${sanitized}.meta" -n project:onboard ) >/dev/null ( cd "$STORE_PATH" && "$MEMOIR" -s "$STORE_PATH" remember "$summary_blob" -p "files.${sanitized}.summary" -n project:onboard ) >/dev/null done ``` -------------------------------- ### Run the container interactively Source: https://github.com/zhangfengcdt/memoir/blob/main/plugins/docker-tests/hermes/README.md Starts the container in interactive mode for manual debugging and exploration. ```bash docker run --rm -it -e ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" hermes-memoir-test bash ``` -------------------------------- ### Extract Profile Updates Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/theory/classifier.md Examples of mapping definitive personal facts to specific profile paths. ```python Detects definitive facts that replace previous information: - "I'm 25 years old" → profile.personal.identity.age.current - "I work at Google" → profile.professional.current.company.name ``` -------------------------------- ### Initialize Store Path and CLI Wrapper Source: https://github.com/zhangfengcdt/memoir/blob/main/plugins/claude-code/skills/memory-recall/SKILL.md Sets the storage path and defines the CLI wrapper command to ensure consistent execution across different environments. ```bash STORE="${MEMOIR_STORE:-$(bash "$CLAUDE_PLUGIN_ROOT/scripts/derive-store-path.sh")}" MEMOIR="$CLAUDE_PLUGIN_ROOT/scripts/memoir-cli.sh" ``` -------------------------------- ### Manage Claude Code Plugin Source: https://github.com/zhangfengcdt/memoir/blob/main/CONTRIBUTING.md Commands for installing, updating, and uninstalling the local Claude Code plugin. ```text /plugin marketplace add /absolute/path/to/memoir /plugin install memoir@memoir ``` ```text /plugin marketplace update memoir # re-read the local marketplace ``` ```text /plugin uninstall memoir@memoir /plugin marketplace remove memoir ``` -------------------------------- ### Initialize Memoir Environment Variables Source: https://github.com/zhangfengcdt/memoir/blob/main/plugins/codex/skills/memory-recall/SKILL.md Configures the plugin root, store path, and CLI wrapper path. This preamble must be executed before any memoir commands to ensure correct environment resolution. ```bash PLUGIN_ROOT="${PLUGIN_ROOT:-}" if [ -z "$PLUGIN_ROOT" ]; then PLUGIN_ROOT=$(find "${CODEX_HOME:-$HOME/.codex}/plugins" -path '*/.codex-plugin/plugin.json' -print 2>/dev/null \ | while IFS= read -r manifest; do python3 - "$manifest" <<'PY' import json, sys from pathlib import Path path = Path(sys.argv[1]) try: data = json.loads(path.read_text()) except Exception: raise SystemExit(0) if data.get("name") == "memoir": print(path.parent.parent) PY done | head -n 1) fi STORE="${MEMOIR_STORE:-$(bash "$PLUGIN_ROOT/scripts/derive-store-path.sh")}" MEMOIR="$PLUGIN_ROOT/scripts/memoir-cli.sh" ``` -------------------------------- ### Initialize ProllyTreeMemoryStoreManager Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/architecture.md Orchestrates the system components using dependency injection for the store, classifier, and search engine. ```python from memoir.core.memory import ProllyTreeMemoryStoreManager memory_manager = ProllyTreeMemoryStoreManager( prolly_store=store, # Injected dependency classifier=classifier, # Injected dependency search_engine=search_engine # Injected dependency ) ``` -------------------------------- ### Configure External Onboarding Tools Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/claude_code.md Define external tools for processing specific file types by creating a YAML configuration file in the user or project directory. ```yaml # ~/.memoir/onboard-tools.yaml (user-global) # /.memoir/onboard-tools.yaml (project-local; merged after global) audio: - name: whisper command: "whisper {path} --output-format json" timeout_s: 60 image: - name: claude-vision command: "vision-caption.sh {path}" timeout_s: 30 ``` -------------------------------- ### Validate and pack Claude Desktop extension Source: https://github.com/zhangfengcdt/memoir/blob/main/packaging/mcp/README.md Commands to validate the manifest and generate the .mcpb file for one-click installation. ```bash cd packaging/mcp npx @anthropic-ai/mcpb validate manifest.json npx @anthropic-ai/mcpb pack . # → memoir.mcpb (double-click to install) ``` -------------------------------- ### Build Main Timeline Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/examples/context_branching.md Populates the main memory timeline and creates a snapshot for future reference. ```python namespace = "user123" # Store user's actual career path await prolly_store.store_memory_async( namespace, "I graduated with a computer science degree in 2020", "profile.education.degree" ) await prolly_store.store_memory_async( namespace, "I chose to work at a startup doing backend development", "profile.career.current.startup" ) await prolly_store.store_memory_async( namespace, "I've been promoted to senior engineer after 3 years", "profile.career.progression.senior" ) # Create snapshot of main timeline main_snapshot = f"main_timeline_{int(time.time())}" prolly_store.create_time_snapshot(main_snapshot) print(f"Main timeline snapshot: {main_snapshot}") ``` -------------------------------- ### Fetch specific memory keys Source: https://github.com/zhangfengcdt/memoir/blob/main/plugins/claude-code/skills/memory-recall/SKILL.md Retrieve up to 7 exact keys using a single batched get command. ```bash "$MEMOIR" --json -s "$STORE" get ... -n default ``` -------------------------------- ### Manage and search memoir files Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/watch.md Commands for initializing a store, watching directories or files, listing registered paths, scanning for changes, and performing semantic searches. ```bash # Create a store (or reuse an existing one) memoir new ~/.memoir/notes export MEMOIR_STORE=~/.memoir/notes # Point watch at a folder of docs memoir watch add ~/Documents/notes # → walks the folder, parses each file, classifies, indexes for search # Or a single file memoir watch add ~/papers/transformer.pdf -n research # See what's registered memoir watch list # Re-scan (idempotent — only changed files are re-indexed) memoir watch scan ~/Documents/notes # Search the indexed content memoir search "transformer attention mechanism" memoir search "async patterns" -n research -k 10 --json # Tear down memoir watch remove ~/Documents/notes --purge ``` -------------------------------- ### Visualize Storage Flow Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/architecture.md Diagram illustrating the pipeline from memory input to ProllyTree storage. ```mermaid flowchart LR A["Memory Input
I work at X"] --> B["Classification
Classifier analysis"] B --> C["Path Selection
profile.professional.occupation"] C --> D["Aggregation
with similar memories"] D --> E["Storage
ProllyTree"] ``` -------------------------------- ### Manual Memory Capture with Explicit Policy Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/claude_code.md Example of bypassing interactive prompts by providing an explicit merge policy via the CLI. ```bash /memoir:remember "…" -p --merge-policy replace ``` -------------------------------- ### Basic CLI operations Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/quickstart.md Commands for creating a store, remembering information, and recalling memories. ```bash # 1. Create a memoir store memoir new my-memoir-store cd my-memoir-store # 2. Store with an explicit path (offline, no LLM call) memoir remember "Sarah prefers tabs and 2-space indents" -p preferences.coding.style # 3. Store with auto-classification (LLM picks the path; needs API key) memoir remember "I work in Pacific time" # 4. Read back by path (offline) memoir get preferences.coding.style # 5. Semantic search (LLM-backed) memoir recall "what does Sarah prefer?" # 6. Open the visual explorer (auto-opens in your browser) memoir ui ``` -------------------------------- ### Creating Baseline State Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/examples/reproducible_testing.md Initializes the ProllyTreeStore with versioning enabled and populates it with shared baseline memories before creating a snapshot. ```python import asyncio import os import tempfile import time from memoir.store.prolly_adapter import ProllyTreeStore # Initialize store with versioning temp_dir = tempfile.mkdtemp() prolly_path = os.path.join(temp_dir, "memory_store") prolly_store = ProllyTreeStore( path=prolly_path, enable_versioning=True, cache_size=10000, ) namespace = "test_user" # Create shared baseline memories await prolly_store.store_memory_async( namespace, "User is a software engineer with 5 years experience", "profile.professional.occupation.role" ) await prolly_store.store_memory_async( namespace, "User knows Python and JavaScript proficiently", "profile.skills.programming.languages" ) # Create baseline snapshot baseline_snapshot = f"baseline_{int(time.time())}" prolly_store.create_time_snapshot(baseline_snapshot) ``` -------------------------------- ### Create a release branch Source: https://github.com/zhangfengcdt/memoir/blob/main/RELEASING.md Commands to initialize a new release branch from the main branch. ```bash git checkout main git pull git checkout -b release/X.Y.Z ``` -------------------------------- ### Determine Onboarding Procedure Source: https://github.com/zhangfengcdt/memoir/blob/main/plugins/claude-code/skills/memoir-onboard/SKILL.md Detects whether to use codebase:onboard or project:onboard based on the current directory's git status. ```bash bash -c 'source "${CLAUDE_PLUGIN_ROOT}/hooks/common.sh" >/dev/null 2>&1; in_git_repo && echo codebase:onboard || echo project:onboard' ``` -------------------------------- ### Configure MCP for Zed Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/mcp.md Zed uses a context_servers key with a nested command structure in settings.json. ```json { "context_servers": { "memoir": { "command": { "path": "uvx", "args": ["--from", "memoir-ai[mcp]", "memoir-mcp"] } } } } ``` -------------------------------- ### Configure search and monitor metrics Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/faq.md Implement intelligent search engines and retrieve performance metrics for monitoring. ```python # Use intelligent search for memory retrieval from memoir.search.intelligent import IntelligentSearchEngine search_engine = IntelligentSearchEngine(llm=llm, store=store) ``` ```python # Get performance metrics from the low-level manager # (requires the `langmem` extra: pip install memoir-ai[langmem]) from memoir import ProllyTreeMemoryStoreManager stats = memory_manager.get_performance_metrics() print(f"Average search time: {stats['avg_search_ms']}ms") print(f"Classification time: {stats['avg_classification_ms']}ms") ``` -------------------------------- ### Add Marketplace via CLI Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/codex.md Register the Memoir marketplace using the Codex CLI. ```bash codex plugin marketplace add zhangfengcdt/memoir ``` ```bash codex plugin marketplace add /absolute/path/to/memoir ``` -------------------------------- ### Create Alternative Branch Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/examples/context_branching.md Initializes and switches to a new branch for hypothetical memory storage. ```python # Create branch for hypothetical exploration alternative_branch = f"alternative_path_{int(time.time())}" prolly_store.tree.create_branch(alternative_branch) prolly_store.tree.checkout(alternative_branch) print(f"Created branch: {alternative_branch}") print("Now exploring: What if I had joined Google instead?") ``` -------------------------------- ### Configure MCP for VS Code (GitHub Copilot) Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/mcp.md VS Code requires a top-level servers key in the .vscode/mcp.json file. ```json { "servers": { "memoir": { "type": "stdio", "command": "uvx", "args": ["--from", "memoir-ai[mcp]", "memoir-mcp"], "env": { "MEMOIR_STORE": "${userHome}/.memoir/mcp" } } } } ``` -------------------------------- ### Run Quality Assurance Tasks Source: https://github.com/zhangfengcdt/memoir/blob/main/CONTRIBUTING.md Standard commands to format, lint, and test the codebase before committing. ```bash make format # black + isort + ruff --fix make lint # must pass make test # must pass make ci # full pipeline (lint, test, security, docs build) ``` -------------------------------- ### Inspect Plugin Store Source: https://github.com/zhangfengcdt/memoir/blob/main/docs/codex.md Commands to resolve the store path and inspect plugin data using the CLI. ```bash PLUGIN_ROOT=/path/to/memoir/plugins/codex STORE=$("$PLUGIN_ROOT/scripts/derive-store-path.sh" /path/to/project) "$PLUGIN_ROOT/scripts/memoir-cli.sh" -s "$STORE" status "$PLUGIN_ROOT/scripts/memoir-cli.sh" --json -s "$STORE" summarize --keys "*" -n default ``` -------------------------------- ### Initialize Memoir Environment Variables Source: https://github.com/zhangfengcdt/memoir/blob/main/plugins/claude-code/skills/memoir-onboard/SKILL.md Sets the required STORE_PATH and MEMOIR wrapper variables for consistent CLI invocation. ```bash STORE_PATH="${MEMOIR_STORE:-$(bash "${CLAUDE_PLUGIN_ROOT}/scripts/derive-store-path.sh")}" MEMOIR="${CLAUDE_PLUGIN_ROOT}/scripts/memoir-cli.sh" ```